blob: 6c25893758cea74b0071f0ebc0d432da5aaa02fe [file] [log] [blame]
Douglas Gregor5251f1b2008-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 McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036
John McCall7decc9e2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
39static Expr *
40CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41 SourceLocation Loc = SourceLocation()) {
42 Expr *E = new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc);
43 S.DefaultFunctionArrayConversion(E);
44 return E;
45}
46
John McCall5c32be02010-08-24 20:38:10 +000047static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
48 bool InOverloadResolution,
49 StandardConversionSequence &SCS);
50static OverloadingResult
51IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
52 UserDefinedConversionSequence& User,
53 OverloadCandidateSet& Conversions,
54 bool AllowExplicit);
55
56
57static ImplicitConversionSequence::CompareKind
58CompareStandardConversionSequences(Sema &S,
59 const StandardConversionSequence& SCS1,
60 const StandardConversionSequence& SCS2);
61
62static ImplicitConversionSequence::CompareKind
63CompareQualificationConversions(Sema &S,
64 const StandardConversionSequence& SCS1,
65 const StandardConversionSequence& SCS2);
66
67static ImplicitConversionSequence::CompareKind
68CompareDerivedToBaseConversions(Sema &S,
69 const StandardConversionSequence& SCS1,
70 const StandardConversionSequence& SCS2);
71
72
73
Douglas Gregor5251f1b2008-10-21 16:13:35 +000074/// GetConversionCategory - Retrieve the implicit conversion
75/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000076ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000077GetConversionCategory(ImplicitConversionKind Kind) {
78 static const ImplicitConversionCategory
79 Category[(int)ICK_Num_Conversion_Kinds] = {
80 ICC_Identity,
81 ICC_Lvalue_Transformation,
82 ICC_Lvalue_Transformation,
83 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000084 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000085 ICC_Qualification_Adjustment,
86 ICC_Promotion,
87 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000088 ICC_Promotion,
89 ICC_Conversion,
90 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000091 ICC_Conversion,
92 ICC_Conversion,
93 ICC_Conversion,
94 ICC_Conversion,
95 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000096 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000097 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000098 ICC_Conversion,
99 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000100 ICC_Conversion
101 };
102 return Category[(int)Kind];
103}
104
105/// GetConversionRank - Retrieve the implicit conversion rank
106/// corresponding to the given implicit conversion kind.
107ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
108 static const ImplicitConversionRank
109 Rank[(int)ICK_Num_Conversion_Kinds] = {
110 ICR_Exact_Match,
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000115 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000116 ICR_Promotion,
117 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000118 ICR_Promotion,
119 ICR_Conversion,
120 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000126 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000127 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000128 ICR_Conversion,
129 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000130 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000131 };
132 return Rank[(int)Kind];
133}
134
135/// GetImplicitConversionName - Return the name of this kind of
136/// implicit conversion.
137const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000138 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000139 "No conversion",
140 "Lvalue-to-rvalue",
141 "Array-to-pointer",
142 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000143 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000144 "Qualification",
145 "Integral promotion",
146 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000147 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000148 "Integral conversion",
149 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000150 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151 "Floating-integral conversion",
152 "Pointer conversion",
153 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000154 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000155 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000156 "Derived-to-base conversion",
157 "Vector conversion",
158 "Vector splat",
159 "Complex-real conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000160 };
161 return Name[Kind];
162}
163
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000164/// StandardConversionSequence - Set the standard conversion
165/// sequence to the identity conversion.
166void StandardConversionSequence::setAsIdentityConversion() {
167 First = ICK_Identity;
168 Second = ICK_Identity;
169 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000170 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000171 ReferenceBinding = false;
172 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000173 IsLvalueReference = true;
174 BindsToFunctionLvalue = false;
175 BindsToRvalue = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000176 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000177}
178
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000179/// getRank - Retrieve the rank of this standard conversion sequence
180/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
181/// implicit conversions.
182ImplicitConversionRank StandardConversionSequence::getRank() const {
183 ImplicitConversionRank Rank = ICR_Exact_Match;
184 if (GetConversionRank(First) > Rank)
185 Rank = GetConversionRank(First);
186 if (GetConversionRank(Second) > Rank)
187 Rank = GetConversionRank(Second);
188 if (GetConversionRank(Third) > Rank)
189 Rank = GetConversionRank(Third);
190 return Rank;
191}
192
193/// isPointerConversionToBool - Determines whether this conversion is
194/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000195/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000196/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000197bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000198 // Note that FromType has not necessarily been transformed by the
199 // array-to-pointer or function-to-pointer implicit conversions, so
200 // check for their presence as well as checking whether FromType is
201 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000202 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000203 (getFromType()->isPointerType() ||
204 getFromType()->isObjCObjectPointerType() ||
205 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000206 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000207 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
208 return true;
209
210 return false;
211}
212
Douglas Gregor5c407d92008-10-23 00:40:37 +0000213/// isPointerConversionToVoidPointer - Determines whether this
214/// conversion is a conversion of a pointer to a void pointer. This is
215/// used as part of the ranking of standard conversion sequences (C++
216/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000217bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000218StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000219isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000220 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000221 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000222
223 // Note that FromType has not necessarily been transformed by the
224 // array-to-pointer implicit conversion, so check for its presence
225 // and redo the conversion to get a pointer.
226 if (First == ICK_Array_To_Pointer)
227 FromType = Context.getArrayDecayedType(FromType);
228
John McCall75851b12010-10-26 06:40:27 +0000229 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000230 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000231 return ToPtrType->getPointeeType()->isVoidType();
232
233 return false;
234}
235
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000236/// DebugPrint - Print this standard conversion sequence to standard
237/// error. Useful for debugging overloading issues.
238void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000239 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000240 bool PrintedSomething = false;
241 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000242 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000243 PrintedSomething = true;
244 }
245
246 if (Second != ICK_Identity) {
247 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000248 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000249 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000251
252 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000254 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000255 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000256 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000257 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000258 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000259 PrintedSomething = true;
260 }
261
262 if (Third != ICK_Identity) {
263 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000264 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000266 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000267 PrintedSomething = true;
268 }
269
270 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000271 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000272 }
273}
274
275/// DebugPrint - Print this user-defined conversion sequence to standard
276/// error. Useful for debugging overloading issues.
277void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000278 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000279 if (Before.First || Before.Second || Before.Third) {
280 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000281 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000282 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000283 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000284 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000285 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000286 After.DebugPrint();
287 }
288}
289
290/// DebugPrint - Print this implicit conversion sequence to standard
291/// error. Useful for debugging overloading issues.
292void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000293 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000294 switch (ConversionKind) {
295 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000296 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000297 Standard.DebugPrint();
298 break;
299 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000300 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000301 UserDefined.DebugPrint();
302 break;
303 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000304 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000305 break;
John McCall0d1da222010-01-12 00:44:57 +0000306 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000307 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000308 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000309 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000310 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000311 break;
312 }
313
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000314 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000315}
316
John McCall0d1da222010-01-12 00:44:57 +0000317void AmbiguousConversionSequence::construct() {
318 new (&conversions()) ConversionSet();
319}
320
321void AmbiguousConversionSequence::destruct() {
322 conversions().~ConversionSet();
323}
324
325void
326AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
327 FromTypePtr = O.FromTypePtr;
328 ToTypePtr = O.ToTypePtr;
329 new (&conversions()) ConversionSet(O.conversions());
330}
331
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000332namespace {
333 // Structure used by OverloadCandidate::DeductionFailureInfo to store
334 // template parameter and template argument information.
335 struct DFIParamWithArguments {
336 TemplateParameter Param;
337 TemplateArgument FirstArg;
338 TemplateArgument SecondArg;
339 };
340}
341
342/// \brief Convert from Sema's representation of template deduction information
343/// to the form used in overload-candidate information.
344OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000345static MakeDeductionFailureInfo(ASTContext &Context,
346 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000347 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000348 OverloadCandidate::DeductionFailureInfo Result;
349 Result.Result = static_cast<unsigned>(TDK);
350 Result.Data = 0;
351 switch (TDK) {
352 case Sema::TDK_Success:
353 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000354 case Sema::TDK_TooManyArguments:
355 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000356 break;
357
358 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000359 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000360 Result.Data = Info.Param.getOpaqueValue();
361 break;
362
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000363 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000364 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000365 // FIXME: Should allocate from normal heap so that we can free this later.
366 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000367 Saved->Param = Info.Param;
368 Saved->FirstArg = Info.FirstArg;
369 Saved->SecondArg = Info.SecondArg;
370 Result.Data = Saved;
371 break;
372 }
373
374 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000375 Result.Data = Info.take();
376 break;
377
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000378 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000379 case Sema::TDK_FailedOverloadResolution:
380 break;
381 }
382
383 return Result;
384}
John McCall0d1da222010-01-12 00:44:57 +0000385
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000386void OverloadCandidate::DeductionFailureInfo::Destroy() {
387 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
388 case Sema::TDK_Success:
389 case Sema::TDK_InstantiationDepth:
390 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000391 case Sema::TDK_TooManyArguments:
392 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000393 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000394 break;
395
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000396 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000397 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000398 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000399 Data = 0;
400 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000401
402 case Sema::TDK_SubstitutionFailure:
403 // FIXME: Destroy the template arugment list?
404 Data = 0;
405 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000406
Douglas Gregor461761d2010-05-08 18:20:53 +0000407 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000408 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000409 case Sema::TDK_FailedOverloadResolution:
410 break;
411 }
412}
413
414TemplateParameter
415OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
416 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
417 case Sema::TDK_Success:
418 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000419 case Sema::TDK_TooManyArguments:
420 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000421 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000422 return TemplateParameter();
423
424 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000425 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000426 return TemplateParameter::getFromOpaqueValue(Data);
427
428 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000429 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000430 return static_cast<DFIParamWithArguments*>(Data)->Param;
431
432 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000433 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000434 case Sema::TDK_FailedOverloadResolution:
435 break;
436 }
437
438 return TemplateParameter();
439}
Douglas Gregord09efd42010-05-08 20:07:26 +0000440
441TemplateArgumentList *
442OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
443 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
444 case Sema::TDK_Success:
445 case Sema::TDK_InstantiationDepth:
446 case Sema::TDK_TooManyArguments:
447 case Sema::TDK_TooFewArguments:
448 case Sema::TDK_Incomplete:
449 case Sema::TDK_InvalidExplicitArguments:
450 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000451 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000452 return 0;
453
454 case Sema::TDK_SubstitutionFailure:
455 return static_cast<TemplateArgumentList*>(Data);
456
457 // Unhandled
458 case Sema::TDK_NonDeducedMismatch:
459 case Sema::TDK_FailedOverloadResolution:
460 break;
461 }
462
463 return 0;
464}
465
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000466const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
467 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
468 case Sema::TDK_Success:
469 case Sema::TDK_InstantiationDepth:
470 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000471 case Sema::TDK_TooManyArguments:
472 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000473 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000474 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000475 return 0;
476
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000477 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000478 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000479 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
480
Douglas Gregor461761d2010-05-08 18:20:53 +0000481 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000482 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000483 case Sema::TDK_FailedOverloadResolution:
484 break;
485 }
486
487 return 0;
488}
489
490const TemplateArgument *
491OverloadCandidate::DeductionFailureInfo::getSecondArg() {
492 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
493 case Sema::TDK_Success:
494 case Sema::TDK_InstantiationDepth:
495 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000496 case Sema::TDK_TooManyArguments:
497 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000498 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000499 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000500 return 0;
501
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000502 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000503 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000504 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
505
Douglas Gregor461761d2010-05-08 18:20:53 +0000506 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000507 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000508 case Sema::TDK_FailedOverloadResolution:
509 break;
510 }
511
512 return 0;
513}
514
515void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000516 inherited::clear();
517 Functions.clear();
518}
519
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000520// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000521// overload of the declarations in Old. This routine returns false if
522// New and Old cannot be overloaded, e.g., if New has the same
523// signature as some function in Old (C++ 1.3.10) or if the Old
524// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000525// it does return false, MatchedDecl will point to the decl that New
526// cannot be overloaded with. This decl may be a UsingShadowDecl on
527// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000528//
529// Example: Given the following input:
530//
531// void f(int, float); // #1
532// void f(int, int); // #2
533// int f(int, int); // #3
534//
535// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000536// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000537//
John McCall3d988d92009-12-02 08:47:38 +0000538// When we process #2, Old contains only the FunctionDecl for #1. By
539// comparing the parameter types, we see that #1 and #2 are overloaded
540// (since they have different signatures), so this routine returns
541// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000542//
John McCall3d988d92009-12-02 08:47:38 +0000543// When we process #3, Old is an overload set containing #1 and #2. We
544// compare the signatures of #3 to #1 (they're overloaded, so we do
545// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
546// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000547// signature), IsOverload returns false and MatchedDecl will be set to
548// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000549//
550// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
551// into a class by a using declaration. The rules for whether to hide
552// shadow declarations ignore some properties which otherwise figure
553// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000554Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000555Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
556 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000557 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000558 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000559 NamedDecl *OldD = *I;
560
561 bool OldIsUsingDecl = false;
562 if (isa<UsingShadowDecl>(OldD)) {
563 OldIsUsingDecl = true;
564
565 // We can always introduce two using declarations into the same
566 // context, even if they have identical signatures.
567 if (NewIsUsingDecl) continue;
568
569 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
570 }
571
572 // If either declaration was introduced by a using declaration,
573 // we'll need to use slightly different rules for matching.
574 // Essentially, these rules are the normal rules, except that
575 // function templates hide function templates with different
576 // return types or template parameter lists.
577 bool UseMemberUsingDeclRules =
578 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
579
John McCall3d988d92009-12-02 08:47:38 +0000580 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000581 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
582 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
583 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
584 continue;
585 }
586
John McCalldaa3d6b2009-12-09 03:35:25 +0000587 Match = *I;
588 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000589 }
John McCall3d988d92009-12-02 08:47:38 +0000590 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000591 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
592 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
593 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
594 continue;
595 }
596
John McCalldaa3d6b2009-12-09 03:35:25 +0000597 Match = *I;
598 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000599 }
John McCalla8987a2942010-11-10 03:01:53 +0000600 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000601 // We can overload with these, which can show up when doing
602 // redeclaration checks for UsingDecls.
603 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000604 } else if (isa<TagDecl>(OldD)) {
605 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000606 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
607 // Optimistically assume that an unresolved using decl will
608 // overload; if it doesn't, we'll have to diagnose during
609 // template instantiation.
610 } else {
John McCall1f82f242009-11-18 22:49:29 +0000611 // (C++ 13p1):
612 // Only function declarations can be overloaded; object and type
613 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000614 Match = *I;
615 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000616 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000617 }
John McCall1f82f242009-11-18 22:49:29 +0000618
John McCalldaa3d6b2009-12-09 03:35:25 +0000619 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000620}
621
John McCalle9cccd82010-06-16 08:42:20 +0000622bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
623 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000624 // If both of the functions are extern "C", then they are not
625 // overloads.
626 if (Old->isExternC() && New->isExternC())
627 return false;
628
John McCall1f82f242009-11-18 22:49:29 +0000629 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
630 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
631
632 // C++ [temp.fct]p2:
633 // A function template can be overloaded with other function templates
634 // and with normal (non-template) functions.
635 if ((OldTemplate == 0) != (NewTemplate == 0))
636 return true;
637
638 // Is the function New an overload of the function Old?
639 QualType OldQType = Context.getCanonicalType(Old->getType());
640 QualType NewQType = Context.getCanonicalType(New->getType());
641
642 // Compare the signatures (C++ 1.3.10) of the two functions to
643 // determine whether they are overloads. If we find any mismatch
644 // in the signature, they are overloads.
645
646 // If either of these functions is a K&R-style function (no
647 // prototype), then we consider them to have matching signatures.
648 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
649 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
650 return false;
651
John McCall424cec92011-01-19 06:33:43 +0000652 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
653 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000654
655 // The signature of a function includes the types of its
656 // parameters (C++ 1.3.10), which includes the presence or absence
657 // of the ellipsis; see C++ DR 357).
658 if (OldQType != NewQType &&
659 (OldType->getNumArgs() != NewType->getNumArgs() ||
660 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000661 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000662 return true;
663
664 // C++ [temp.over.link]p4:
665 // The signature of a function template consists of its function
666 // signature, its return type and its template parameter list. The names
667 // of the template parameters are significant only for establishing the
668 // relationship between the template parameters and the rest of the
669 // signature.
670 //
671 // We check the return type and template parameter lists for function
672 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000673 //
674 // However, we don't consider either of these when deciding whether
675 // a member introduced by a shadow declaration is hidden.
676 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000677 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
678 OldTemplate->getTemplateParameters(),
679 false, TPL_TemplateMatch) ||
680 OldType->getResultType() != NewType->getResultType()))
681 return true;
682
683 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000684 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000685 //
686 // As part of this, also check whether one of the member functions
687 // is static, in which case they are not overloads (C++
688 // 13.1p2). While not part of the definition of the signature,
689 // this check is important to determine whether these functions
690 // can be overloaded.
691 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
692 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
693 if (OldMethod && NewMethod &&
694 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000695 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
696 OldMethod->getRefQualifier() != NewMethod->getRefQualifier()))
John McCall1f82f242009-11-18 22:49:29 +0000697 return true;
698
699 // The signatures match; this is not an overload.
700 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000701}
702
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000703/// TryImplicitConversion - Attempt to perform an implicit conversion
704/// from the given expression (Expr) to the given type (ToType). This
705/// function returns an implicit conversion sequence that can be used
706/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000707///
708/// void f(float f);
709/// void g(int i) { f(i); }
710///
711/// this routine would produce an implicit conversion sequence to
712/// describe the initialization of f from i, which will be a standard
713/// conversion sequence containing an lvalue-to-rvalue conversion (C++
714/// 4.1) followed by a floating-integral conversion (C++ 4.9).
715//
716/// Note that this routine only determines how the conversion can be
717/// performed; it does not actually perform the conversion. As such,
718/// it will not produce any diagnostics if no conversion is available,
719/// but will instead return an implicit conversion sequence of kind
720/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000721///
722/// If @p SuppressUserConversions, then user-defined conversions are
723/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000724/// If @p AllowExplicit, then explicit user-defined conversions are
725/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000726static ImplicitConversionSequence
727TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
728 bool SuppressUserConversions,
729 bool AllowExplicit,
730 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000731 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000732 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
733 ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000734 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000735 return ICS;
736 }
737
John McCall5c32be02010-08-24 20:38:10 +0000738 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000739 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000740 return ICS;
741 }
742
Douglas Gregor836a7e82010-08-11 02:15:33 +0000743 // C++ [over.ics.user]p4:
744 // A conversion of an expression of class type to the same class
745 // type is given Exact Match rank, and a conversion of an
746 // expression of class type to a base class of that type is
747 // given Conversion rank, in spite of the fact that a copy/move
748 // constructor (i.e., a user-defined conversion function) is
749 // called for those cases.
750 QualType FromType = From->getType();
751 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000752 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
753 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000754 ICS.setStandard();
755 ICS.Standard.setAsIdentityConversion();
756 ICS.Standard.setFromType(FromType);
757 ICS.Standard.setAllToTypes(ToType);
758
759 // We don't actually check at this point whether there is a valid
760 // copy/move constructor, since overloading just assumes that it
761 // exists. When we actually perform initialization, we'll find the
762 // appropriate constructor to copy the returned object, if needed.
763 ICS.Standard.CopyConstructor = 0;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000764
Douglas Gregor5ab11652010-04-17 22:01:05 +0000765 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000766 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000767 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000768
769 return ICS;
770 }
771
772 if (SuppressUserConversions) {
773 // We're not in the case above, so there is no conversion that
774 // we can perform.
775 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000776 return ICS;
777 }
778
779 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000780 OverloadCandidateSet Conversions(From->getExprLoc());
781 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000782 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000783 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000784
785 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000786 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000787 // C++ [over.ics.user]p4:
788 // A conversion of an expression of class type to the same class
789 // type is given Exact Match rank, and a conversion of an
790 // expression of class type to a base class of that type is
791 // given Conversion rank, in spite of the fact that a copy
792 // constructor (i.e., a user-defined conversion function) is
793 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000794 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000795 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000796 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000797 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
798 QualType ToCanon
799 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000800 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000801 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000802 // Turn this into a "standard" conversion sequence, so that it
803 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000804 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000805 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000806 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000807 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000808 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000809 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000810 ICS.Standard.Second = ICK_Derived_To_Base;
811 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000812 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000813
814 // C++ [over.best.ics]p4:
815 // However, when considering the argument of a user-defined
816 // conversion function that is a candidate by 13.3.1.3 when
817 // invoked for the copying of the temporary in the second step
818 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
819 // 13.3.1.6 in all cases, only standard conversion sequences and
820 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000821 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000822 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000823 }
John McCalle8c8cd22010-01-13 22:30:33 +0000824 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000825 ICS.setAmbiguous();
826 ICS.Ambiguous.setFromType(From->getType());
827 ICS.Ambiguous.setToType(ToType);
828 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
829 Cand != Conversions.end(); ++Cand)
830 if (Cand->Viable)
831 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000832 } else {
John McCall65eb8792010-02-25 01:37:24 +0000833 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000834 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000835
836 return ICS;
837}
838
John McCall5c32be02010-08-24 20:38:10 +0000839bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
840 const InitializedEntity &Entity,
841 Expr *Initializer,
842 bool SuppressUserConversions,
843 bool AllowExplicitConversions,
844 bool InOverloadResolution) {
845 ImplicitConversionSequence ICS
846 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
847 SuppressUserConversions,
848 AllowExplicitConversions,
849 InOverloadResolution);
850 if (ICS.isBad()) return true;
851
852 // Perform the actual conversion.
853 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
854 return false;
855}
856
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000857/// PerformImplicitConversion - Perform an implicit conversion of the
858/// expression From to the type ToType. Returns true if there was an
859/// error, false otherwise. The expression From is replaced with the
860/// converted expression. Flavor is the kind of conversion we're
861/// performing, used in the error message. If @p AllowExplicit,
862/// explicit user-defined conversions are permitted.
863bool
864Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
865 AssignmentAction Action, bool AllowExplicit) {
866 ImplicitConversionSequence ICS;
867 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
868}
869
870bool
871Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
872 AssignmentAction Action, bool AllowExplicit,
873 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000874 ICS = clang::TryImplicitConversion(*this, From, ToType,
875 /*SuppressUserConversions=*/false,
876 AllowExplicit,
877 /*InOverloadResolution=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000878 return PerformImplicitConversion(From, ToType, ICS, Action);
879}
880
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000881/// \brief Determine whether the conversion from FromType to ToType is a valid
882/// conversion that strips "noreturn" off the nested function type.
883static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
884 QualType ToType, QualType &ResultTy) {
885 if (Context.hasSameUnqualifiedType(FromType, ToType))
886 return false;
887
John McCall991eb4b2010-12-21 00:44:39 +0000888 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
889 // where F adds one of the following at most once:
890 // - a pointer
891 // - a member pointer
892 // - a block pointer
893 CanQualType CanTo = Context.getCanonicalType(ToType);
894 CanQualType CanFrom = Context.getCanonicalType(FromType);
895 Type::TypeClass TyClass = CanTo->getTypeClass();
896 if (TyClass != CanFrom->getTypeClass()) return false;
897 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
898 if (TyClass == Type::Pointer) {
899 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
900 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
901 } else if (TyClass == Type::BlockPointer) {
902 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
903 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
904 } else if (TyClass == Type::MemberPointer) {
905 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
906 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
907 } else {
908 return false;
909 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000910
John McCall991eb4b2010-12-21 00:44:39 +0000911 TyClass = CanTo->getTypeClass();
912 if (TyClass != CanFrom->getTypeClass()) return false;
913 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
914 return false;
915 }
916
917 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
918 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
919 if (!EInfo.getNoReturn()) return false;
920
921 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
922 assert(QualType(FromFn, 0).isCanonical());
923 if (QualType(FromFn, 0) != CanTo) return false;
924
925 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000926 return true;
927}
Douglas Gregor46188682010-05-18 22:42:18 +0000928
929/// \brief Determine whether the conversion from FromType to ToType is a valid
930/// vector conversion.
931///
932/// \param ICK Will be set to the vector conversion kind, if this is a vector
933/// conversion.
934static bool IsVectorConversion(ASTContext &Context, QualType FromType,
935 QualType ToType, ImplicitConversionKind &ICK) {
936 // We need at least one of these types to be a vector type to have a vector
937 // conversion.
938 if (!ToType->isVectorType() && !FromType->isVectorType())
939 return false;
940
941 // Identical types require no conversions.
942 if (Context.hasSameUnqualifiedType(FromType, ToType))
943 return false;
944
945 // There are no conversions between extended vector types, only identity.
946 if (ToType->isExtVectorType()) {
947 // There are no conversions between extended vector types other than the
948 // identity conversion.
949 if (FromType->isExtVectorType())
950 return false;
951
952 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000953 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000954 ICK = ICK_Vector_Splat;
955 return true;
956 }
957 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000958
959 // We can perform the conversion between vector types in the following cases:
960 // 1)vector types are equivalent AltiVec and GCC vector types
961 // 2)lax vector conversions are permitted and the vector types are of the
962 // same size
963 if (ToType->isVectorType() && FromType->isVectorType()) {
964 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000965 (Context.getLangOptions().LaxVectorConversions &&
966 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000967 ICK = ICK_Vector_Conversion;
968 return true;
969 }
Douglas Gregor46188682010-05-18 22:42:18 +0000970 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000971
Douglas Gregor46188682010-05-18 22:42:18 +0000972 return false;
973}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000974
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000975/// IsStandardConversion - Determines whether there is a standard
976/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
977/// expression From to the type ToType. Standard conversion sequences
978/// only consider non-class types; for conversions that involve class
979/// types, use TryImplicitConversion. If a conversion exists, SCS will
980/// contain the standard conversion sequence required to perform this
981/// conversion and this routine will return true. Otherwise, this
982/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +0000983static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
984 bool InOverloadResolution,
985 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000986 QualType FromType = From->getType();
John McCall5c32be02010-08-24 20:38:10 +0000987
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000988 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000989 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000990 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000991 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000992 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000993 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000994
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000995 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000996 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000997 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +0000998 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000999 return false;
1000
Mike Stump11289f42009-09-09 15:08:12 +00001001 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001002 }
1003
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001004 // The first conversion can be an lvalue-to-rvalue conversion,
1005 // array-to-pointer conversion, or function-to-pointer conversion
1006 // (C++ 4p1).
1007
John McCall5c32be02010-08-24 20:38:10 +00001008 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001009 DeclAccessPair AccessPair;
1010 if (FunctionDecl *Fn
John McCall5c32be02010-08-24 20:38:10 +00001011 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1012 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001013 // We were able to resolve the address of the overloaded function,
1014 // so we can convert to the type of that function.
1015 FromType = Fn->getType();
1016 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
1017 if (!Method->isStatic()) {
John McCall424cec92011-01-19 06:33:43 +00001018 const Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +00001019 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1020 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +00001021 }
1022 }
1023
1024 // If the "from" expression takes the address of the overloaded
1025 // function, update the type of the resulting expression accordingly.
1026 if (FromType->getAs<FunctionType>())
1027 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +00001028 if (UnOp->getOpcode() == UO_AddrOf)
John McCall5c32be02010-08-24 20:38:10 +00001029 FromType = S.Context.getPointerType(FromType);
Douglas Gregor980fb162010-04-29 18:24:40 +00001030
1031 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00001032 assert(S.Context.hasSameType(FromType,
1033 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001034 } else {
1035 return false;
1036 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001037 }
Mike Stump11289f42009-09-09 15:08:12 +00001038 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001039 // An lvalue (3.10) of a non-function, non-array type T can be
1040 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001041 bool argIsLValue = From->isLValue();
1042 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001043 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001044 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001045 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001046
1047 // If T is a non-class type, the type of the rvalue is the
1048 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001049 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1050 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001051 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001052 } else if (FromType->isArrayType()) {
1053 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001054 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001055
1056 // An lvalue or rvalue of type "array of N T" or "array of unknown
1057 // bound of T" can be converted to an rvalue of type "pointer to
1058 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001059 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001060
John McCall5c32be02010-08-24 20:38:10 +00001061 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001063 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001064
1065 // For the purpose of ranking in overload resolution
1066 // (13.3.3.1.1), this conversion is considered an
1067 // array-to-pointer conversion followed by a qualification
1068 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001069 SCS.Second = ICK_Identity;
1070 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001071 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001072 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001073 }
John McCall086a4642010-11-24 05:12:34 +00001074 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001075 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001076 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001077
1078 // An lvalue of function type T can be converted to an rvalue of
1079 // type "pointer to T." The result is a pointer to the
1080 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001081 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001082 } else {
1083 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001084 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001085 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001086 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001087
1088 // The second conversion can be an integral promotion, floating
1089 // point promotion, integral conversion, floating point conversion,
1090 // floating-integral conversion, pointer conversion,
1091 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001092 // For overloading in C, this can also be a "compatible-type"
1093 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001094 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001095 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001096 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001097 // The unqualified versions of the types are the same: there's no
1098 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001099 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001100 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001101 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001102 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001103 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001104 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001105 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001106 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001107 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001108 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001109 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001110 SCS.Second = ICK_Complex_Promotion;
1111 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001112 } else if (ToType->isBooleanType() &&
1113 (FromType->isArithmeticType() ||
1114 FromType->isAnyPointerType() ||
1115 FromType->isBlockPointerType() ||
1116 FromType->isMemberPointerType() ||
1117 FromType->isNullPtrType())) {
1118 // Boolean conversions (C++ 4.12).
1119 SCS.Second = ICK_Boolean_Conversion;
1120 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001121 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001122 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001123 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001124 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001125 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001126 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001127 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001128 SCS.Second = ICK_Complex_Conversion;
1129 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001130 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1131 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001132 // Complex-real conversions (C99 6.3.1.7)
1133 SCS.Second = ICK_Complex_Real;
1134 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001135 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001136 // Floating point conversions (C++ 4.8).
1137 SCS.Second = ICK_Floating_Conversion;
1138 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001139 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001140 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001141 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001142 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001143 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001144 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001145 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001146 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1147 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001148 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001149 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001150 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall5c32be02010-08-24 20:38:10 +00001151 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1152 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001153 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001154 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001155 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001156 SCS.Second = SecondICK;
1157 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001158 } else if (!S.getLangOptions().CPlusPlus &&
1159 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001160 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001161 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001162 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001163 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001164 // Treat a conversion that strips "noreturn" as an identity conversion.
1165 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001166 } else {
1167 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001168 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001169 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001170 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001171
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001172 QualType CanonFrom;
1173 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001174 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall5c32be02010-08-24 20:38:10 +00001175 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001176 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001177 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001178 CanonFrom = S.Context.getCanonicalType(FromType);
1179 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001180 } else {
1181 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001182 SCS.Third = ICK_Identity;
1183
Mike Stump11289f42009-09-09 15:08:12 +00001184 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001185 // [...] Any difference in top-level cv-qualification is
1186 // subsumed by the initialization itself and does not constitute
1187 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001188 CanonFrom = S.Context.getCanonicalType(FromType);
1189 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001190 if (CanonFrom.getLocalUnqualifiedType()
1191 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001192 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1193 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001194 FromType = ToType;
1195 CanonFrom = CanonTo;
1196 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001197 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001198 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001199
1200 // If we have not converted the argument type to the parameter type,
1201 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001202 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001203 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001204
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001205 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001206}
1207
1208/// IsIntegralPromotion - Determines whether the conversion from the
1209/// expression From (whose potentially-adjusted type is FromType) to
1210/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1211/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001212bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001213 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001214 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001215 if (!To) {
1216 return false;
1217 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001218
1219 // An rvalue of type char, signed char, unsigned char, short int, or
1220 // unsigned short int can be converted to an rvalue of type int if
1221 // int can represent all the values of the source type; otherwise,
1222 // the source rvalue can be converted to an rvalue of type unsigned
1223 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001224 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1225 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001226 if (// We can promote any signed, promotable integer type to an int
1227 (FromType->isSignedIntegerType() ||
1228 // We can promote any unsigned integer type whose size is
1229 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001230 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001231 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001232 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001233 }
1234
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001235 return To->getKind() == BuiltinType::UInt;
1236 }
1237
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001238 // C++0x [conv.prom]p3:
1239 // A prvalue of an unscoped enumeration type whose underlying type is not
1240 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1241 // following types that can represent all the values of the enumeration
1242 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1243 // unsigned int, long int, unsigned long int, long long int, or unsigned
1244 // long long int. If none of the types in that list can represent all the
1245 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1246 // type can be converted to an rvalue a prvalue of the extended integer type
1247 // with lowest integer conversion rank (4.13) greater than the rank of long
1248 // long in which all the values of the enumeration can be represented. If
1249 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001250 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1251 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1252 // provided for a scoped enumeration.
1253 if (FromEnumType->getDecl()->isScoped())
1254 return false;
1255
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001256 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001257 if (ToType->isIntegerType() &&
1258 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001259 return Context.hasSameUnqualifiedType(ToType,
1260 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001261 }
John McCall56774992009-12-09 09:09:27 +00001262
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001263 // C++0x [conv.prom]p2:
1264 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1265 // to an rvalue a prvalue of the first of the following types that can
1266 // represent all the values of its underlying type: int, unsigned int,
1267 // long int, unsigned long int, long long int, or unsigned long long int.
1268 // If none of the types in that list can represent all the values of its
1269 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1270 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1271 // type.
1272 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1273 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001274 // Determine whether the type we're converting from is signed or
1275 // unsigned.
1276 bool FromIsSigned;
1277 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001278
1279 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1280 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001281
1282 // The types we'll try to promote to, in the appropriate
1283 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001284 QualType PromoteTypes[6] = {
1285 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001286 Context.LongTy, Context.UnsignedLongTy ,
1287 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001288 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001289 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001290 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1291 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001292 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001293 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1294 // We found the type that we can promote to. If this is the
1295 // type we wanted, we have a promotion. Otherwise, no
1296 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001297 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001298 }
1299 }
1300 }
1301
1302 // An rvalue for an integral bit-field (9.6) can be converted to an
1303 // rvalue of type int if int can represent all the values of the
1304 // bit-field; otherwise, it can be converted to unsigned int if
1305 // unsigned int can represent all the values of the bit-field. If
1306 // the bit-field is larger yet, no integral promotion applies to
1307 // it. If the bit-field has an enumerated type, it is treated as any
1308 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001309 // FIXME: We should delay checking of bit-fields until we actually perform the
1310 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001311 using llvm::APSInt;
1312 if (From)
1313 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001314 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001315 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001316 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1317 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1318 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001319
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001320 // Are we promoting to an int from a bitfield that fits in an int?
1321 if (BitWidth < ToSize ||
1322 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1323 return To->getKind() == BuiltinType::Int;
1324 }
Mike Stump11289f42009-09-09 15:08:12 +00001325
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001326 // Are we promoting to an unsigned int from an unsigned bitfield
1327 // that fits into an unsigned int?
1328 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1329 return To->getKind() == BuiltinType::UInt;
1330 }
Mike Stump11289f42009-09-09 15:08:12 +00001331
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001332 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001333 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001334 }
Mike Stump11289f42009-09-09 15:08:12 +00001335
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001336 // An rvalue of type bool can be converted to an rvalue of type int,
1337 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001338 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001339 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001340 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001341
1342 return false;
1343}
1344
1345/// IsFloatingPointPromotion - Determines whether the conversion from
1346/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1347/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001348bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001349 /// An rvalue of type float can be converted to an rvalue of type
1350 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001351 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1352 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001353 if (FromBuiltin->getKind() == BuiltinType::Float &&
1354 ToBuiltin->getKind() == BuiltinType::Double)
1355 return true;
1356
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001357 // C99 6.3.1.5p1:
1358 // When a float is promoted to double or long double, or a
1359 // double is promoted to long double [...].
1360 if (!getLangOptions().CPlusPlus &&
1361 (FromBuiltin->getKind() == BuiltinType::Float ||
1362 FromBuiltin->getKind() == BuiltinType::Double) &&
1363 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1364 return true;
1365 }
1366
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001367 return false;
1368}
1369
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001370/// \brief Determine if a conversion is a complex promotion.
1371///
1372/// A complex promotion is defined as a complex -> complex conversion
1373/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001374/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001375bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001376 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001377 if (!FromComplex)
1378 return false;
1379
John McCall9dd450b2009-09-21 23:43:11 +00001380 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001381 if (!ToComplex)
1382 return false;
1383
1384 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001385 ToComplex->getElementType()) ||
1386 IsIntegralPromotion(0, FromComplex->getElementType(),
1387 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001388}
1389
Douglas Gregor237f96c2008-11-26 23:31:11 +00001390/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1391/// the pointer type FromPtr to a pointer to type ToPointee, with the
1392/// same type qualifiers as FromPtr has on its pointee type. ToType,
1393/// if non-empty, will be a pointer to ToType that may or may not have
1394/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001395static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001396BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001397 QualType ToPointee, QualType ToType,
1398 ASTContext &Context) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001399 assert((FromPtr->getTypeClass() == Type::Pointer ||
1400 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1401 "Invalid similarly-qualified pointer type");
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001402
1403 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1404 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1405 return ToType.getUnqualifiedType();
1406
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001407 QualType CanonFromPointee
1408 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001409 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001410 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001411
1412 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001413 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001414 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001415 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001416 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001417
1418 // Build a pointer to ToPointee. It has the right qualifiers
1419 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001420 if (isa<ObjCObjectPointerType>(ToType))
1421 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001422 return Context.getPointerType(ToPointee);
1423 }
1424
1425 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001426 QualType QualifiedCanonToPointee
1427 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001428
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001429 if (isa<ObjCObjectPointerType>(ToType))
1430 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1431 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001432}
1433
Mike Stump11289f42009-09-09 15:08:12 +00001434static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001435 bool InOverloadResolution,
1436 ASTContext &Context) {
1437 // Handle value-dependent integral null pointer constants correctly.
1438 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1439 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001440 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001441 return !InOverloadResolution;
1442
Douglas Gregor56751b52009-09-25 04:25:58 +00001443 return Expr->isNullPointerConstant(Context,
1444 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1445 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001446}
Mike Stump11289f42009-09-09 15:08:12 +00001447
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001448/// IsPointerConversion - Determines whether the conversion of the
1449/// expression From, which has the (possibly adjusted) type FromType,
1450/// can be converted to the type ToType via a pointer conversion (C++
1451/// 4.10). If so, returns true and places the converted type (that
1452/// might differ from ToType in its cv-qualifiers at some level) into
1453/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001454///
Douglas Gregora29dc052008-11-27 01:19:21 +00001455/// This routine also supports conversions to and from block pointers
1456/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1457/// pointers to interfaces. FIXME: Once we've determined the
1458/// appropriate overloading rules for Objective-C, we may want to
1459/// split the Objective-C checks into a different routine; however,
1460/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001461/// conversions, so for now they live here. IncompatibleObjC will be
1462/// set if the conversion is an allowed Objective-C conversion that
1463/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001464bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001465 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001466 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001467 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001468 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001469 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1470 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001471 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001472
Mike Stump11289f42009-09-09 15:08:12 +00001473 // Conversion from a null pointer constant to any Objective-C pointer type.
1474 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001475 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001476 ConvertedType = ToType;
1477 return true;
1478 }
1479
Douglas Gregor231d1c62008-11-27 00:15:41 +00001480 // Blocks: Block pointers can be converted to void*.
1481 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001482 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001483 ConvertedType = ToType;
1484 return true;
1485 }
1486 // Blocks: A null pointer constant can be converted to a block
1487 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001488 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001489 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001490 ConvertedType = ToType;
1491 return true;
1492 }
1493
Sebastian Redl576fd422009-05-10 18:38:11 +00001494 // If the left-hand-side is nullptr_t, the right side can be a null
1495 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001496 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001497 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001498 ConvertedType = ToType;
1499 return true;
1500 }
1501
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001502 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001503 if (!ToTypePtr)
1504 return false;
1505
1506 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001507 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001508 ConvertedType = ToType;
1509 return true;
1510 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001511
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001512 // Beyond this point, both types need to be pointers
1513 // , including objective-c pointers.
1514 QualType ToPointeeType = ToTypePtr->getPointeeType();
1515 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001516 ConvertedType = BuildSimilarlyQualifiedPointerType(
1517 FromType->getAs<ObjCObjectPointerType>(),
1518 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001519 ToType, Context);
1520 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001521 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001522 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001523 if (!FromTypePtr)
1524 return false;
1525
1526 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001527
Douglas Gregorfb640862010-08-18 21:25:30 +00001528 // If the unqualified pointee types are the same, this can't be a
1529 // pointer conversion, so don't do all of the work below.
1530 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1531 return false;
1532
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001533 // An rvalue of type "pointer to cv T," where T is an object type,
1534 // can be converted to an rvalue of type "pointer to cv void" (C++
1535 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001536 if (FromPointeeType->isIncompleteOrObjectType() &&
1537 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001538 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001539 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001540 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001541 return true;
1542 }
1543
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001544 // When we're overloading in C, we allow a special kind of pointer
1545 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001546 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001547 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001548 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001549 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001550 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001551 return true;
1552 }
1553
Douglas Gregor5c407d92008-10-23 00:40:37 +00001554 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001555 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001556 // An rvalue of type "pointer to cv D," where D is a class type,
1557 // can be converted to an rvalue of type "pointer to cv B," where
1558 // B is a base class (clause 10) of D. If B is an inaccessible
1559 // (clause 11) or ambiguous (10.2) base class of D, a program that
1560 // necessitates this conversion is ill-formed. The result of the
1561 // conversion is a pointer to the base class sub-object of the
1562 // derived class object. The null pointer value is converted to
1563 // the null pointer value of the destination type.
1564 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001565 // Note that we do not check for ambiguity or inaccessibility
1566 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001567 if (getLangOptions().CPlusPlus &&
1568 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001569 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001570 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001571 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001572 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001573 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001574 ToType, Context);
1575 return true;
1576 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001577
Douglas Gregora119f102008-12-19 19:13:09 +00001578 return false;
1579}
1580
1581/// isObjCPointerConversion - Determines whether this is an
1582/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1583/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001584bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001585 QualType& ConvertedType,
1586 bool &IncompatibleObjC) {
1587 if (!getLangOptions().ObjC1)
1588 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001589
Steve Naroff7cae42b2009-07-10 23:34:53 +00001590 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001591 const ObjCObjectPointerType* ToObjCPtr =
1592 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001593 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001594 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001595
Steve Naroff7cae42b2009-07-10 23:34:53 +00001596 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001597 // If the pointee types are the same (ignoring qualifications),
1598 // then this is not a pointer conversion.
1599 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1600 FromObjCPtr->getPointeeType()))
1601 return false;
1602
Steve Naroff1329fa02009-07-15 18:40:39 +00001603 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001604 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001605 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001606 ConvertedType = ToType;
1607 return true;
1608 }
1609 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001610 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001611 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001612 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001613 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001614 ConvertedType = ToType;
1615 return true;
1616 }
1617 // Objective C++: We're able to convert from a pointer to an
1618 // interface to a pointer to a different interface.
1619 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001620 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1621 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1622 if (getLangOptions().CPlusPlus && LHS && RHS &&
1623 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1624 FromObjCPtr->getPointeeType()))
1625 return false;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001626 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1627 ToObjCPtr->getPointeeType(),
1628 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001629 return true;
1630 }
1631
1632 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1633 // Okay: this is some kind of implicit downcast of Objective-C
1634 // interfaces, which is permitted. However, we're going to
1635 // complain about it.
1636 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001637 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1638 ToObjCPtr->getPointeeType(),
1639 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001640 return true;
1641 }
Mike Stump11289f42009-09-09 15:08:12 +00001642 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001643 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001644 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001645 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001646 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001647 else if (const BlockPointerType *ToBlockPtr =
1648 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001649 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001650 // to a block pointer type.
1651 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1652 ConvertedType = ToType;
1653 return true;
1654 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001655 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001656 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001657 else if (FromType->getAs<BlockPointerType>() &&
1658 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1659 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001660 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001661 ConvertedType = ToType;
1662 return true;
1663 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001664 else
Douglas Gregora119f102008-12-19 19:13:09 +00001665 return false;
1666
Douglas Gregor033f56d2008-12-23 00:53:59 +00001667 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001668 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001669 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001670 else if (const BlockPointerType *FromBlockPtr =
1671 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001672 FromPointeeType = FromBlockPtr->getPointeeType();
1673 else
Douglas Gregora119f102008-12-19 19:13:09 +00001674 return false;
1675
Douglas Gregora119f102008-12-19 19:13:09 +00001676 // If we have pointers to pointers, recursively check whether this
1677 // is an Objective-C conversion.
1678 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1679 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1680 IncompatibleObjC)) {
1681 // We always complain about this conversion.
1682 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001683 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregora119f102008-12-19 19:13:09 +00001684 return true;
1685 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001686 // Allow conversion of pointee being objective-c pointer to another one;
1687 // as in I* to id.
1688 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1689 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1690 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1691 IncompatibleObjC)) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001692 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001693 return true;
1694 }
1695
Douglas Gregor033f56d2008-12-23 00:53:59 +00001696 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001697 // differences in the argument and result types are in Objective-C
1698 // pointer conversions. If so, we permit the conversion (but
1699 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001700 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001701 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001702 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001703 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001704 if (FromFunctionType && ToFunctionType) {
1705 // If the function types are exactly the same, this isn't an
1706 // Objective-C pointer conversion.
1707 if (Context.getCanonicalType(FromPointeeType)
1708 == Context.getCanonicalType(ToPointeeType))
1709 return false;
1710
1711 // Perform the quick checks that will tell us whether these
1712 // function types are obviously different.
1713 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1714 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1715 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1716 return false;
1717
1718 bool HasObjCConversion = false;
1719 if (Context.getCanonicalType(FromFunctionType->getResultType())
1720 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1721 // Okay, the types match exactly. Nothing to do.
1722 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1723 ToFunctionType->getResultType(),
1724 ConvertedType, IncompatibleObjC)) {
1725 // Okay, we have an Objective-C pointer conversion.
1726 HasObjCConversion = true;
1727 } else {
1728 // Function types are too different. Abort.
1729 return false;
1730 }
Mike Stump11289f42009-09-09 15:08:12 +00001731
Douglas Gregora119f102008-12-19 19:13:09 +00001732 // Check argument types.
1733 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1734 ArgIdx != NumArgs; ++ArgIdx) {
1735 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1736 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1737 if (Context.getCanonicalType(FromArgType)
1738 == Context.getCanonicalType(ToArgType)) {
1739 // Okay, the types match exactly. Nothing to do.
1740 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1741 ConvertedType, IncompatibleObjC)) {
1742 // Okay, we have an Objective-C pointer conversion.
1743 HasObjCConversion = true;
1744 } else {
1745 // Argument types are too different. Abort.
1746 return false;
1747 }
1748 }
1749
1750 if (HasObjCConversion) {
1751 // We had an Objective-C conversion. Allow this pointer
1752 // conversion, but complain about it.
1753 ConvertedType = ToType;
1754 IncompatibleObjC = true;
1755 return true;
1756 }
1757 }
1758
Sebastian Redl72b597d2009-01-25 19:43:20 +00001759 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001760}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001761
1762/// FunctionArgTypesAreEqual - This routine checks two function proto types
1763/// for equlity of their argument types. Caller has already checked that
1764/// they have same number of arguments. This routine assumes that Objective-C
1765/// pointer types which only differ in their protocol qualifiers are equal.
John McCall424cec92011-01-19 06:33:43 +00001766bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
1767 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001768 if (!getLangOptions().ObjC1)
1769 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1770 NewType->arg_type_begin());
1771
1772 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1773 N = NewType->arg_type_begin(),
1774 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1775 QualType ToType = (*O);
1776 QualType FromType = (*N);
1777 if (ToType != FromType) {
1778 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1779 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001780 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1781 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1782 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1783 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001784 continue;
1785 }
John McCall8b07ec22010-05-15 11:32:37 +00001786 else if (const ObjCObjectPointerType *PTTo =
1787 ToType->getAs<ObjCObjectPointerType>()) {
1788 if (const ObjCObjectPointerType *PTFr =
1789 FromType->getAs<ObjCObjectPointerType>())
1790 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1791 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001792 }
1793 return false;
1794 }
1795 }
1796 return true;
1797}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001798
Douglas Gregor39c16d42008-10-24 04:54:22 +00001799/// CheckPointerConversion - Check the pointer conversion from the
1800/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001801/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001802/// conversions for which IsPointerConversion has already returned
1803/// true. It returns true and produces a diagnostic if there was an
1804/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001805bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001806 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001807 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001808 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001809 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001810 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001811
John McCall8cb679e2010-11-15 09:13:47 +00001812 Kind = CK_BitCast;
1813
Douglas Gregor4038cf42010-06-08 17:35:15 +00001814 if (CXXBoolLiteralExpr* LitBool
1815 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001816 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregor4038cf42010-06-08 17:35:15 +00001817 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1818 << ToType;
1819
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001820 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1821 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001822 QualType FromPointeeType = FromPtrType->getPointeeType(),
1823 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001824
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001825 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1826 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001827 // We must have a derived-to-base conversion. Check an
1828 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001829 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1830 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001831 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001832 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001833 return true;
1834
1835 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00001836 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001837 }
1838 }
Mike Stump11289f42009-09-09 15:08:12 +00001839 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00001840 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001841 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001842 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001843 // Objective-C++ conversions are always okay.
1844 // FIXME: We should have a different class of conversions for the
1845 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001846 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001847 return false;
John McCall8cb679e2010-11-15 09:13:47 +00001848 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001849 }
John McCall8cb679e2010-11-15 09:13:47 +00001850
1851 // We shouldn't fall into this case unless it's valid for other
1852 // reasons.
1853 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1854 Kind = CK_NullToPointer;
1855
Douglas Gregor39c16d42008-10-24 04:54:22 +00001856 return false;
1857}
1858
Sebastian Redl72b597d2009-01-25 19:43:20 +00001859/// IsMemberPointerConversion - Determines whether the conversion of the
1860/// expression From, which has the (possibly adjusted) type FromType, can be
1861/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1862/// If so, returns true and places the converted type (that might differ from
1863/// ToType in its cv-qualifiers at some level) into ConvertedType.
1864bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001865 QualType ToType,
1866 bool InOverloadResolution,
1867 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001868 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001869 if (!ToTypePtr)
1870 return false;
1871
1872 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001873 if (From->isNullPointerConstant(Context,
1874 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1875 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001876 ConvertedType = ToType;
1877 return true;
1878 }
1879
1880 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001881 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001882 if (!FromTypePtr)
1883 return false;
1884
1885 // A pointer to member of B can be converted to a pointer to member of D,
1886 // where D is derived from B (C++ 4.11p2).
1887 QualType FromClass(FromTypePtr->getClass(), 0);
1888 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001889
Douglas Gregor7f6ae692010-12-21 21:40:41 +00001890 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
1891 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
1892 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001893 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1894 ToClass.getTypePtr());
1895 return true;
1896 }
1897
1898 return false;
1899}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001900
Sebastian Redl72b597d2009-01-25 19:43:20 +00001901/// CheckMemberPointerConversion - Check the member pointer conversion from the
1902/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001903/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001904/// for which IsMemberPointerConversion has already returned true. It returns
1905/// true and produces a diagnostic if there was an error, or returns false
1906/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001907bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001908 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001909 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001910 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001911 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001912 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001913 if (!FromPtrType) {
1914 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001915 assert(From->isNullPointerConstant(Context,
1916 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001917 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00001918 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001919 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001920 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001921
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001922 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001923 assert(ToPtrType && "No member pointer cast has a target type "
1924 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001925
Sebastian Redled8f2002009-01-28 18:33:18 +00001926 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1927 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001928
Sebastian Redled8f2002009-01-28 18:33:18 +00001929 // FIXME: What about dependent types?
1930 assert(FromClass->isRecordType() && "Pointer into non-class.");
1931 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001932
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001933 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001934 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001935 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1936 assert(DerivationOkay &&
1937 "Should not have been called if derivation isn't OK.");
1938 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001939
Sebastian Redled8f2002009-01-28 18:33:18 +00001940 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1941 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001942 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1943 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1944 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1945 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001946 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001947
Douglas Gregor89ee6822009-02-28 01:32:25 +00001948 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001949 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1950 << FromClass << ToClass << QualType(VBase, 0)
1951 << From->getSourceRange();
1952 return true;
1953 }
1954
John McCall5b0829a2010-02-10 09:31:12 +00001955 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001956 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1957 Paths.front(),
1958 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001959
Anders Carlssond7923c62009-08-22 23:33:40 +00001960 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001961 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001962 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001963 return false;
1964}
1965
Douglas Gregor9a657932008-10-21 23:43:52 +00001966/// IsQualificationConversion - Determines whether the conversion from
1967/// an rvalue of type FromType to ToType is a qualification conversion
1968/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001969bool
1970Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001971 FromType = Context.getCanonicalType(FromType);
1972 ToType = Context.getCanonicalType(ToType);
1973
1974 // If FromType and ToType are the same type, this is not a
1975 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001976 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001977 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001978
Douglas Gregor9a657932008-10-21 23:43:52 +00001979 // (C++ 4.4p4):
1980 // A conversion can add cv-qualifiers at levels other than the first
1981 // in multi-level pointers, subject to the following rules: [...]
1982 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001983 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001984 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001985 // Within each iteration of the loop, we check the qualifiers to
1986 // determine if this still looks like a qualification
1987 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001988 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001989 // until there are no more pointers or pointers-to-members left to
1990 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001991 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001992
1993 // -- for every j > 0, if const is in cv 1,j then const is in cv
1994 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001995 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001996 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001997
Douglas Gregor9a657932008-10-21 23:43:52 +00001998 // -- if the cv 1,j and cv 2,j are different, then const is in
1999 // every cv for 0 < k < j.
2000 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002001 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002002 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002003
Douglas Gregor9a657932008-10-21 23:43:52 +00002004 // Keep track of whether all prior cv-qualifiers in the "to" type
2005 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002006 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00002007 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002008 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002009
2010 // We are left with FromType and ToType being the pointee types
2011 // after unwrapping the original FromType and ToType the same number
2012 // of types. If we unwrapped any pointers, and if FromType and
2013 // ToType have the same unqualified type (since we checked
2014 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002015 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002016}
2017
Douglas Gregor576e98c2009-01-30 23:27:23 +00002018/// Determines whether there is a user-defined conversion sequence
2019/// (C++ [over.ics.user]) that converts expression From to the type
2020/// ToType. If such a conversion exists, User will contain the
2021/// user-defined conversion sequence that performs such a conversion
2022/// and this routine will return true. Otherwise, this routine returns
2023/// false and User is unspecified.
2024///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002025/// \param AllowExplicit true if the conversion should consider C++0x
2026/// "explicit" conversion functions as well as non-explicit conversion
2027/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002028static OverloadingResult
2029IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2030 UserDefinedConversionSequence& User,
2031 OverloadCandidateSet& CandidateSet,
2032 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002033 // Whether we will only visit constructors.
2034 bool ConstructorsOnly = false;
2035
2036 // If the type we are conversion to is a class type, enumerate its
2037 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002038 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002039 // C++ [over.match.ctor]p1:
2040 // When objects of class type are direct-initialized (8.5), or
2041 // copy-initialized from an expression of the same or a
2042 // derived class type (8.5), overload resolution selects the
2043 // constructor. [...] For copy-initialization, the candidate
2044 // functions are all the converting constructors (12.3.1) of
2045 // that class. The argument list is the expression-list within
2046 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002047 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002048 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002049 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002050 ConstructorsOnly = true;
2051
John McCall5c32be02010-08-24 20:38:10 +00002052 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002053 // We're not going to find any constructors.
2054 } else if (CXXRecordDecl *ToRecordDecl
2055 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002056 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002057 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002058 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002059 NamedDecl *D = *Con;
2060 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2061
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002062 // Find the constructor (which may be a template).
2063 CXXConstructorDecl *Constructor = 0;
2064 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002065 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002066 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002067 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002068 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2069 else
John McCalla0296f72010-03-19 07:35:19 +00002070 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002071
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002072 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002073 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002074 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002075 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2076 /*ExplicitArgs*/ 0,
2077 &From, 1, CandidateSet,
2078 /*SuppressUserConversions=*/
2079 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002080 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002081 // Allow one user-defined conversion when user specifies a
2082 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002083 S.AddOverloadCandidate(Constructor, FoundDecl,
2084 &From, 1, CandidateSet,
2085 /*SuppressUserConversions=*/
2086 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002087 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002088 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002089 }
2090 }
2091
Douglas Gregor5ab11652010-04-17 22:01:05 +00002092 // Enumerate conversion functions, if we're allowed to.
2093 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002094 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2095 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002096 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002097 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002098 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002099 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002100 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2101 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002102 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002103 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002104 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002105 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002106 DeclAccessPair FoundDecl = I.getPair();
2107 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002108 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2109 if (isa<UsingShadowDecl>(D))
2110 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2111
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002112 CXXConversionDecl *Conv;
2113 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002114 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2115 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002116 else
John McCallda4458e2010-03-31 01:36:47 +00002117 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002118
2119 if (AllowExplicit || !Conv->isExplicit()) {
2120 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002121 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2122 ActingContext, From, ToType,
2123 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002124 else
John McCall5c32be02010-08-24 20:38:10 +00002125 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2126 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002127 }
2128 }
2129 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002130 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002131
2132 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002133 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002134 case OR_Success:
2135 // Record the standard conversion we used and the conversion function.
2136 if (CXXConstructorDecl *Constructor
2137 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2138 // C++ [over.ics.user]p1:
2139 // If the user-defined conversion is specified by a
2140 // constructor (12.3.1), the initial standard conversion
2141 // sequence converts the source type to the type required by
2142 // the argument of the constructor.
2143 //
2144 QualType ThisType = Constructor->getThisType(S.Context);
2145 if (Best->Conversions[0].isEllipsis())
2146 User.EllipsisConversion = true;
2147 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002148 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002149 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002150 }
John McCall5c32be02010-08-24 20:38:10 +00002151 User.ConversionFunction = Constructor;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002152 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002153 User.After.setAsIdentityConversion();
2154 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2155 User.After.setAllToTypes(ToType);
2156 return OR_Success;
2157 } else if (CXXConversionDecl *Conversion
2158 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2159 // C++ [over.ics.user]p1:
2160 //
2161 // [...] If the user-defined conversion is specified by a
2162 // conversion function (12.3.2), the initial standard
2163 // conversion sequence converts the source type to the
2164 // implicit object parameter of the conversion function.
2165 User.Before = Best->Conversions[0].Standard;
2166 User.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002167 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002168 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002169
John McCall5c32be02010-08-24 20:38:10 +00002170 // C++ [over.ics.user]p2:
2171 // The second standard conversion sequence converts the
2172 // result of the user-defined conversion to the target type
2173 // for the sequence. Since an implicit conversion sequence
2174 // is an initialization, the special rules for
2175 // initialization by user-defined conversion apply when
2176 // selecting the best user-defined conversion for a
2177 // user-defined conversion sequence (see 13.3.3 and
2178 // 13.3.3.1).
2179 User.After = Best->FinalConversion;
2180 return OR_Success;
2181 } else {
2182 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002183 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002184 }
2185
John McCall5c32be02010-08-24 20:38:10 +00002186 case OR_No_Viable_Function:
2187 return OR_No_Viable_Function;
2188 case OR_Deleted:
2189 // No conversion here! We're done.
2190 return OR_Deleted;
2191
2192 case OR_Ambiguous:
2193 return OR_Ambiguous;
2194 }
2195
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002196 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002197}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002198
2199bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002200Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002201 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002202 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002203 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002204 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002205 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002206 if (OvResult == OR_Ambiguous)
2207 Diag(From->getSourceRange().getBegin(),
2208 diag::err_typecheck_ambiguous_condition)
2209 << From->getType() << ToType << From->getSourceRange();
2210 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2211 Diag(From->getSourceRange().getBegin(),
2212 diag::err_typecheck_nonviable_condition)
2213 << From->getType() << ToType << From->getSourceRange();
2214 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002215 return false;
John McCall5c32be02010-08-24 20:38:10 +00002216 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002217 return true;
2218}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002219
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002220/// CompareImplicitConversionSequences - Compare two implicit
2221/// conversion sequences to determine whether one is better than the
2222/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002223static ImplicitConversionSequence::CompareKind
2224CompareImplicitConversionSequences(Sema &S,
2225 const ImplicitConversionSequence& ICS1,
2226 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002227{
2228 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2229 // conversion sequences (as defined in 13.3.3.1)
2230 // -- a standard conversion sequence (13.3.3.1.1) is a better
2231 // conversion sequence than a user-defined conversion sequence or
2232 // an ellipsis conversion sequence, and
2233 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2234 // conversion sequence than an ellipsis conversion sequence
2235 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002236 //
John McCall0d1da222010-01-12 00:44:57 +00002237 // C++0x [over.best.ics]p10:
2238 // For the purpose of ranking implicit conversion sequences as
2239 // described in 13.3.3.2, the ambiguous conversion sequence is
2240 // treated as a user-defined sequence that is indistinguishable
2241 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002242 if (ICS1.getKindRank() < ICS2.getKindRank())
2243 return ImplicitConversionSequence::Better;
2244 else if (ICS2.getKindRank() < ICS1.getKindRank())
2245 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002246
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002247 // The following checks require both conversion sequences to be of
2248 // the same kind.
2249 if (ICS1.getKind() != ICS2.getKind())
2250 return ImplicitConversionSequence::Indistinguishable;
2251
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002252 // Two implicit conversion sequences of the same form are
2253 // indistinguishable conversion sequences unless one of the
2254 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002255 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002256 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002257 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002258 // User-defined conversion sequence U1 is a better conversion
2259 // sequence than another user-defined conversion sequence U2 if
2260 // they contain the same user-defined conversion function or
2261 // constructor and if the second standard conversion sequence of
2262 // U1 is better than the second standard conversion sequence of
2263 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002264 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002265 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002266 return CompareStandardConversionSequences(S,
2267 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002268 ICS2.UserDefined.After);
2269 }
2270
2271 return ImplicitConversionSequence::Indistinguishable;
2272}
2273
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002274static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2275 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2276 Qualifiers Quals;
2277 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2278 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2279 }
2280
2281 return Context.hasSameUnqualifiedType(T1, T2);
2282}
2283
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002284// Per 13.3.3.2p3, compare the given standard conversion sequences to
2285// determine if one is a proper subset of the other.
2286static ImplicitConversionSequence::CompareKind
2287compareStandardConversionSubsets(ASTContext &Context,
2288 const StandardConversionSequence& SCS1,
2289 const StandardConversionSequence& SCS2) {
2290 ImplicitConversionSequence::CompareKind Result
2291 = ImplicitConversionSequence::Indistinguishable;
2292
Douglas Gregore87561a2010-05-23 22:10:15 +00002293 // the identity conversion sequence is considered to be a subsequence of
2294 // any non-identity conversion sequence
2295 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2296 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2297 return ImplicitConversionSequence::Better;
2298 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2299 return ImplicitConversionSequence::Worse;
2300 }
2301
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002302 if (SCS1.Second != SCS2.Second) {
2303 if (SCS1.Second == ICK_Identity)
2304 Result = ImplicitConversionSequence::Better;
2305 else if (SCS2.Second == ICK_Identity)
2306 Result = ImplicitConversionSequence::Worse;
2307 else
2308 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002309 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002310 return ImplicitConversionSequence::Indistinguishable;
2311
2312 if (SCS1.Third == SCS2.Third) {
2313 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2314 : ImplicitConversionSequence::Indistinguishable;
2315 }
2316
2317 if (SCS1.Third == ICK_Identity)
2318 return Result == ImplicitConversionSequence::Worse
2319 ? ImplicitConversionSequence::Indistinguishable
2320 : ImplicitConversionSequence::Better;
2321
2322 if (SCS2.Third == ICK_Identity)
2323 return Result == ImplicitConversionSequence::Better
2324 ? ImplicitConversionSequence::Indistinguishable
2325 : ImplicitConversionSequence::Worse;
2326
2327 return ImplicitConversionSequence::Indistinguishable;
2328}
2329
Douglas Gregore696ebb2011-01-26 14:52:12 +00002330/// \brief Determine whether one of the given reference bindings is better
2331/// than the other based on what kind of bindings they are.
2332static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2333 const StandardConversionSequence &SCS2) {
2334 // C++0x [over.ics.rank]p3b4:
2335 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2336 // implicit object parameter of a non-static member function declared
2337 // without a ref-qualifier, and *either* S1 binds an rvalue reference
2338 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
2339 // lvalue reference to a function lvalue and S2 binds an rvalue
2340 // reference*.
2341 //
2342 // FIXME: Rvalue references. We're going rogue with the above edits,
2343 // because the semantics in the current C++0x working paper (N3225 at the
2344 // time of this writing) break the standard definition of std::forward
2345 // and std::reference_wrapper when dealing with references to functions.
2346 // Proposed wording changes submitted to CWG for consideration.
2347 //
2348 // FIXME: Rvalue references. We don't know if we're dealing with the
2349 // implicit object parameter, or if the member function in this case has a
2350 // ref qualifier. (Of course, we don't have ref qualifiers yet.)
2351 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2352 SCS2.IsLvalueReference) ||
2353 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2354 !SCS2.IsLvalueReference);
2355}
2356
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002357/// CompareStandardConversionSequences - Compare two standard
2358/// conversion sequences to determine whether one is better than the
2359/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002360static ImplicitConversionSequence::CompareKind
2361CompareStandardConversionSequences(Sema &S,
2362 const StandardConversionSequence& SCS1,
2363 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002364{
2365 // Standard conversion sequence S1 is a better conversion sequence
2366 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2367
2368 // -- S1 is a proper subsequence of S2 (comparing the conversion
2369 // sequences in the canonical form defined by 13.3.3.1.1,
2370 // excluding any Lvalue Transformation; the identity conversion
2371 // sequence is considered to be a subsequence of any
2372 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002373 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002374 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002375 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002376
2377 // -- the rank of S1 is better than the rank of S2 (by the rules
2378 // defined below), or, if not that,
2379 ImplicitConversionRank Rank1 = SCS1.getRank();
2380 ImplicitConversionRank Rank2 = SCS2.getRank();
2381 if (Rank1 < Rank2)
2382 return ImplicitConversionSequence::Better;
2383 else if (Rank2 < Rank1)
2384 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002385
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002386 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2387 // are indistinguishable unless one of the following rules
2388 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002389
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002390 // A conversion that is not a conversion of a pointer, or
2391 // pointer to member, to bool is better than another conversion
2392 // that is such a conversion.
2393 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2394 return SCS2.isPointerConversionToBool()
2395 ? ImplicitConversionSequence::Better
2396 : ImplicitConversionSequence::Worse;
2397
Douglas Gregor5c407d92008-10-23 00:40:37 +00002398 // C++ [over.ics.rank]p4b2:
2399 //
2400 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002401 // conversion of B* to A* is better than conversion of B* to
2402 // void*, and conversion of A* to void* is better than conversion
2403 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002404 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002405 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002406 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002407 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002408 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2409 // Exactly one of the conversion sequences is a conversion to
2410 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002411 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2412 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002413 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2414 // Neither conversion sequence converts to a void pointer; compare
2415 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002416 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002417 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002418 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002419 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2420 // Both conversion sequences are conversions to void
2421 // pointers. Compare the source types to determine if there's an
2422 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002423 QualType FromType1 = SCS1.getFromType();
2424 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002425
2426 // Adjust the types we're converting from via the array-to-pointer
2427 // conversion, if we need to.
2428 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002429 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002430 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002431 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002432
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002433 QualType FromPointee1
2434 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2435 QualType FromPointee2
2436 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002437
John McCall5c32be02010-08-24 20:38:10 +00002438 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002439 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002440 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002441 return ImplicitConversionSequence::Worse;
2442
2443 // Objective-C++: If one interface is more specific than the
2444 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002445 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2446 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002447 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002448 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002449 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002450 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002451 return ImplicitConversionSequence::Worse;
2452 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002453 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002454
2455 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2456 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002457 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002458 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002459 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002460
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002461 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002462 // Check for a better reference binding based on the kind of bindings.
2463 if (isBetterReferenceBindingKind(SCS1, SCS2))
2464 return ImplicitConversionSequence::Better;
2465 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2466 return ImplicitConversionSequence::Worse;
2467
Sebastian Redlb28b4072009-03-22 23:49:27 +00002468 // C++ [over.ics.rank]p3b4:
2469 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2470 // which the references refer are the same type except for
2471 // top-level cv-qualifiers, and the type to which the reference
2472 // initialized by S2 refers is more cv-qualified than the type
2473 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002474 QualType T1 = SCS1.getToType(2);
2475 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002476 T1 = S.Context.getCanonicalType(T1);
2477 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002478 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002479 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2480 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002481 if (UnqualT1 == UnqualT2) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00002482 // If the type is an array type, promote the element qualifiers to the
2483 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002484 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002485 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002486 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002487 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002488 if (T2.isMoreQualifiedThan(T1))
2489 return ImplicitConversionSequence::Better;
2490 else if (T1.isMoreQualifiedThan(T2))
2491 return ImplicitConversionSequence::Worse;
2492 }
2493 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002494
2495 return ImplicitConversionSequence::Indistinguishable;
2496}
2497
2498/// CompareQualificationConversions - Compares two standard conversion
2499/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002500/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2501ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002502CompareQualificationConversions(Sema &S,
2503 const StandardConversionSequence& SCS1,
2504 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002505 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002506 // -- S1 and S2 differ only in their qualification conversion and
2507 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2508 // cv-qualification signature of type T1 is a proper subset of
2509 // the cv-qualification signature of type T2, and S1 is not the
2510 // deprecated string literal array-to-pointer conversion (4.2).
2511 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2512 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2513 return ImplicitConversionSequence::Indistinguishable;
2514
2515 // FIXME: the example in the standard doesn't use a qualification
2516 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002517 QualType T1 = SCS1.getToType(2);
2518 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002519 T1 = S.Context.getCanonicalType(T1);
2520 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002521 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002522 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2523 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002524
2525 // If the types are the same, we won't learn anything by unwrapped
2526 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002527 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002528 return ImplicitConversionSequence::Indistinguishable;
2529
Chandler Carruth607f38e2009-12-29 07:16:59 +00002530 // If the type is an array type, promote the element qualifiers to the type
2531 // for comparison.
2532 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002533 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002534 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002535 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002536
Mike Stump11289f42009-09-09 15:08:12 +00002537 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002538 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002539 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002540 // Within each iteration of the loop, we check the qualifiers to
2541 // determine if this still looks like a qualification
2542 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002543 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002544 // until there are no more pointers or pointers-to-members left
2545 // to unwrap. This essentially mimics what
2546 // IsQualificationConversion does, but here we're checking for a
2547 // strict subset of qualifiers.
2548 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2549 // The qualifiers are the same, so this doesn't tell us anything
2550 // about how the sequences rank.
2551 ;
2552 else if (T2.isMoreQualifiedThan(T1)) {
2553 // T1 has fewer qualifiers, so it could be the better sequence.
2554 if (Result == ImplicitConversionSequence::Worse)
2555 // Neither has qualifiers that are a subset of the other's
2556 // qualifiers.
2557 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002558
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002559 Result = ImplicitConversionSequence::Better;
2560 } else if (T1.isMoreQualifiedThan(T2)) {
2561 // T2 has fewer qualifiers, so it could be the better sequence.
2562 if (Result == ImplicitConversionSequence::Better)
2563 // Neither has qualifiers that are a subset of the other's
2564 // qualifiers.
2565 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002566
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002567 Result = ImplicitConversionSequence::Worse;
2568 } else {
2569 // Qualifiers are disjoint.
2570 return ImplicitConversionSequence::Indistinguishable;
2571 }
2572
2573 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002574 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002575 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002576 }
2577
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002578 // Check that the winning standard conversion sequence isn't using
2579 // the deprecated string literal array to pointer conversion.
2580 switch (Result) {
2581 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002582 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002583 Result = ImplicitConversionSequence::Indistinguishable;
2584 break;
2585
2586 case ImplicitConversionSequence::Indistinguishable:
2587 break;
2588
2589 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002590 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002591 Result = ImplicitConversionSequence::Indistinguishable;
2592 break;
2593 }
2594
2595 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002596}
2597
Douglas Gregor5c407d92008-10-23 00:40:37 +00002598/// CompareDerivedToBaseConversions - Compares two standard conversion
2599/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002600/// various kinds of derived-to-base conversions (C++
2601/// [over.ics.rank]p4b3). As part of these checks, we also look at
2602/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002603ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002604CompareDerivedToBaseConversions(Sema &S,
2605 const StandardConversionSequence& SCS1,
2606 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002607 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002608 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002609 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002610 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002611
2612 // Adjust the types we're converting from via the array-to-pointer
2613 // conversion, if we need to.
2614 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002615 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002616 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002617 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002618
2619 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002620 FromType1 = S.Context.getCanonicalType(FromType1);
2621 ToType1 = S.Context.getCanonicalType(ToType1);
2622 FromType2 = S.Context.getCanonicalType(FromType2);
2623 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002624
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002625 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002626 //
2627 // If class B is derived directly or indirectly from class A and
2628 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002629 //
2630 // For Objective-C, we let A, B, and C also be Objective-C
2631 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002632
2633 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002634 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002635 SCS2.Second == ICK_Pointer_Conversion &&
2636 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2637 FromType1->isPointerType() && FromType2->isPointerType() &&
2638 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002639 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002640 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002641 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002642 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002643 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002644 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002645 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002646 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002647
John McCall8b07ec22010-05-15 11:32:37 +00002648 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2649 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2650 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2651 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002652
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002653 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002654 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002655 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002656 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002657 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002658 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002659
2660 if (ToIface1 && ToIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002661 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002662 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002663 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002664 return ImplicitConversionSequence::Worse;
2665 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002666 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002667
2668 // -- conversion of B* to A* is better than conversion of C* to A*,
2669 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002670 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002671 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002672 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002673 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002674
Douglas Gregor237f96c2008-11-26 23:31:11 +00002675 if (FromIface1 && FromIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002676 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002677 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002678 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002679 return ImplicitConversionSequence::Worse;
2680 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002681 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002682 }
2683
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002684 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002685 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2686 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2687 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2688 const MemberPointerType * FromMemPointer1 =
2689 FromType1->getAs<MemberPointerType>();
2690 const MemberPointerType * ToMemPointer1 =
2691 ToType1->getAs<MemberPointerType>();
2692 const MemberPointerType * FromMemPointer2 =
2693 FromType2->getAs<MemberPointerType>();
2694 const MemberPointerType * ToMemPointer2 =
2695 ToType2->getAs<MemberPointerType>();
2696 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2697 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2698 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2699 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2700 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2701 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2702 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2703 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002704 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002705 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002706 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002707 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002708 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002709 return ImplicitConversionSequence::Better;
2710 }
2711 // conversion of B::* to C::* is better than conversion of A::* to C::*
2712 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002713 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002714 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002715 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002716 return ImplicitConversionSequence::Worse;
2717 }
2718 }
2719
Douglas Gregor5ab11652010-04-17 22:01:05 +00002720 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002721 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002722 // -- binding of an expression of type C to a reference of type
2723 // B& is better than binding an expression of type C to a
2724 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002725 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2726 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2727 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002728 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002729 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002730 return ImplicitConversionSequence::Worse;
2731 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002732
Douglas Gregor2fe98832008-11-03 19:09:14 +00002733 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002734 // -- binding of an expression of type B to a reference of type
2735 // A& is better than binding an expression of type C to a
2736 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002737 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2738 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2739 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002740 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002741 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002742 return ImplicitConversionSequence::Worse;
2743 }
2744 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002745
Douglas Gregor5c407d92008-10-23 00:40:37 +00002746 return ImplicitConversionSequence::Indistinguishable;
2747}
2748
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002749/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2750/// determine whether they are reference-related,
2751/// reference-compatible, reference-compatible with added
2752/// qualification, or incompatible, for use in C++ initialization by
2753/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2754/// type, and the first type (T1) is the pointee type of the reference
2755/// type being initialized.
2756Sema::ReferenceCompareResult
2757Sema::CompareReferenceRelationship(SourceLocation Loc,
2758 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002759 bool &DerivedToBase,
2760 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002761 assert(!OrigT1->isReferenceType() &&
2762 "T1 must be the pointee type of the reference type");
2763 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2764
2765 QualType T1 = Context.getCanonicalType(OrigT1);
2766 QualType T2 = Context.getCanonicalType(OrigT2);
2767 Qualifiers T1Quals, T2Quals;
2768 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2769 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2770
2771 // C++ [dcl.init.ref]p4:
2772 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2773 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2774 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002775 DerivedToBase = false;
2776 ObjCConversion = false;
2777 if (UnqualT1 == UnqualT2) {
2778 // Nothing to do.
2779 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002780 IsDerivedFrom(UnqualT2, UnqualT1))
2781 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002782 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2783 UnqualT2->isObjCObjectOrInterfaceType() &&
2784 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2785 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002786 else
2787 return Ref_Incompatible;
2788
2789 // At this point, we know that T1 and T2 are reference-related (at
2790 // least).
2791
2792 // If the type is an array type, promote the element qualifiers to the type
2793 // for comparison.
2794 if (isa<ArrayType>(T1) && T1Quals)
2795 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2796 if (isa<ArrayType>(T2) && T2Quals)
2797 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2798
2799 // C++ [dcl.init.ref]p4:
2800 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2801 // reference-related to T2 and cv1 is the same cv-qualification
2802 // as, or greater cv-qualification than, cv2. For purposes of
2803 // overload resolution, cases for which cv1 is greater
2804 // cv-qualification than cv2 are identified as
2805 // reference-compatible with added qualification (see 13.3.3.2).
2806 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2807 return Ref_Compatible;
2808 else if (T1.isMoreQualifiedThan(T2))
2809 return Ref_Compatible_With_Added_Qualification;
2810 else
2811 return Ref_Related;
2812}
2813
Douglas Gregor836a7e82010-08-11 02:15:33 +00002814/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002815/// with DeclType. Return true if something definite is found.
2816static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002817FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2818 QualType DeclType, SourceLocation DeclLoc,
2819 Expr *Init, QualType T2, bool AllowRvalues,
2820 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002821 assert(T2->isRecordType() && "Can only find conversions of record types.");
2822 CXXRecordDecl *T2RecordDecl
2823 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2824
2825 OverloadCandidateSet CandidateSet(DeclLoc);
2826 const UnresolvedSetImpl *Conversions
2827 = T2RecordDecl->getVisibleConversionFunctions();
2828 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2829 E = Conversions->end(); I != E; ++I) {
2830 NamedDecl *D = *I;
2831 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2832 if (isa<UsingShadowDecl>(D))
2833 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2834
2835 FunctionTemplateDecl *ConvTemplate
2836 = dyn_cast<FunctionTemplateDecl>(D);
2837 CXXConversionDecl *Conv;
2838 if (ConvTemplate)
2839 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2840 else
2841 Conv = cast<CXXConversionDecl>(D);
2842
Douglas Gregor836a7e82010-08-11 02:15:33 +00002843 // If this is an explicit conversion, and we're not allowed to consider
2844 // explicit conversions, skip it.
2845 if (!AllowExplicit && Conv->isExplicit())
2846 continue;
2847
2848 if (AllowRvalues) {
2849 bool DerivedToBase = false;
2850 bool ObjCConversion = false;
2851 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00002852 S.CompareReferenceRelationship(
2853 DeclLoc,
2854 Conv->getConversionType().getNonReferenceType()
2855 .getUnqualifiedType(),
2856 DeclType.getNonReferenceType().getUnqualifiedType(),
2857 DerivedToBase, ObjCConversion) ==
2858 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00002859 continue;
2860 } else {
2861 // If the conversion function doesn't return a reference type,
2862 // it can't be considered for this conversion. An rvalue reference
2863 // is only acceptable if its referencee is a function type.
2864
2865 const ReferenceType *RefType =
2866 Conv->getConversionType()->getAs<ReferenceType>();
2867 if (!RefType ||
2868 (!RefType->isLValueReferenceType() &&
2869 !RefType->getPointeeType()->isFunctionType()))
2870 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002871 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002872
2873 if (ConvTemplate)
2874 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00002875 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00002876 else
2877 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00002878 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002879 }
2880
2881 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002882 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002883 case OR_Success:
2884 // C++ [over.ics.ref]p1:
2885 //
2886 // [...] If the parameter binds directly to the result of
2887 // applying a conversion function to the argument
2888 // expression, the implicit conversion sequence is a
2889 // user-defined conversion sequence (13.3.3.1.2), with the
2890 // second standard conversion sequence either an identity
2891 // conversion or, if the conversion function returns an
2892 // entity of a type that is a derived class of the parameter
2893 // type, a derived-to-base Conversion.
2894 if (!Best->FinalConversion.DirectBinding)
2895 return false;
2896
2897 ICS.setUserDefined();
2898 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2899 ICS.UserDefined.After = Best->FinalConversion;
2900 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002901 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redld92badf2010-06-30 18:13:39 +00002902 ICS.UserDefined.EllipsisConversion = false;
2903 assert(ICS.UserDefined.After.ReferenceBinding &&
2904 ICS.UserDefined.After.DirectBinding &&
2905 "Expected a direct reference binding!");
2906 return true;
2907
2908 case OR_Ambiguous:
2909 ICS.setAmbiguous();
2910 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2911 Cand != CandidateSet.end(); ++Cand)
2912 if (Cand->Viable)
2913 ICS.Ambiguous.addConversion(Cand->Function);
2914 return true;
2915
2916 case OR_No_Viable_Function:
2917 case OR_Deleted:
2918 // There was no suitable conversion, or we found a deleted
2919 // conversion; continue with other checks.
2920 return false;
2921 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002922
2923 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002924}
2925
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002926/// \brief Compute an implicit conversion sequence for reference
2927/// initialization.
2928static ImplicitConversionSequence
2929TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2930 SourceLocation DeclLoc,
2931 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002932 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002933 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2934
2935 // Most paths end in a failed conversion.
2936 ImplicitConversionSequence ICS;
2937 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2938
2939 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2940 QualType T2 = Init->getType();
2941
2942 // If the initializer is the address of an overloaded function, try
2943 // to resolve the overloaded function. If all goes well, T2 is the
2944 // type of the resulting function.
2945 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2946 DeclAccessPair Found;
2947 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2948 false, Found))
2949 T2 = Fn->getType();
2950 }
2951
2952 // Compute some basic properties of the types and the initializer.
2953 bool isRValRef = DeclType->isRValueReferenceType();
2954 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002955 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002956 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002957 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002958 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2959 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002960
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002961
Sebastian Redld92badf2010-06-30 18:13:39 +00002962 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002963 // A reference to type "cv1 T1" is initialized by an expression
2964 // of type "cv2 T2" as follows:
2965
Sebastian Redld92badf2010-06-30 18:13:39 +00002966 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00002967 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002968 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2969 // reference-compatible with "cv2 T2," or
2970 //
2971 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2972 if (InitCategory.isLValue() &&
2973 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002974 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002975 // When a parameter of reference type binds directly (8.5.3)
2976 // to an argument expression, the implicit conversion sequence
2977 // is the identity conversion, unless the argument expression
2978 // has a type that is a derived class of the parameter type,
2979 // in which case the implicit conversion sequence is a
2980 // derived-to-base Conversion (13.3.3.1).
2981 ICS.setStandard();
2982 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002983 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2984 : ObjCConversion? ICK_Compatible_Conversion
2985 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002986 ICS.Standard.Third = ICK_Identity;
2987 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2988 ICS.Standard.setToType(0, T2);
2989 ICS.Standard.setToType(1, T1);
2990 ICS.Standard.setToType(2, T1);
2991 ICS.Standard.ReferenceBinding = true;
2992 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00002993 ICS.Standard.IsLvalueReference = !isRValRef;
2994 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
2995 ICS.Standard.BindsToRvalue = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002996 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002997
Sebastian Redld92badf2010-06-30 18:13:39 +00002998 // Nothing more to do: the inaccessibility/ambiguity check for
2999 // derived-to-base conversions is suppressed when we're
3000 // computing the implicit conversion sequence (C++
3001 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003002 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003003 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003004
Sebastian Redld92badf2010-06-30 18:13:39 +00003005 // -- has a class type (i.e., T2 is a class type), where T1 is
3006 // not reference-related to T2, and can be implicitly
3007 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3008 // is reference-compatible with "cv3 T3" 92) (this
3009 // conversion is selected by enumerating the applicable
3010 // conversion functions (13.3.1.6) and choosing the best
3011 // one through overload resolution (13.3)),
3012 if (!SuppressUserConversions && T2->isRecordType() &&
3013 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3014 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003015 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3016 Init, T2, /*AllowRvalues=*/false,
3017 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003018 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003019 }
3020 }
3021
Sebastian Redld92badf2010-06-30 18:13:39 +00003022 // -- Otherwise, the reference shall be an lvalue reference to a
3023 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003024 // shall be an rvalue reference.
Douglas Gregor870f3742010-04-18 09:22:00 +00003025 //
3026 // We actually handle one oddity of C++ [over.ics.ref] at this
3027 // point, which is that, due to p2 (which short-circuits reference
3028 // binding by only attempting a simple conversion for non-direct
3029 // bindings) and p3's strange wording, we allow a const volatile
3030 // reference to bind to an rvalue. Hence the check for the presence
3031 // of "const" rather than checking for "const" being the only
3032 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003033 // This is also the point where rvalue references and lvalue inits no longer
3034 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003035 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003036 return ICS;
3037
Douglas Gregorf143cd52011-01-24 16:14:37 +00003038 // -- If the initializer expression
3039 //
3040 // -- is an xvalue, class prvalue, array prvalue or function
3041 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3042 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3043 (InitCategory.isXValue() ||
3044 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3045 (InitCategory.isLValue() && T2->isFunctionType()))) {
3046 ICS.setStandard();
3047 ICS.Standard.First = ICK_Identity;
3048 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3049 : ObjCConversion? ICK_Compatible_Conversion
3050 : ICK_Identity;
3051 ICS.Standard.Third = ICK_Identity;
3052 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3053 ICS.Standard.setToType(0, T2);
3054 ICS.Standard.setToType(1, T1);
3055 ICS.Standard.setToType(2, T1);
3056 ICS.Standard.ReferenceBinding = true;
3057 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3058 // binding unless we're binding to a class prvalue.
3059 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3060 // allow the use of rvalue references in C++98/03 for the benefit of
3061 // standard library implementors; therefore, we need the xvalue check here.
3062 ICS.Standard.DirectBinding =
3063 S.getLangOptions().CPlusPlus0x ||
3064 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003065 ICS.Standard.IsLvalueReference = !isRValRef;
3066 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3067 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorf143cd52011-01-24 16:14:37 +00003068 ICS.Standard.CopyConstructor = 0;
3069 return ICS;
3070 }
3071
3072 // -- has a class type (i.e., T2 is a class type), where T1 is not
3073 // reference-related to T2, and can be implicitly converted to
3074 // an xvalue, class prvalue, or function lvalue of type
3075 // "cv3 T3", where "cv1 T1" is reference-compatible with
3076 // "cv3 T3",
3077 //
3078 // then the reference is bound to the value of the initializer
3079 // expression in the first case and to the result of the conversion
3080 // in the second case (or, in either case, to an appropriate base
3081 // class subobject).
3082 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3083 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
3084 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3085 Init, T2, /*AllowRvalues=*/true,
3086 AllowExplicit)) {
3087 // In the second case, if the reference is an rvalue reference
3088 // and the second standard conversion sequence of the
3089 // user-defined conversion sequence includes an lvalue-to-rvalue
3090 // conversion, the program is ill-formed.
3091 if (ICS.isUserDefined() && isRValRef &&
3092 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3093 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3094
Douglas Gregor95273c32011-01-21 16:36:05 +00003095 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003096 }
Douglas Gregor95273c32011-01-21 16:36:05 +00003097
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003098 // -- Otherwise, a temporary of type "cv1 T1" is created and
3099 // initialized from the initializer expression using the
3100 // rules for a non-reference copy initialization (8.5). The
3101 // reference is then bound to the temporary. If T1 is
3102 // reference-related to T2, cv1 must be the same
3103 // cv-qualification as, or greater cv-qualification than,
3104 // cv2; otherwise, the program is ill-formed.
3105 if (RefRelationship == Sema::Ref_Related) {
3106 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3107 // we would be reference-compatible or reference-compatible with
3108 // added qualification. But that wasn't the case, so the reference
3109 // initialization fails.
3110 return ICS;
3111 }
3112
3113 // If at least one of the types is a class type, the types are not
3114 // related, and we aren't allowed any user conversions, the
3115 // reference binding fails. This case is important for breaking
3116 // recursion, since TryImplicitConversion below will attempt to
3117 // create a temporary through the use of a copy constructor.
3118 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3119 (T1->isRecordType() || T2->isRecordType()))
3120 return ICS;
3121
Douglas Gregorcba72b12011-01-21 05:18:22 +00003122 // If T1 is reference-related to T2 and the reference is an rvalue
3123 // reference, the initializer expression shall not be an lvalue.
3124 if (RefRelationship >= Sema::Ref_Related &&
3125 isRValRef && Init->Classify(S.Context).isLValue())
3126 return ICS;
3127
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003128 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003129 // When a parameter of reference type is not bound directly to
3130 // an argument expression, the conversion sequence is the one
3131 // required to convert the argument expression to the
3132 // underlying type of the reference according to
3133 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3134 // to copy-initializing a temporary of the underlying type with
3135 // the argument expression. Any difference in top-level
3136 // cv-qualification is subsumed by the initialization itself
3137 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003138 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3139 /*AllowExplicit=*/false,
3140 /*InOverloadResolution=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003141
3142 // Of course, that's still a reference binding.
3143 if (ICS.isStandard()) {
3144 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003145 ICS.Standard.IsLvalueReference = !isRValRef;
3146 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3147 ICS.Standard.BindsToRvalue = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003148 } else if (ICS.isUserDefined()) {
3149 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003150 ICS.Standard.IsLvalueReference = !isRValRef;
3151 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3152 ICS.Standard.BindsToRvalue = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003153 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003154
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003155 return ICS;
3156}
3157
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003158/// TryCopyInitialization - Try to copy-initialize a value of type
3159/// ToType from the expression From. Return the implicit conversion
3160/// sequence required to pass this argument, which may be a bad
3161/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003162/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003163/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003164static ImplicitConversionSequence
3165TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00003166 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003167 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003168 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003169 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003170 /*FIXME:*/From->getLocStart(),
3171 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003172 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003173
John McCall5c32be02010-08-24 20:38:10 +00003174 return TryImplicitConversion(S, From, ToType,
3175 SuppressUserConversions,
3176 /*AllowExplicit=*/false,
3177 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003178}
3179
Douglas Gregor436424c2008-11-18 23:14:02 +00003180/// TryObjectArgumentInitialization - Try to initialize the object
3181/// parameter of the given member function (@c Method) from the
3182/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003183static ImplicitConversionSequence
3184TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3185 CXXMethodDecl *Method,
3186 CXXRecordDecl *ActingContext) {
3187 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003188 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3189 // const volatile object.
3190 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3191 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003192 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003193
3194 // Set up the conversion sequence as a "bad" conversion, to allow us
3195 // to exit early.
3196 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003197
3198 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003199 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003200 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003201 FromType = PT->getPointeeType();
3202
3203 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003204
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003205 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00003206 // where X is the class of which the function is a member
3207 // (C++ [over.match.funcs]p4). However, when finding an implicit
3208 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00003209 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003210 // (C++ [over.match.funcs]p5). We perform a simplified version of
3211 // reference binding here, that allows class rvalues to bind to
3212 // non-constant references.
3213
3214 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3215 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall5c32be02010-08-24 20:38:10 +00003216 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003217 if (ImplicitParamType.getCVRQualifiers()
3218 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003219 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003220 ICS.setBad(BadConversionSequence::bad_qualifiers,
3221 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003222 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003223 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003224
3225 // Check that we have either the same type or a derived type. It
3226 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003227 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003228 ImplicitConversionKind SecondKind;
3229 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3230 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003231 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003232 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003233 else {
John McCall65eb8792010-02-25 01:37:24 +00003234 ICS.setBad(BadConversionSequence::unrelated_class,
3235 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003236 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003237 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003238
3239 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003240 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003241 ICS.Standard.setAsIdentityConversion();
3242 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003243 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003244 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003245 ICS.Standard.ReferenceBinding = true;
3246 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003247
3248 // FIXME: Rvalue references.
3249 ICS.Standard.IsLvalueReference = true;
3250 ICS.Standard.BindsToFunctionLvalue = false;
3251 ICS.Standard.BindsToRvalue = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003252 return ICS;
3253}
3254
3255/// PerformObjectArgumentInitialization - Perform initialization of
3256/// the implicit object parameter for the given Method with the given
3257/// expression.
3258bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003259Sema::PerformObjectArgumentInitialization(Expr *&From,
3260 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003261 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003262 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003263 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003264 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003265 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003266
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003267 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003268 FromRecordType = PT->getPointeeType();
3269 DestType = Method->getThisType(Context);
3270 } else {
3271 FromRecordType = From->getType();
3272 DestType = ImplicitParamRecordType;
3273 }
3274
John McCall6e9f8f62009-12-03 04:06:58 +00003275 // Note that we always use the true parent context when performing
3276 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003277 ImplicitConversionSequence ICS
John McCall5c32be02010-08-24 20:38:10 +00003278 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall6e9f8f62009-12-03 04:06:58 +00003279 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003280 if (ICS.isBad()) {
3281 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3282 Qualifiers FromQs = FromRecordType.getQualifiers();
3283 Qualifiers ToQs = DestType.getQualifiers();
3284 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3285 if (CVR) {
3286 Diag(From->getSourceRange().getBegin(),
3287 diag::err_member_function_call_bad_cvr)
3288 << Method->getDeclName() << FromRecordType << (CVR - 1)
3289 << From->getSourceRange();
3290 Diag(Method->getLocation(), diag::note_previous_decl)
3291 << Method->getDeclName();
3292 return true;
3293 }
3294 }
3295
Douglas Gregor436424c2008-11-18 23:14:02 +00003296 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003297 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003298 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003299 }
Mike Stump11289f42009-09-09 15:08:12 +00003300
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003301 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003302 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003303
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003304 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003305 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003306 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003307 return false;
3308}
3309
Douglas Gregor5fb53972009-01-14 15:45:31 +00003310/// TryContextuallyConvertToBool - Attempt to contextually convert the
3311/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003312static ImplicitConversionSequence
3313TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003314 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003315 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003316 // FIXME: Are these flags correct?
3317 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003318 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003319 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003320}
3321
3322/// PerformContextuallyConvertToBool - Perform a contextual conversion
3323/// of the expression From to bool (C++0x [conv]p3).
3324bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003325 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003326 if (!ICS.isBad())
3327 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003328
Fariborz Jahanian76197412009-11-18 18:26:29 +00003329 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003330 return Diag(From->getSourceRange().getBegin(),
3331 diag::err_typecheck_bool_condition)
3332 << From->getType() << From->getSourceRange();
3333 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003334}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003335
3336/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3337/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003338static ImplicitConversionSequence
3339TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3340 QualType Ty = S.Context.getObjCIdType();
3341 return TryImplicitConversion(S, From, Ty,
3342 // FIXME: Are these flags correct?
3343 /*SuppressUserConversions=*/false,
3344 /*AllowExplicit=*/true,
3345 /*InOverloadResolution=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003346}
John McCall5c32be02010-08-24 20:38:10 +00003347
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003348/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3349/// of the expression From to 'id'.
3350bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003351 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003352 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003353 if (!ICS.isBad())
3354 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3355 return true;
3356}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003357
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003358/// \brief Attempt to convert the given expression to an integral or
3359/// enumeration type.
3360///
3361/// This routine will attempt to convert an expression of class type to an
3362/// integral or enumeration type, if that class type only has a single
3363/// conversion to an integral or enumeration type.
3364///
Douglas Gregor4799d032010-06-30 00:20:43 +00003365/// \param Loc The source location of the construct that requires the
3366/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003367///
Douglas Gregor4799d032010-06-30 00:20:43 +00003368/// \param FromE The expression we're converting from.
3369///
3370/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3371/// have integral or enumeration type.
3372///
3373/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3374/// incomplete class type.
3375///
3376/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3377/// explicit conversion function (because no implicit conversion functions
3378/// were available). This is a recovery mode.
3379///
3380/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3381/// showing which conversion was picked.
3382///
3383/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3384/// conversion function that could convert to integral or enumeration type.
3385///
3386/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3387/// usable conversion function.
3388///
3389/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3390/// function, which may be an extension in this case.
3391///
3392/// \returns The expression, converted to an integral or enumeration type if
3393/// successful.
John McCalldadc5752010-08-24 06:29:42 +00003394ExprResult
John McCallb268a282010-08-23 23:25:46 +00003395Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003396 const PartialDiagnostic &NotIntDiag,
3397 const PartialDiagnostic &IncompleteDiag,
3398 const PartialDiagnostic &ExplicitConvDiag,
3399 const PartialDiagnostic &ExplicitConvNote,
3400 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003401 const PartialDiagnostic &AmbigNote,
3402 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003403 // We can't perform any more checking for type-dependent expressions.
3404 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003405 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003406
3407 // If the expression already has integral or enumeration type, we're golden.
3408 QualType T = From->getType();
3409 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003410 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003411
3412 // FIXME: Check for missing '()' if T is a function type?
3413
3414 // If we don't have a class type in C++, there's no way we can get an
3415 // expression of integral or enumeration type.
3416 const RecordType *RecordTy = T->getAs<RecordType>();
3417 if (!RecordTy || !getLangOptions().CPlusPlus) {
3418 Diag(Loc, NotIntDiag)
3419 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003420 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003421 }
3422
3423 // We must have a complete class type.
3424 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003425 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003426
3427 // Look for a conversion to an integral or enumeration type.
3428 UnresolvedSet<4> ViableConversions;
3429 UnresolvedSet<4> ExplicitConversions;
3430 const UnresolvedSetImpl *Conversions
3431 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3432
3433 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3434 E = Conversions->end();
3435 I != E;
3436 ++I) {
3437 if (CXXConversionDecl *Conversion
3438 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3439 if (Conversion->getConversionType().getNonReferenceType()
3440 ->isIntegralOrEnumerationType()) {
3441 if (Conversion->isExplicit())
3442 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3443 else
3444 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3445 }
3446 }
3447
3448 switch (ViableConversions.size()) {
3449 case 0:
3450 if (ExplicitConversions.size() == 1) {
3451 DeclAccessPair Found = ExplicitConversions[0];
3452 CXXConversionDecl *Conversion
3453 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3454
3455 // The user probably meant to invoke the given explicit
3456 // conversion; use it.
3457 QualType ConvTy
3458 = Conversion->getConversionType().getNonReferenceType();
3459 std::string TypeStr;
3460 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3461
3462 Diag(Loc, ExplicitConvDiag)
3463 << T << ConvTy
3464 << FixItHint::CreateInsertion(From->getLocStart(),
3465 "static_cast<" + TypeStr + ">(")
3466 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3467 ")");
3468 Diag(Conversion->getLocation(), ExplicitConvNote)
3469 << ConvTy->isEnumeralType() << ConvTy;
3470
3471 // If we aren't in a SFINAE context, build a call to the
3472 // explicit conversion function.
3473 if (isSFINAEContext())
3474 return ExprError();
3475
3476 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00003477 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3478 if (Result.isInvalid())
3479 return ExprError();
3480
3481 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003482 }
3483
3484 // We'll complain below about a non-integral condition type.
3485 break;
3486
3487 case 1: {
3488 // Apply this conversion.
3489 DeclAccessPair Found = ViableConversions[0];
3490 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003491
3492 CXXConversionDecl *Conversion
3493 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3494 QualType ConvTy
3495 = Conversion->getConversionType().getNonReferenceType();
3496 if (ConvDiag.getDiagID()) {
3497 if (isSFINAEContext())
3498 return ExprError();
3499
3500 Diag(Loc, ConvDiag)
3501 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3502 }
3503
Douglas Gregor668443e2011-01-20 00:18:04 +00003504 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003505 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00003506 if (Result.isInvalid())
3507 return ExprError();
3508
3509 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003510 break;
3511 }
3512
3513 default:
3514 Diag(Loc, AmbigDiag)
3515 << T << From->getSourceRange();
3516 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3517 CXXConversionDecl *Conv
3518 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3519 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3520 Diag(Conv->getLocation(), AmbigNote)
3521 << ConvTy->isEnumeralType() << ConvTy;
3522 }
John McCallb268a282010-08-23 23:25:46 +00003523 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003524 }
3525
Douglas Gregor5823da32010-06-29 23:25:20 +00003526 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003527 Diag(Loc, NotIntDiag)
3528 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003529
John McCallb268a282010-08-23 23:25:46 +00003530 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003531}
3532
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003533/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003534/// candidate functions, using the given function call arguments. If
3535/// @p SuppressUserConversions, then don't allow user-defined
3536/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003537///
3538/// \para PartialOverloading true if we are performing "partial" overloading
3539/// based on an incomplete set of function arguments. This feature is used by
3540/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003541void
3542Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003543 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003544 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003545 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003546 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003547 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003548 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003549 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003550 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003551 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003552 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003553
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003554 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003555 if (!isa<CXXConstructorDecl>(Method)) {
3556 // If we get here, it's because we're calling a member function
3557 // that is named without a member access expression (e.g.,
3558 // "this->f") that was either written explicitly or created
3559 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003560 // function, e.g., X::f(). We use an empty type for the implied
3561 // object argument (C++ [over.call.func]p3), and the acting context
3562 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003563 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003564 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003565 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003566 return;
3567 }
3568 // We treat a constructor like a non-member function, since its object
3569 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003570 }
3571
Douglas Gregorff7028a2009-11-13 23:59:09 +00003572 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003573 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003574
Douglas Gregor27381f32009-11-23 12:27:39 +00003575 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003576 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003577
Douglas Gregorffe14e32009-11-14 01:20:54 +00003578 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3579 // C++ [class.copy]p3:
3580 // A member function template is never instantiated to perform the copy
3581 // of a class object to an object of its class type.
3582 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3583 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003584 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003585 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3586 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003587 return;
3588 }
3589
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003590 // Add this candidate
3591 CandidateSet.push_back(OverloadCandidate());
3592 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003593 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003594 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003595 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003596 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003597 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003598 Candidate.ExplicitCallArguments = NumArgs;
3599
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003600 unsigned NumArgsInProto = Proto->getNumArgs();
3601
3602 // (C++ 13.3.2p2): A candidate function having fewer than m
3603 // parameters is viable only if it has an ellipsis in its parameter
3604 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003605 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3606 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003607 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003608 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003609 return;
3610 }
3611
3612 // (C++ 13.3.2p2): A candidate function having more than m parameters
3613 // is viable only if the (m+1)st parameter has a default argument
3614 // (8.3.6). For the purposes of overload resolution, the
3615 // parameter list is truncated on the right, so that there are
3616 // exactly m parameters.
3617 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003618 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003619 // Not enough arguments.
3620 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003621 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003622 return;
3623 }
3624
3625 // Determine the implicit conversion sequences for each of the
3626 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003627 Candidate.Conversions.resize(NumArgs);
3628 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3629 if (ArgIdx < NumArgsInProto) {
3630 // (C++ 13.3.2p3): for F to be a viable function, there shall
3631 // exist for each argument an implicit conversion sequence
3632 // (13.3.3.1) that converts that argument to the corresponding
3633 // parameter of F.
3634 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003635 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003636 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003637 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003638 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003639 if (Candidate.Conversions[ArgIdx].isBad()) {
3640 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003641 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003642 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003643 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003644 } else {
3645 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3646 // argument for which there is no corresponding parameter is
3647 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003648 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003649 }
3650 }
3651}
3652
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003653/// \brief Add all of the function declarations in the given function set to
3654/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003655void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003656 Expr **Args, unsigned NumArgs,
3657 OverloadCandidateSet& CandidateSet,
3658 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003659 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003660 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3661 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003662 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003663 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003664 cast<CXXMethodDecl>(FD)->getParent(),
3665 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003666 CandidateSet, SuppressUserConversions);
3667 else
John McCalla0296f72010-03-19 07:35:19 +00003668 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003669 SuppressUserConversions);
3670 } else {
John McCalla0296f72010-03-19 07:35:19 +00003671 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003672 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3673 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003674 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003675 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003676 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003677 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003678 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003679 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003680 else
John McCalla0296f72010-03-19 07:35:19 +00003681 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003682 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003683 Args, NumArgs, CandidateSet,
3684 SuppressUserConversions);
3685 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003686 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003687}
3688
John McCallf0f1cf02009-11-17 07:50:12 +00003689/// AddMethodCandidate - Adds a named decl (which is some kind of
3690/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003691void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003692 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003693 Expr **Args, unsigned NumArgs,
3694 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003695 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003696 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003697 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003698
3699 if (isa<UsingShadowDecl>(Decl))
3700 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3701
3702 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3703 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3704 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003705 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3706 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003707 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003708 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003709 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003710 } else {
John McCalla0296f72010-03-19 07:35:19 +00003711 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003712 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003713 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003714 }
3715}
3716
Douglas Gregor436424c2008-11-18 23:14:02 +00003717/// AddMethodCandidate - Adds the given C++ member function to the set
3718/// of candidate functions, using the given function call arguments
3719/// and the object argument (@c Object). For example, in a call
3720/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3721/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3722/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003723/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003724void
John McCalla0296f72010-03-19 07:35:19 +00003725Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003726 CXXRecordDecl *ActingContext, QualType ObjectType,
3727 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003728 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003729 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003730 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003731 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003732 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003733 assert(!isa<CXXConstructorDecl>(Method) &&
3734 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003735
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003736 if (!CandidateSet.isNewCandidate(Method))
3737 return;
3738
Douglas Gregor27381f32009-11-23 12:27:39 +00003739 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003740 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003741
Douglas Gregor436424c2008-11-18 23:14:02 +00003742 // Add this candidate
3743 CandidateSet.push_back(OverloadCandidate());
3744 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003745 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003746 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003747 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003748 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003749 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00003750
3751 unsigned NumArgsInProto = Proto->getNumArgs();
3752
3753 // (C++ 13.3.2p2): A candidate function having fewer than m
3754 // parameters is viable only if it has an ellipsis in its parameter
3755 // list (8.3.5).
3756 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3757 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003758 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003759 return;
3760 }
3761
3762 // (C++ 13.3.2p2): A candidate function having more than m parameters
3763 // is viable only if the (m+1)st parameter has a default argument
3764 // (8.3.6). For the purposes of overload resolution, the
3765 // parameter list is truncated on the right, so that there are
3766 // exactly m parameters.
3767 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3768 if (NumArgs < MinRequiredArgs) {
3769 // Not enough arguments.
3770 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003771 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003772 return;
3773 }
3774
3775 Candidate.Viable = true;
3776 Candidate.Conversions.resize(NumArgs + 1);
3777
John McCall6e9f8f62009-12-03 04:06:58 +00003778 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003779 // The implicit object argument is ignored.
3780 Candidate.IgnoreObjectArgument = true;
3781 else {
3782 // Determine the implicit conversion sequence for the object
3783 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003784 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003785 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3786 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003787 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003788 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003789 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003790 return;
3791 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003792 }
3793
3794 // Determine the implicit conversion sequences for each of the
3795 // arguments.
3796 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3797 if (ArgIdx < NumArgsInProto) {
3798 // (C++ 13.3.2p3): for F to be a viable function, there shall
3799 // exist for each argument an implicit conversion sequence
3800 // (13.3.3.1) that converts that argument to the corresponding
3801 // parameter of F.
3802 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003803 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003804 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003805 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003806 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003807 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003808 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003809 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003810 break;
3811 }
3812 } else {
3813 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3814 // argument for which there is no corresponding parameter is
3815 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003816 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003817 }
3818 }
3819}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003820
Douglas Gregor97628d62009-08-21 00:16:32 +00003821/// \brief Add a C++ member function template as a candidate to the candidate
3822/// set, using template argument deduction to produce an appropriate member
3823/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003824void
Douglas Gregor97628d62009-08-21 00:16:32 +00003825Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003826 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003827 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003828 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003829 QualType ObjectType,
3830 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003831 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003832 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003833 if (!CandidateSet.isNewCandidate(MethodTmpl))
3834 return;
3835
Douglas Gregor97628d62009-08-21 00:16:32 +00003836 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003837 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003838 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003839 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003840 // candidate functions in the usual way.113) A given name can refer to one
3841 // or more function templates and also to a set of overloaded non-template
3842 // functions. In such a case, the candidate functions generated from each
3843 // function template are combined with the set of non-template candidate
3844 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003845 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003846 FunctionDecl *Specialization = 0;
3847 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003848 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003849 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003850 CandidateSet.push_back(OverloadCandidate());
3851 OverloadCandidate &Candidate = CandidateSet.back();
3852 Candidate.FoundDecl = FoundDecl;
3853 Candidate.Function = MethodTmpl->getTemplatedDecl();
3854 Candidate.Viable = false;
3855 Candidate.FailureKind = ovl_fail_bad_deduction;
3856 Candidate.IsSurrogate = false;
3857 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003858 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003859 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3860 Info);
3861 return;
3862 }
Mike Stump11289f42009-09-09 15:08:12 +00003863
Douglas Gregor97628d62009-08-21 00:16:32 +00003864 // Add the function template specialization produced by template argument
3865 // deduction as a candidate.
3866 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003867 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003868 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003869 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003870 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003871 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003872}
3873
Douglas Gregor05155d82009-08-21 23:19:43 +00003874/// \brief Add a C++ function template specialization as a candidate
3875/// in the candidate set, using template argument deduction to produce
3876/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003877void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003878Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003879 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003880 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003881 Expr **Args, unsigned NumArgs,
3882 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003883 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003884 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3885 return;
3886
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003887 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003888 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003889 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003890 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003891 // candidate functions in the usual way.113) A given name can refer to one
3892 // or more function templates and also to a set of overloaded non-template
3893 // functions. In such a case, the candidate functions generated from each
3894 // function template are combined with the set of non-template candidate
3895 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003896 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003897 FunctionDecl *Specialization = 0;
3898 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003899 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003900 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003901 CandidateSet.push_back(OverloadCandidate());
3902 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003903 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003904 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3905 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003906 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003907 Candidate.IsSurrogate = false;
3908 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003909 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003910 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3911 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003912 return;
3913 }
Mike Stump11289f42009-09-09 15:08:12 +00003914
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003915 // Add the function template specialization produced by template argument
3916 // deduction as a candidate.
3917 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003918 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003919 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003920}
Mike Stump11289f42009-09-09 15:08:12 +00003921
Douglas Gregora1f013e2008-11-07 22:36:19 +00003922/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003923/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003924/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003925/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003926/// (which may or may not be the same type as the type that the
3927/// conversion function produces).
3928void
3929Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003930 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003931 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003932 Expr *From, QualType ToType,
3933 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003934 assert(!Conversion->getDescribedFunctionTemplate() &&
3935 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003936 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003937 if (!CandidateSet.isNewCandidate(Conversion))
3938 return;
3939
Douglas Gregor27381f32009-11-23 12:27:39 +00003940 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003941 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003942
Douglas Gregora1f013e2008-11-07 22:36:19 +00003943 // Add this candidate
3944 CandidateSet.push_back(OverloadCandidate());
3945 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003946 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003947 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003948 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003949 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003950 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003951 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003952 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003953 Candidate.Viable = true;
3954 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00003955 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003956
Douglas Gregor6affc782010-08-19 15:37:02 +00003957 // C++ [over.match.funcs]p4:
3958 // For conversion functions, the function is considered to be a member of
3959 // the class of the implicit implied object argument for the purpose of
3960 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003961 //
3962 // Determine the implicit conversion sequence for the implicit
3963 // object parameter.
3964 QualType ImplicitParamType = From->getType();
3965 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3966 ImplicitParamType = FromPtrType->getPointeeType();
3967 CXXRecordDecl *ConversionContext
3968 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3969
3970 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003971 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003972 ConversionContext);
3973
John McCall0d1da222010-01-12 00:44:57 +00003974 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003975 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003976 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003977 return;
3978 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003979
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003980 // We won't go through a user-define type conversion function to convert a
3981 // derived to base as such conversions are given Conversion Rank. They only
3982 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3983 QualType FromCanon
3984 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3985 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3986 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3987 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003988 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003989 return;
3990 }
3991
Douglas Gregora1f013e2008-11-07 22:36:19 +00003992 // To determine what the conversion from the result of calling the
3993 // conversion function to the type we're eventually trying to
3994 // convert to (ToType), we need to synthesize a call to the
3995 // conversion function and attempt copy initialization from it. This
3996 // makes sure that we get the right semantics with respect to
3997 // lvalues/rvalues and the type. Fortunately, we can allocate this
3998 // call on the stack and we don't need its arguments to be
3999 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004000 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004001 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004002 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4003 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004004 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004005 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004006
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004007 QualType CallResultType
4008 = Conversion->getConversionType().getNonLValueExprType(Context);
4009 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4010 Candidate.Viable = false;
4011 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4012 return;
4013 }
4014
John McCall7decc9e2010-11-18 06:31:45 +00004015 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4016
Mike Stump11289f42009-09-09 15:08:12 +00004017 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004018 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4019 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00004020 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004021 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004022 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004023 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004024 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00004025 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004026
John McCall0d1da222010-01-12 00:44:57 +00004027 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004028 case ImplicitConversionSequence::StandardConversion:
4029 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004030
4031 // C++ [over.ics.user]p3:
4032 // If the user-defined conversion is specified by a specialization of a
4033 // conversion function template, the second standard conversion sequence
4034 // shall have exact match rank.
4035 if (Conversion->getPrimaryTemplate() &&
4036 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4037 Candidate.Viable = false;
4038 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4039 }
4040
Douglas Gregorcba72b12011-01-21 05:18:22 +00004041 // C++0x [dcl.init.ref]p5:
4042 // In the second case, if the reference is an rvalue reference and
4043 // the second standard conversion sequence of the user-defined
4044 // conversion sequence includes an lvalue-to-rvalue conversion, the
4045 // program is ill-formed.
4046 if (ToType->isRValueReferenceType() &&
4047 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4048 Candidate.Viable = false;
4049 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4050 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004051 break;
4052
4053 case ImplicitConversionSequence::BadConversion:
4054 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004055 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004056 break;
4057
4058 default:
Mike Stump11289f42009-09-09 15:08:12 +00004059 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004060 "Can only end up with a standard conversion sequence or failure");
4061 }
4062}
4063
Douglas Gregor05155d82009-08-21 23:19:43 +00004064/// \brief Adds a conversion function template specialization
4065/// candidate to the overload set, using template argument deduction
4066/// to deduce the template arguments of the conversion function
4067/// template from the type that we are converting to (C++
4068/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004069void
Douglas Gregor05155d82009-08-21 23:19:43 +00004070Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004071 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004072 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004073 Expr *From, QualType ToType,
4074 OverloadCandidateSet &CandidateSet) {
4075 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4076 "Only conversion function templates permitted here");
4077
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004078 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4079 return;
4080
John McCallbc077cf2010-02-08 23:07:23 +00004081 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004082 CXXConversionDecl *Specialization = 0;
4083 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004084 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004085 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004086 CandidateSet.push_back(OverloadCandidate());
4087 OverloadCandidate &Candidate = CandidateSet.back();
4088 Candidate.FoundDecl = FoundDecl;
4089 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4090 Candidate.Viable = false;
4091 Candidate.FailureKind = ovl_fail_bad_deduction;
4092 Candidate.IsSurrogate = false;
4093 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004094 Candidate.ExplicitCallArguments = 1;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004095 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4096 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004097 return;
4098 }
Mike Stump11289f42009-09-09 15:08:12 +00004099
Douglas Gregor05155d82009-08-21 23:19:43 +00004100 // Add the conversion function template specialization produced by
4101 // template argument deduction as a candidate.
4102 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004103 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004104 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004105}
4106
Douglas Gregorab7897a2008-11-19 22:57:39 +00004107/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4108/// converts the given @c Object to a function pointer via the
4109/// conversion function @c Conversion, and then attempts to call it
4110/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4111/// the type of function that we'll eventually be calling.
4112void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004113 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004114 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004115 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00004116 QualType ObjectType,
4117 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004118 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004119 if (!CandidateSet.isNewCandidate(Conversion))
4120 return;
4121
Douglas Gregor27381f32009-11-23 12:27:39 +00004122 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004123 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004124
Douglas Gregorab7897a2008-11-19 22:57:39 +00004125 CandidateSet.push_back(OverloadCandidate());
4126 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004127 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004128 Candidate.Function = 0;
4129 Candidate.Surrogate = Conversion;
4130 Candidate.Viable = true;
4131 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004132 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004133 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004134 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004135
4136 // Determine the implicit conversion sequence for the implicit
4137 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004138 ImplicitConversionSequence ObjectInit
John McCall5c32be02010-08-24 20:38:10 +00004139 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
4140 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004141 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004142 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004143 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004144 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004145 return;
4146 }
4147
4148 // The first conversion is actually a user-defined conversion whose
4149 // first conversion is ObjectInit's standard conversion (which is
4150 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004151 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004152 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004153 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004154 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00004155 Candidate.Conversions[0].UserDefined.FoundConversionFunction
4156 = FoundDecl.getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004157 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004158 = Candidate.Conversions[0].UserDefined.Before;
4159 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4160
Mike Stump11289f42009-09-09 15:08:12 +00004161 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004162 unsigned NumArgsInProto = Proto->getNumArgs();
4163
4164 // (C++ 13.3.2p2): A candidate function having fewer than m
4165 // parameters is viable only if it has an ellipsis in its parameter
4166 // list (8.3.5).
4167 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4168 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004169 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004170 return;
4171 }
4172
4173 // Function types don't have any default arguments, so just check if
4174 // we have enough arguments.
4175 if (NumArgs < NumArgsInProto) {
4176 // Not enough arguments.
4177 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004178 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004179 return;
4180 }
4181
4182 // Determine the implicit conversion sequences for each of the
4183 // arguments.
4184 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4185 if (ArgIdx < NumArgsInProto) {
4186 // (C++ 13.3.2p3): for F to be a viable function, there shall
4187 // exist for each argument an implicit conversion sequence
4188 // (13.3.3.1) that converts that argument to the corresponding
4189 // parameter of F.
4190 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004191 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004192 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004193 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004194 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004195 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004196 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004197 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004198 break;
4199 }
4200 } else {
4201 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4202 // argument for which there is no corresponding parameter is
4203 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004204 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004205 }
4206 }
4207}
4208
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004209/// \brief Add overload candidates for overloaded operators that are
4210/// member functions.
4211///
4212/// Add the overloaded operator candidates that are member functions
4213/// for the operator Op that was used in an operator expression such
4214/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4215/// CandidateSet will store the added overload candidates. (C++
4216/// [over.match.oper]).
4217void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4218 SourceLocation OpLoc,
4219 Expr **Args, unsigned NumArgs,
4220 OverloadCandidateSet& CandidateSet,
4221 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004222 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4223
4224 // C++ [over.match.oper]p3:
4225 // For a unary operator @ with an operand of a type whose
4226 // cv-unqualified version is T1, and for a binary operator @ with
4227 // a left operand of a type whose cv-unqualified version is T1 and
4228 // a right operand of a type whose cv-unqualified version is T2,
4229 // three sets of candidate functions, designated member
4230 // candidates, non-member candidates and built-in candidates, are
4231 // constructed as follows:
4232 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004233
4234 // -- If T1 is a class type, the set of member candidates is the
4235 // result of the qualified lookup of T1::operator@
4236 // (13.3.1.1.1); otherwise, the set of member candidates is
4237 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004238 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004239 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004240 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004241 return;
Mike Stump11289f42009-09-09 15:08:12 +00004242
John McCall27b18f82009-11-17 02:14:36 +00004243 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4244 LookupQualifiedName(Operators, T1Rec->getDecl());
4245 Operators.suppressDiagnostics();
4246
Mike Stump11289f42009-09-09 15:08:12 +00004247 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004248 OperEnd = Operators.end();
4249 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004250 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004251 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004252 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004253 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004254 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004255}
4256
Douglas Gregora11693b2008-11-12 17:17:38 +00004257/// AddBuiltinCandidate - Add a candidate for a built-in
4258/// operator. ResultTy and ParamTys are the result and parameter types
4259/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004260/// arguments being passed to the candidate. IsAssignmentOperator
4261/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004262/// operator. NumContextualBoolArguments is the number of arguments
4263/// (at the beginning of the argument list) that will be contextually
4264/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004265void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004266 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004267 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004268 bool IsAssignmentOperator,
4269 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004270 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004271 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004272
Douglas Gregora11693b2008-11-12 17:17:38 +00004273 // Add this candidate
4274 CandidateSet.push_back(OverloadCandidate());
4275 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004276 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004277 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004278 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004279 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004280 Candidate.BuiltinTypes.ResultTy = ResultTy;
4281 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4282 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4283
4284 // Determine the implicit conversion sequences for each of the
4285 // arguments.
4286 Candidate.Viable = true;
4287 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004288 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004289 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004290 // C++ [over.match.oper]p4:
4291 // For the built-in assignment operators, conversions of the
4292 // left operand are restricted as follows:
4293 // -- no temporaries are introduced to hold the left operand, and
4294 // -- no user-defined conversions are applied to the left
4295 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004296 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004297 //
4298 // We block these conversions by turning off user-defined
4299 // conversions, since that is the only way that initialization of
4300 // a reference to a non-class type can occur from something that
4301 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004302 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004303 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004304 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004305 Candidate.Conversions[ArgIdx]
4306 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004307 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004308 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004309 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004310 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004311 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004312 }
John McCall0d1da222010-01-12 00:44:57 +00004313 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004314 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004315 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004316 break;
4317 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004318 }
4319}
4320
4321/// BuiltinCandidateTypeSet - A set of types that will be used for the
4322/// candidate operator functions for built-in operators (C++
4323/// [over.built]). The types are separated into pointer types and
4324/// enumeration types.
4325class BuiltinCandidateTypeSet {
4326 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004327 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004328
4329 /// PointerTypes - The set of pointer types that will be used in the
4330 /// built-in candidates.
4331 TypeSet PointerTypes;
4332
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004333 /// MemberPointerTypes - The set of member pointer types that will be
4334 /// used in the built-in candidates.
4335 TypeSet MemberPointerTypes;
4336
Douglas Gregora11693b2008-11-12 17:17:38 +00004337 /// EnumerationTypes - The set of enumeration types that will be
4338 /// used in the built-in candidates.
4339 TypeSet EnumerationTypes;
4340
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004341 /// \brief The set of vector types that will be used in the built-in
4342 /// candidates.
4343 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004344
4345 /// \brief A flag indicating non-record types are viable candidates
4346 bool HasNonRecordTypes;
4347
4348 /// \brief A flag indicating whether either arithmetic or enumeration types
4349 /// were present in the candidate set.
4350 bool HasArithmeticOrEnumeralTypes;
4351
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004352 /// Sema - The semantic analysis instance where we are building the
4353 /// candidate type set.
4354 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004355
Douglas Gregora11693b2008-11-12 17:17:38 +00004356 /// Context - The AST context in which we will build the type sets.
4357 ASTContext &Context;
4358
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004359 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4360 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004361 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004362
4363public:
4364 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004365 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004366
Mike Stump11289f42009-09-09 15:08:12 +00004367 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004368 : HasNonRecordTypes(false),
4369 HasArithmeticOrEnumeralTypes(false),
4370 SemaRef(SemaRef),
4371 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004372
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004373 void AddTypesConvertedFrom(QualType Ty,
4374 SourceLocation Loc,
4375 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004376 bool AllowExplicitConversions,
4377 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004378
4379 /// pointer_begin - First pointer type found;
4380 iterator pointer_begin() { return PointerTypes.begin(); }
4381
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004382 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004383 iterator pointer_end() { return PointerTypes.end(); }
4384
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004385 /// member_pointer_begin - First member pointer type found;
4386 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4387
4388 /// member_pointer_end - Past the last member pointer type found;
4389 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4390
Douglas Gregora11693b2008-11-12 17:17:38 +00004391 /// enumeration_begin - First enumeration type found;
4392 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4393
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004394 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004395 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004396
4397 iterator vector_begin() { return VectorTypes.begin(); }
4398 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00004399
4400 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4401 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregora11693b2008-11-12 17:17:38 +00004402};
4403
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004404/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004405/// the set of pointer types along with any more-qualified variants of
4406/// that type. For example, if @p Ty is "int const *", this routine
4407/// will add "int const *", "int const volatile *", "int const
4408/// restrict *", and "int const volatile restrict *" to the set of
4409/// pointer types. Returns true if the add of @p Ty itself succeeded,
4410/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004411///
4412/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004413bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004414BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4415 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004416
Douglas Gregora11693b2008-11-12 17:17:38 +00004417 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004418 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004419 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004420
4421 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004422 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004423 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004424 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004425 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004426 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004427 buildObjCPtr = true;
4428 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004429 else
4430 assert(false && "type was not a pointer type!");
4431 }
4432 else
4433 PointeeTy = PointerTy->getPointeeType();
4434
Sebastian Redl4990a632009-11-18 20:39:26 +00004435 // Don't add qualified variants of arrays. For one, they're not allowed
4436 // (the qualifier would sink to the element type), and for another, the
4437 // only overload situation where it matters is subscript or pointer +- int,
4438 // and those shouldn't have qualifier variants anyway.
4439 if (PointeeTy->isArrayType())
4440 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004441 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004442 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004443 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004444 bool hasVolatile = VisibleQuals.hasVolatile();
4445 bool hasRestrict = VisibleQuals.hasRestrict();
4446
John McCall8ccfcb52009-09-24 19:53:00 +00004447 // Iterate through all strict supersets of BaseCVR.
4448 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4449 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004450 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4451 // in the types.
4452 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4453 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004454 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004455 if (!buildObjCPtr)
4456 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4457 else
4458 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004459 }
4460
4461 return true;
4462}
4463
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004464/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4465/// to the set of pointer types along with any more-qualified variants of
4466/// that type. For example, if @p Ty is "int const *", this routine
4467/// will add "int const *", "int const volatile *", "int const
4468/// restrict *", and "int const volatile restrict *" to the set of
4469/// pointer types. Returns true if the add of @p Ty itself succeeded,
4470/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004471///
4472/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004473bool
4474BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4475 QualType Ty) {
4476 // Insert this type.
4477 if (!MemberPointerTypes.insert(Ty))
4478 return false;
4479
John McCall8ccfcb52009-09-24 19:53:00 +00004480 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4481 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004482
John McCall8ccfcb52009-09-24 19:53:00 +00004483 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004484 // Don't add qualified variants of arrays. For one, they're not allowed
4485 // (the qualifier would sink to the element type), and for another, the
4486 // only overload situation where it matters is subscript or pointer +- int,
4487 // and those shouldn't have qualifier variants anyway.
4488 if (PointeeTy->isArrayType())
4489 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004490 const Type *ClassTy = PointerTy->getClass();
4491
4492 // Iterate through all strict supersets of the pointee type's CVR
4493 // qualifiers.
4494 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4495 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4496 if ((CVR | BaseCVR) != CVR) continue;
4497
4498 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00004499 MemberPointerTypes.insert(
4500 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004501 }
4502
4503 return true;
4504}
4505
Douglas Gregora11693b2008-11-12 17:17:38 +00004506/// AddTypesConvertedFrom - Add each of the types to which the type @p
4507/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004508/// primarily interested in pointer types and enumeration types. We also
4509/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004510/// AllowUserConversions is true if we should look at the conversion
4511/// functions of a class type, and AllowExplicitConversions if we
4512/// should also include the explicit conversion functions of a class
4513/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004514void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004515BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004516 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004517 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004518 bool AllowExplicitConversions,
4519 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004520 // Only deal with canonical types.
4521 Ty = Context.getCanonicalType(Ty);
4522
4523 // Look through reference types; they aren't part of the type of an
4524 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004525 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004526 Ty = RefTy->getPointeeType();
4527
John McCall33ddac02011-01-19 10:06:00 +00004528 // If we're dealing with an array type, decay to the pointer.
4529 if (Ty->isArrayType())
4530 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4531
4532 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004533 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004534
Chandler Carruth00a38332010-12-13 01:44:01 +00004535 // Flag if we ever add a non-record type.
4536 const RecordType *TyRec = Ty->getAs<RecordType>();
4537 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4538
Chandler Carruth00a38332010-12-13 01:44:01 +00004539 // Flag if we encounter an arithmetic type.
4540 HasArithmeticOrEnumeralTypes =
4541 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4542
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004543 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4544 PointerTypes.insert(Ty);
4545 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004546 // Insert our type, and its more-qualified variants, into the set
4547 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004548 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004549 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004550 } else if (Ty->isMemberPointerType()) {
4551 // Member pointers are far easier, since the pointee can't be converted.
4552 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4553 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004554 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004555 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00004556 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004557 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004558 // We treat vector types as arithmetic types in many contexts as an
4559 // extension.
4560 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004561 VectorTypes.insert(Ty);
Chandler Carruth00a38332010-12-13 01:44:01 +00004562 } else if (AllowUserConversions && TyRec) {
4563 // No conversion functions in incomplete types.
4564 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4565 return;
Mike Stump11289f42009-09-09 15:08:12 +00004566
Chandler Carruth00a38332010-12-13 01:44:01 +00004567 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4568 const UnresolvedSetImpl *Conversions
4569 = ClassDecl->getVisibleConversionFunctions();
4570 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4571 E = Conversions->end(); I != E; ++I) {
4572 NamedDecl *D = I.getDecl();
4573 if (isa<UsingShadowDecl>(D))
4574 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004575
Chandler Carruth00a38332010-12-13 01:44:01 +00004576 // Skip conversion function templates; they don't tell us anything
4577 // about which builtin types we can convert to.
4578 if (isa<FunctionTemplateDecl>(D))
4579 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00004580
Chandler Carruth00a38332010-12-13 01:44:01 +00004581 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4582 if (AllowExplicitConversions || !Conv->isExplicit()) {
4583 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4584 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004585 }
4586 }
4587 }
4588}
4589
Douglas Gregor84605ae2009-08-24 13:43:27 +00004590/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4591/// the volatile- and non-volatile-qualified assignment operators for the
4592/// given type to the candidate set.
4593static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4594 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004595 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004596 unsigned NumArgs,
4597 OverloadCandidateSet &CandidateSet) {
4598 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004599
Douglas Gregor84605ae2009-08-24 13:43:27 +00004600 // T& operator=(T&, T)
4601 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4602 ParamTypes[1] = T;
4603 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4604 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004605
Douglas Gregor84605ae2009-08-24 13:43:27 +00004606 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4607 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004608 ParamTypes[0]
4609 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004610 ParamTypes[1] = T;
4611 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004612 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004613 }
4614}
Mike Stump11289f42009-09-09 15:08:12 +00004615
Sebastian Redl1054fae2009-10-25 17:03:50 +00004616/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4617/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004618static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4619 Qualifiers VRQuals;
4620 const RecordType *TyRec;
4621 if (const MemberPointerType *RHSMPType =
4622 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004623 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004624 else
4625 TyRec = ArgExpr->getType()->getAs<RecordType>();
4626 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004627 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004628 VRQuals.addVolatile();
4629 VRQuals.addRestrict();
4630 return VRQuals;
4631 }
4632
4633 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004634 if (!ClassDecl->hasDefinition())
4635 return VRQuals;
4636
John McCallad371252010-01-20 00:46:10 +00004637 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004638 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004639
John McCallad371252010-01-20 00:46:10 +00004640 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004641 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004642 NamedDecl *D = I.getDecl();
4643 if (isa<UsingShadowDecl>(D))
4644 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4645 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004646 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4647 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4648 CanTy = ResTypeRef->getPointeeType();
4649 // Need to go down the pointer/mempointer chain and add qualifiers
4650 // as see them.
4651 bool done = false;
4652 while (!done) {
4653 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4654 CanTy = ResTypePtr->getPointeeType();
4655 else if (const MemberPointerType *ResTypeMPtr =
4656 CanTy->getAs<MemberPointerType>())
4657 CanTy = ResTypeMPtr->getPointeeType();
4658 else
4659 done = true;
4660 if (CanTy.isVolatileQualified())
4661 VRQuals.addVolatile();
4662 if (CanTy.isRestrictQualified())
4663 VRQuals.addRestrict();
4664 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4665 return VRQuals;
4666 }
4667 }
4668 }
4669 return VRQuals;
4670}
John McCall52872982010-11-13 05:51:15 +00004671
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004672namespace {
John McCall52872982010-11-13 05:51:15 +00004673
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004674/// \brief Helper class to manage the addition of builtin operator overload
4675/// candidates. It provides shared state and utility methods used throughout
4676/// the process, as well as a helper method to add each group of builtin
4677/// operator overloads from the standard to a candidate set.
4678class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004679 // Common instance state available to all overload candidate addition methods.
4680 Sema &S;
4681 Expr **Args;
4682 unsigned NumArgs;
4683 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00004684 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruthc6586e52010-12-12 10:35:00 +00004685 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4686 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004687
Chandler Carruthc6586e52010-12-12 10:35:00 +00004688 // Define some constants used to index and iterate over the arithemetic types
4689 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00004690 // The "promoted arithmetic types" are the arithmetic
4691 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00004692 static const unsigned FirstIntegralType = 3;
4693 static const unsigned LastIntegralType = 18;
4694 static const unsigned FirstPromotedIntegralType = 3,
4695 LastPromotedIntegralType = 9;
4696 static const unsigned FirstPromotedArithmeticType = 0,
4697 LastPromotedArithmeticType = 9;
4698 static const unsigned NumArithmeticTypes = 18;
4699
Chandler Carruthc6586e52010-12-12 10:35:00 +00004700 /// \brief Get the canonical type for a given arithmetic type index.
4701 CanQualType getArithmeticType(unsigned index) {
4702 assert(index < NumArithmeticTypes);
4703 static CanQualType ASTContext::* const
4704 ArithmeticTypes[NumArithmeticTypes] = {
4705 // Start of promoted types.
4706 &ASTContext::FloatTy,
4707 &ASTContext::DoubleTy,
4708 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00004709
Chandler Carruthc6586e52010-12-12 10:35:00 +00004710 // Start of integral types.
4711 &ASTContext::IntTy,
4712 &ASTContext::LongTy,
4713 &ASTContext::LongLongTy,
4714 &ASTContext::UnsignedIntTy,
4715 &ASTContext::UnsignedLongTy,
4716 &ASTContext::UnsignedLongLongTy,
4717 // End of promoted types.
4718
4719 &ASTContext::BoolTy,
4720 &ASTContext::CharTy,
4721 &ASTContext::WCharTy,
4722 &ASTContext::Char16Ty,
4723 &ASTContext::Char32Ty,
4724 &ASTContext::SignedCharTy,
4725 &ASTContext::ShortTy,
4726 &ASTContext::UnsignedCharTy,
4727 &ASTContext::UnsignedShortTy,
4728 // End of integral types.
4729 // FIXME: What about complex?
4730 };
4731 return S.Context.*ArithmeticTypes[index];
4732 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004733
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004734 /// \brief Gets the canonical type resulting from the usual arithemetic
4735 /// converions for the given arithmetic types.
4736 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
4737 // Accelerator table for performing the usual arithmetic conversions.
4738 // The rules are basically:
4739 // - if either is floating-point, use the wider floating-point
4740 // - if same signedness, use the higher rank
4741 // - if same size, use unsigned of the higher rank
4742 // - use the larger type
4743 // These rules, together with the axiom that higher ranks are
4744 // never smaller, are sufficient to precompute all of these results
4745 // *except* when dealing with signed types of higher rank.
4746 // (we could precompute SLL x UI for all known platforms, but it's
4747 // better not to make any assumptions).
4748 enum PromotedType {
4749 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
4750 };
4751 static PromotedType ConversionsTable[LastPromotedArithmeticType]
4752 [LastPromotedArithmeticType] = {
4753 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4754 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4755 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4756 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4757 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4758 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4759 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4760 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4761 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
4762 };
4763
4764 assert(L < LastPromotedArithmeticType);
4765 assert(R < LastPromotedArithmeticType);
4766 int Idx = ConversionsTable[L][R];
4767
4768 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004769 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004770
4771 // Slow path: we need to compare widths.
4772 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004773 CanQualType LT = getArithmeticType(L),
4774 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004775 unsigned LW = S.Context.getIntWidth(LT),
4776 RW = S.Context.getIntWidth(RT);
4777
4778 // If they're different widths, use the signed type.
4779 if (LW > RW) return LT;
4780 else if (LW < RW) return RT;
4781
4782 // Otherwise, use the unsigned type of the signed type's rank.
4783 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
4784 assert(L == SLL || R == SLL);
4785 return S.Context.UnsignedLongLongTy;
4786 }
4787
Chandler Carruth5659c0c2010-12-12 09:22:45 +00004788 /// \brief Helper method to factor out the common pattern of adding overloads
4789 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004790 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
4791 bool HasVolatile) {
4792 QualType ParamTypes[2] = {
4793 S.Context.getLValueReferenceType(CandidateTy),
4794 S.Context.IntTy
4795 };
4796
4797 // Non-volatile version.
4798 if (NumArgs == 1)
4799 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4800 else
4801 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4802
4803 // Use a heuristic to reduce number of builtin candidates in the set:
4804 // add volatile version only if there are conversions to a volatile type.
4805 if (HasVolatile) {
4806 ParamTypes[0] =
4807 S.Context.getLValueReferenceType(
4808 S.Context.getVolatileType(CandidateTy));
4809 if (NumArgs == 1)
4810 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4811 else
4812 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4813 }
4814 }
4815
4816public:
4817 BuiltinOperatorOverloadBuilder(
4818 Sema &S, Expr **Args, unsigned NumArgs,
4819 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00004820 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004821 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
4822 OverloadCandidateSet &CandidateSet)
4823 : S(S), Args(Args), NumArgs(NumArgs),
4824 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00004825 HasArithmeticOrEnumeralCandidateType(
4826 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004827 CandidateTypes(CandidateTypes),
4828 CandidateSet(CandidateSet) {
4829 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004830 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004831 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004832 assert(getArithmeticType(LastPromotedIntegralType - 1)
4833 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004834 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004835 assert(getArithmeticType(FirstPromotedArithmeticType)
4836 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004837 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004838 assert(getArithmeticType(LastPromotedArithmeticType - 1)
4839 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004840 "Invalid last promoted arithmetic type");
4841 }
4842
4843 // C++ [over.built]p3:
4844 //
4845 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4846 // is either volatile or empty, there exist candidate operator
4847 // functions of the form
4848 //
4849 // VQ T& operator++(VQ T&);
4850 // T operator++(VQ T&, int);
4851 //
4852 // C++ [over.built]p4:
4853 //
4854 // For every pair (T, VQ), where T is an arithmetic type other
4855 // than bool, and VQ is either volatile or empty, there exist
4856 // candidate operator functions of the form
4857 //
4858 // VQ T& operator--(VQ T&);
4859 // T operator--(VQ T&, int);
4860 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004861 if (!HasArithmeticOrEnumeralCandidateType)
4862 return;
4863
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004864 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
4865 Arith < NumArithmeticTypes; ++Arith) {
4866 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00004867 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004868 VisibleTypeConversionsQuals.hasVolatile());
4869 }
4870 }
4871
4872 // C++ [over.built]p5:
4873 //
4874 // For every pair (T, VQ), where T is a cv-qualified or
4875 // cv-unqualified object type, and VQ is either volatile or
4876 // empty, there exist candidate operator functions of the form
4877 //
4878 // T*VQ& operator++(T*VQ&);
4879 // T*VQ& operator--(T*VQ&);
4880 // T* operator++(T*VQ&, int);
4881 // T* operator--(T*VQ&, int);
4882 void addPlusPlusMinusMinusPointerOverloads() {
4883 for (BuiltinCandidateTypeSet::iterator
4884 Ptr = CandidateTypes[0].pointer_begin(),
4885 PtrEnd = CandidateTypes[0].pointer_end();
4886 Ptr != PtrEnd; ++Ptr) {
4887 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00004888 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004889 continue;
4890
4891 addPlusPlusMinusMinusStyleOverloads(*Ptr,
4892 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4893 VisibleTypeConversionsQuals.hasVolatile()));
4894 }
4895 }
4896
4897 // C++ [over.built]p6:
4898 // For every cv-qualified or cv-unqualified object type T, there
4899 // exist candidate operator functions of the form
4900 //
4901 // T& operator*(T*);
4902 //
4903 // C++ [over.built]p7:
4904 // For every function type T, there exist candidate operator
4905 // functions of the form
4906 // T& operator*(T*);
4907 void addUnaryStarPointerOverloads() {
4908 for (BuiltinCandidateTypeSet::iterator
4909 Ptr = CandidateTypes[0].pointer_begin(),
4910 PtrEnd = CandidateTypes[0].pointer_end();
4911 Ptr != PtrEnd; ++Ptr) {
4912 QualType ParamTy = *Ptr;
4913 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00004914 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
4915 continue;
4916
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004917 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
4918 &ParamTy, Args, 1, CandidateSet);
4919 }
4920 }
4921
4922 // C++ [over.built]p9:
4923 // For every promoted arithmetic type T, there exist candidate
4924 // operator functions of the form
4925 //
4926 // T operator+(T);
4927 // T operator-(T);
4928 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00004929 if (!HasArithmeticOrEnumeralCandidateType)
4930 return;
4931
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004932 for (unsigned Arith = FirstPromotedArithmeticType;
4933 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004934 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004935 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4936 }
4937
4938 // Extension: We also add these operators for vector types.
4939 for (BuiltinCandidateTypeSet::iterator
4940 Vec = CandidateTypes[0].vector_begin(),
4941 VecEnd = CandidateTypes[0].vector_end();
4942 Vec != VecEnd; ++Vec) {
4943 QualType VecTy = *Vec;
4944 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4945 }
4946 }
4947
4948 // C++ [over.built]p8:
4949 // For every type T, there exist candidate operator functions of
4950 // the form
4951 //
4952 // T* operator+(T*);
4953 void addUnaryPlusPointerOverloads() {
4954 for (BuiltinCandidateTypeSet::iterator
4955 Ptr = CandidateTypes[0].pointer_begin(),
4956 PtrEnd = CandidateTypes[0].pointer_end();
4957 Ptr != PtrEnd; ++Ptr) {
4958 QualType ParamTy = *Ptr;
4959 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4960 }
4961 }
4962
4963 // C++ [over.built]p10:
4964 // For every promoted integral type T, there exist candidate
4965 // operator functions of the form
4966 //
4967 // T operator~(T);
4968 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00004969 if (!HasArithmeticOrEnumeralCandidateType)
4970 return;
4971
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004972 for (unsigned Int = FirstPromotedIntegralType;
4973 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004974 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004975 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4976 }
4977
4978 // Extension: We also add this operator for vector types.
4979 for (BuiltinCandidateTypeSet::iterator
4980 Vec = CandidateTypes[0].vector_begin(),
4981 VecEnd = CandidateTypes[0].vector_end();
4982 Vec != VecEnd; ++Vec) {
4983 QualType VecTy = *Vec;
4984 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4985 }
4986 }
4987
4988 // C++ [over.match.oper]p16:
4989 // For every pointer to member type T, there exist candidate operator
4990 // functions of the form
4991 //
4992 // bool operator==(T,T);
4993 // bool operator!=(T,T);
4994 void addEqualEqualOrNotEqualMemberPointerOverloads() {
4995 /// Set of (canonical) types that we've already handled.
4996 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4997
4998 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4999 for (BuiltinCandidateTypeSet::iterator
5000 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5001 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5002 MemPtr != MemPtrEnd;
5003 ++MemPtr) {
5004 // Don't add the same builtin candidate twice.
5005 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5006 continue;
5007
5008 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5009 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5010 CandidateSet);
5011 }
5012 }
5013 }
5014
5015 // C++ [over.built]p15:
5016 //
5017 // For every pointer or enumeration type T, there exist
5018 // candidate operator functions of the form
5019 //
5020 // bool operator<(T, T);
5021 // bool operator>(T, T);
5022 // bool operator<=(T, T);
5023 // bool operator>=(T, T);
5024 // bool operator==(T, T);
5025 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005026 void addRelationalPointerOrEnumeralOverloads() {
5027 // C++ [over.built]p1:
5028 // If there is a user-written candidate with the same name and parameter
5029 // types as a built-in candidate operator function, the built-in operator
5030 // function is hidden and is not included in the set of candidate
5031 // functions.
5032 //
5033 // The text is actually in a note, but if we don't implement it then we end
5034 // up with ambiguities when the user provides an overloaded operator for
5035 // an enumeration type. Note that only enumeration types have this problem,
5036 // so we track which enumeration types we've seen operators for. Also, the
5037 // only other overloaded operator with enumeration argumenst, operator=,
5038 // cannot be overloaded for enumeration types, so this is the only place
5039 // where we must suppress candidates like this.
5040 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5041 UserDefinedBinaryOperators;
5042
5043 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5044 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5045 CandidateTypes[ArgIdx].enumeration_end()) {
5046 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5047 CEnd = CandidateSet.end();
5048 C != CEnd; ++C) {
5049 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5050 continue;
5051
5052 QualType FirstParamType =
5053 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5054 QualType SecondParamType =
5055 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5056
5057 // Skip if either parameter isn't of enumeral type.
5058 if (!FirstParamType->isEnumeralType() ||
5059 !SecondParamType->isEnumeralType())
5060 continue;
5061
5062 // Add this operator to the set of known user-defined operators.
5063 UserDefinedBinaryOperators.insert(
5064 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5065 S.Context.getCanonicalType(SecondParamType)));
5066 }
5067 }
5068 }
5069
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005070 /// Set of (canonical) types that we've already handled.
5071 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5072
5073 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5074 for (BuiltinCandidateTypeSet::iterator
5075 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5076 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5077 Ptr != PtrEnd; ++Ptr) {
5078 // Don't add the same builtin candidate twice.
5079 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5080 continue;
5081
5082 QualType ParamTypes[2] = { *Ptr, *Ptr };
5083 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5084 CandidateSet);
5085 }
5086 for (BuiltinCandidateTypeSet::iterator
5087 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5088 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5089 Enum != EnumEnd; ++Enum) {
5090 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5091
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005092 // Don't add the same builtin candidate twice, or if a user defined
5093 // candidate exists.
5094 if (!AddedTypes.insert(CanonType) ||
5095 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5096 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005097 continue;
5098
5099 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005100 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5101 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005102 }
5103 }
5104 }
5105
5106 // C++ [over.built]p13:
5107 //
5108 // For every cv-qualified or cv-unqualified object type T
5109 // there exist candidate operator functions of the form
5110 //
5111 // T* operator+(T*, ptrdiff_t);
5112 // T& operator[](T*, ptrdiff_t); [BELOW]
5113 // T* operator-(T*, ptrdiff_t);
5114 // T* operator+(ptrdiff_t, T*);
5115 // T& operator[](ptrdiff_t, T*); [BELOW]
5116 //
5117 // C++ [over.built]p14:
5118 //
5119 // For every T, where T is a pointer to object type, there
5120 // exist candidate operator functions of the form
5121 //
5122 // ptrdiff_t operator-(T, T);
5123 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5124 /// Set of (canonical) types that we've already handled.
5125 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5126
5127 for (int Arg = 0; Arg < 2; ++Arg) {
5128 QualType AsymetricParamTypes[2] = {
5129 S.Context.getPointerDiffType(),
5130 S.Context.getPointerDiffType(),
5131 };
5132 for (BuiltinCandidateTypeSet::iterator
5133 Ptr = CandidateTypes[Arg].pointer_begin(),
5134 PtrEnd = CandidateTypes[Arg].pointer_end();
5135 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005136 QualType PointeeTy = (*Ptr)->getPointeeType();
5137 if (!PointeeTy->isObjectType())
5138 continue;
5139
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005140 AsymetricParamTypes[Arg] = *Ptr;
5141 if (Arg == 0 || Op == OO_Plus) {
5142 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5143 // T* operator+(ptrdiff_t, T*);
5144 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5145 CandidateSet);
5146 }
5147 if (Op == OO_Minus) {
5148 // ptrdiff_t operator-(T, T);
5149 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5150 continue;
5151
5152 QualType ParamTypes[2] = { *Ptr, *Ptr };
5153 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5154 Args, 2, CandidateSet);
5155 }
5156 }
5157 }
5158 }
5159
5160 // C++ [over.built]p12:
5161 //
5162 // For every pair of promoted arithmetic types L and R, there
5163 // exist candidate operator functions of the form
5164 //
5165 // LR operator*(L, R);
5166 // LR operator/(L, R);
5167 // LR operator+(L, R);
5168 // LR operator-(L, R);
5169 // bool operator<(L, R);
5170 // bool operator>(L, R);
5171 // bool operator<=(L, R);
5172 // bool operator>=(L, R);
5173 // bool operator==(L, R);
5174 // bool operator!=(L, R);
5175 //
5176 // where LR is the result of the usual arithmetic conversions
5177 // between types L and R.
5178 //
5179 // C++ [over.built]p24:
5180 //
5181 // For every pair of promoted arithmetic types L and R, there exist
5182 // candidate operator functions of the form
5183 //
5184 // LR operator?(bool, L, R);
5185 //
5186 // where LR is the result of the usual arithmetic conversions
5187 // between types L and R.
5188 // Our candidates ignore the first parameter.
5189 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005190 if (!HasArithmeticOrEnumeralCandidateType)
5191 return;
5192
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005193 for (unsigned Left = FirstPromotedArithmeticType;
5194 Left < LastPromotedArithmeticType; ++Left) {
5195 for (unsigned Right = FirstPromotedArithmeticType;
5196 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005197 QualType LandR[2] = { getArithmeticType(Left),
5198 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005199 QualType Result =
5200 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005201 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005202 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5203 }
5204 }
5205
5206 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5207 // conditional operator for vector types.
5208 for (BuiltinCandidateTypeSet::iterator
5209 Vec1 = CandidateTypes[0].vector_begin(),
5210 Vec1End = CandidateTypes[0].vector_end();
5211 Vec1 != Vec1End; ++Vec1) {
5212 for (BuiltinCandidateTypeSet::iterator
5213 Vec2 = CandidateTypes[1].vector_begin(),
5214 Vec2End = CandidateTypes[1].vector_end();
5215 Vec2 != Vec2End; ++Vec2) {
5216 QualType LandR[2] = { *Vec1, *Vec2 };
5217 QualType Result = S.Context.BoolTy;
5218 if (!isComparison) {
5219 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5220 Result = *Vec1;
5221 else
5222 Result = *Vec2;
5223 }
5224
5225 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5226 }
5227 }
5228 }
5229
5230 // C++ [over.built]p17:
5231 //
5232 // For every pair of promoted integral types L and R, there
5233 // exist candidate operator functions of the form
5234 //
5235 // LR operator%(L, R);
5236 // LR operator&(L, R);
5237 // LR operator^(L, R);
5238 // LR operator|(L, R);
5239 // L operator<<(L, R);
5240 // L operator>>(L, R);
5241 //
5242 // where LR is the result of the usual arithmetic conversions
5243 // between types L and R.
5244 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005245 if (!HasArithmeticOrEnumeralCandidateType)
5246 return;
5247
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005248 for (unsigned Left = FirstPromotedIntegralType;
5249 Left < LastPromotedIntegralType; ++Left) {
5250 for (unsigned Right = FirstPromotedIntegralType;
5251 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005252 QualType LandR[2] = { getArithmeticType(Left),
5253 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005254 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5255 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005256 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005257 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5258 }
5259 }
5260 }
5261
5262 // C++ [over.built]p20:
5263 //
5264 // For every pair (T, VQ), where T is an enumeration or
5265 // pointer to member type and VQ is either volatile or
5266 // empty, there exist candidate operator functions of the form
5267 //
5268 // VQ T& operator=(VQ T&, T);
5269 void addAssignmentMemberPointerOrEnumeralOverloads() {
5270 /// Set of (canonical) types that we've already handled.
5271 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5272
5273 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5274 for (BuiltinCandidateTypeSet::iterator
5275 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5276 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5277 Enum != EnumEnd; ++Enum) {
5278 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5279 continue;
5280
5281 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5282 CandidateSet);
5283 }
5284
5285 for (BuiltinCandidateTypeSet::iterator
5286 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5287 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5288 MemPtr != MemPtrEnd; ++MemPtr) {
5289 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5290 continue;
5291
5292 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5293 CandidateSet);
5294 }
5295 }
5296 }
5297
5298 // C++ [over.built]p19:
5299 //
5300 // For every pair (T, VQ), where T is any type and VQ is either
5301 // volatile or empty, there exist candidate operator functions
5302 // of the form
5303 //
5304 // T*VQ& operator=(T*VQ&, T*);
5305 //
5306 // C++ [over.built]p21:
5307 //
5308 // For every pair (T, VQ), where T is a cv-qualified or
5309 // cv-unqualified object type and VQ is either volatile or
5310 // empty, there exist candidate operator functions of the form
5311 //
5312 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5313 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5314 void addAssignmentPointerOverloads(bool isEqualOp) {
5315 /// Set of (canonical) types that we've already handled.
5316 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5317
5318 for (BuiltinCandidateTypeSet::iterator
5319 Ptr = CandidateTypes[0].pointer_begin(),
5320 PtrEnd = CandidateTypes[0].pointer_end();
5321 Ptr != PtrEnd; ++Ptr) {
5322 // If this is operator=, keep track of the builtin candidates we added.
5323 if (isEqualOp)
5324 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005325 else if (!(*Ptr)->getPointeeType()->isObjectType())
5326 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005327
5328 // non-volatile version
5329 QualType ParamTypes[2] = {
5330 S.Context.getLValueReferenceType(*Ptr),
5331 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5332 };
5333 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5334 /*IsAssigmentOperator=*/ isEqualOp);
5335
5336 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5337 VisibleTypeConversionsQuals.hasVolatile()) {
5338 // volatile version
5339 ParamTypes[0] =
5340 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5341 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5342 /*IsAssigmentOperator=*/isEqualOp);
5343 }
5344 }
5345
5346 if (isEqualOp) {
5347 for (BuiltinCandidateTypeSet::iterator
5348 Ptr = CandidateTypes[1].pointer_begin(),
5349 PtrEnd = CandidateTypes[1].pointer_end();
5350 Ptr != PtrEnd; ++Ptr) {
5351 // Make sure we don't add the same candidate twice.
5352 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5353 continue;
5354
Chandler Carruth8e543b32010-12-12 08:17:55 +00005355 QualType ParamTypes[2] = {
5356 S.Context.getLValueReferenceType(*Ptr),
5357 *Ptr,
5358 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005359
5360 // non-volatile version
5361 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5362 /*IsAssigmentOperator=*/true);
5363
5364 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5365 VisibleTypeConversionsQuals.hasVolatile()) {
5366 // volatile version
5367 ParamTypes[0] =
5368 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00005369 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5370 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005371 }
5372 }
5373 }
5374 }
5375
5376 // C++ [over.built]p18:
5377 //
5378 // For every triple (L, VQ, R), where L is an arithmetic type,
5379 // VQ is either volatile or empty, and R is a promoted
5380 // arithmetic type, there exist candidate operator functions of
5381 // the form
5382 //
5383 // VQ L& operator=(VQ L&, R);
5384 // VQ L& operator*=(VQ L&, R);
5385 // VQ L& operator/=(VQ L&, R);
5386 // VQ L& operator+=(VQ L&, R);
5387 // VQ L& operator-=(VQ L&, R);
5388 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005389 if (!HasArithmeticOrEnumeralCandidateType)
5390 return;
5391
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005392 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5393 for (unsigned Right = FirstPromotedArithmeticType;
5394 Right < LastPromotedArithmeticType; ++Right) {
5395 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005396 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005397
5398 // Add this built-in operator as a candidate (VQ is empty).
5399 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005400 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005401 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5402 /*IsAssigmentOperator=*/isEqualOp);
5403
5404 // Add this built-in operator as a candidate (VQ is 'volatile').
5405 if (VisibleTypeConversionsQuals.hasVolatile()) {
5406 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005407 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005408 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005409 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5410 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005411 /*IsAssigmentOperator=*/isEqualOp);
5412 }
5413 }
5414 }
5415
5416 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5417 for (BuiltinCandidateTypeSet::iterator
5418 Vec1 = CandidateTypes[0].vector_begin(),
5419 Vec1End = CandidateTypes[0].vector_end();
5420 Vec1 != Vec1End; ++Vec1) {
5421 for (BuiltinCandidateTypeSet::iterator
5422 Vec2 = CandidateTypes[1].vector_begin(),
5423 Vec2End = CandidateTypes[1].vector_end();
5424 Vec2 != Vec2End; ++Vec2) {
5425 QualType ParamTypes[2];
5426 ParamTypes[1] = *Vec2;
5427 // Add this built-in operator as a candidate (VQ is empty).
5428 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5429 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5430 /*IsAssigmentOperator=*/isEqualOp);
5431
5432 // Add this built-in operator as a candidate (VQ is 'volatile').
5433 if (VisibleTypeConversionsQuals.hasVolatile()) {
5434 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5435 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005436 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5437 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005438 /*IsAssigmentOperator=*/isEqualOp);
5439 }
5440 }
5441 }
5442 }
5443
5444 // C++ [over.built]p22:
5445 //
5446 // For every triple (L, VQ, R), where L is an integral type, VQ
5447 // is either volatile or empty, and R is a promoted integral
5448 // type, there exist candidate operator functions of the form
5449 //
5450 // VQ L& operator%=(VQ L&, R);
5451 // VQ L& operator<<=(VQ L&, R);
5452 // VQ L& operator>>=(VQ L&, R);
5453 // VQ L& operator&=(VQ L&, R);
5454 // VQ L& operator^=(VQ L&, R);
5455 // VQ L& operator|=(VQ L&, R);
5456 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005457 if (!HasArithmeticOrEnumeralCandidateType)
5458 return;
5459
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005460 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5461 for (unsigned Right = FirstPromotedIntegralType;
5462 Right < LastPromotedIntegralType; ++Right) {
5463 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005464 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005465
5466 // Add this built-in operator as a candidate (VQ is empty).
5467 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005468 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005469 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5470 if (VisibleTypeConversionsQuals.hasVolatile()) {
5471 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00005472 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005473 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5474 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5475 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5476 CandidateSet);
5477 }
5478 }
5479 }
5480 }
5481
5482 // C++ [over.operator]p23:
5483 //
5484 // There also exist candidate operator functions of the form
5485 //
5486 // bool operator!(bool);
5487 // bool operator&&(bool, bool);
5488 // bool operator||(bool, bool);
5489 void addExclaimOverload() {
5490 QualType ParamTy = S.Context.BoolTy;
5491 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5492 /*IsAssignmentOperator=*/false,
5493 /*NumContextualBoolArguments=*/1);
5494 }
5495 void addAmpAmpOrPipePipeOverload() {
5496 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5497 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5498 /*IsAssignmentOperator=*/false,
5499 /*NumContextualBoolArguments=*/2);
5500 }
5501
5502 // C++ [over.built]p13:
5503 //
5504 // For every cv-qualified or cv-unqualified object type T there
5505 // exist candidate operator functions of the form
5506 //
5507 // T* operator+(T*, ptrdiff_t); [ABOVE]
5508 // T& operator[](T*, ptrdiff_t);
5509 // T* operator-(T*, ptrdiff_t); [ABOVE]
5510 // T* operator+(ptrdiff_t, T*); [ABOVE]
5511 // T& operator[](ptrdiff_t, T*);
5512 void addSubscriptOverloads() {
5513 for (BuiltinCandidateTypeSet::iterator
5514 Ptr = CandidateTypes[0].pointer_begin(),
5515 PtrEnd = CandidateTypes[0].pointer_end();
5516 Ptr != PtrEnd; ++Ptr) {
5517 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5518 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005519 if (!PointeeType->isObjectType())
5520 continue;
5521
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005522 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5523
5524 // T& operator[](T*, ptrdiff_t)
5525 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5526 }
5527
5528 for (BuiltinCandidateTypeSet::iterator
5529 Ptr = CandidateTypes[1].pointer_begin(),
5530 PtrEnd = CandidateTypes[1].pointer_end();
5531 Ptr != PtrEnd; ++Ptr) {
5532 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5533 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005534 if (!PointeeType->isObjectType())
5535 continue;
5536
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005537 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5538
5539 // T& operator[](ptrdiff_t, T*)
5540 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5541 }
5542 }
5543
5544 // C++ [over.built]p11:
5545 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5546 // C1 is the same type as C2 or is a derived class of C2, T is an object
5547 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5548 // there exist candidate operator functions of the form
5549 //
5550 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5551 //
5552 // where CV12 is the union of CV1 and CV2.
5553 void addArrowStarOverloads() {
5554 for (BuiltinCandidateTypeSet::iterator
5555 Ptr = CandidateTypes[0].pointer_begin(),
5556 PtrEnd = CandidateTypes[0].pointer_end();
5557 Ptr != PtrEnd; ++Ptr) {
5558 QualType C1Ty = (*Ptr);
5559 QualType C1;
5560 QualifierCollector Q1;
5561 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5562 if (!isa<RecordType>(C1))
5563 continue;
5564 // heuristic to reduce number of builtin candidates in the set.
5565 // Add volatile/restrict version only if there are conversions to a
5566 // volatile/restrict type.
5567 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5568 continue;
5569 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5570 continue;
5571 for (BuiltinCandidateTypeSet::iterator
5572 MemPtr = CandidateTypes[1].member_pointer_begin(),
5573 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5574 MemPtr != MemPtrEnd; ++MemPtr) {
5575 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5576 QualType C2 = QualType(mptr->getClass(), 0);
5577 C2 = C2.getUnqualifiedType();
5578 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5579 break;
5580 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5581 // build CV12 T&
5582 QualType T = mptr->getPointeeType();
5583 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5584 T.isVolatileQualified())
5585 continue;
5586 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5587 T.isRestrictQualified())
5588 continue;
5589 T = Q1.apply(S.Context, T);
5590 QualType ResultTy = S.Context.getLValueReferenceType(T);
5591 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5592 }
5593 }
5594 }
5595
5596 // Note that we don't consider the first argument, since it has been
5597 // contextually converted to bool long ago. The candidates below are
5598 // therefore added as binary.
5599 //
5600 // C++ [over.built]p25:
5601 // For every type T, where T is a pointer, pointer-to-member, or scoped
5602 // enumeration type, there exist candidate operator functions of the form
5603 //
5604 // T operator?(bool, T, T);
5605 //
5606 void addConditionalOperatorOverloads() {
5607 /// Set of (canonical) types that we've already handled.
5608 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5609
5610 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5611 for (BuiltinCandidateTypeSet::iterator
5612 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5613 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5614 Ptr != PtrEnd; ++Ptr) {
5615 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5616 continue;
5617
5618 QualType ParamTypes[2] = { *Ptr, *Ptr };
5619 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5620 }
5621
5622 for (BuiltinCandidateTypeSet::iterator
5623 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5624 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5625 MemPtr != MemPtrEnd; ++MemPtr) {
5626 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5627 continue;
5628
5629 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5630 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5631 }
5632
5633 if (S.getLangOptions().CPlusPlus0x) {
5634 for (BuiltinCandidateTypeSet::iterator
5635 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5636 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5637 Enum != EnumEnd; ++Enum) {
5638 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5639 continue;
5640
5641 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5642 continue;
5643
5644 QualType ParamTypes[2] = { *Enum, *Enum };
5645 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5646 }
5647 }
5648 }
5649 }
5650};
5651
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005652} // end anonymous namespace
5653
5654/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5655/// operator overloads to the candidate set (C++ [over.built]), based
5656/// on the operator @p Op and the arguments given. For example, if the
5657/// operator is a binary '+', this routine might add "int
5658/// operator+(int, int)" to cover integer addition.
5659void
5660Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5661 SourceLocation OpLoc,
5662 Expr **Args, unsigned NumArgs,
5663 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005664 // Find all of the types that the arguments can convert to, but only
5665 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00005666 // that make use of these types. Also record whether we encounter non-record
5667 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005668 Qualifiers VisibleTypeConversionsQuals;
5669 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005670 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5671 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00005672
5673 bool HasNonRecordCandidateType = false;
5674 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005675 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5676 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5677 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5678 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5679 OpLoc,
5680 true,
5681 (Op == OO_Exclaim ||
5682 Op == OO_AmpAmp ||
5683 Op == OO_PipePipe),
5684 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00005685 HasNonRecordCandidateType = HasNonRecordCandidateType ||
5686 CandidateTypes[ArgIdx].hasNonRecordTypes();
5687 HasArithmeticOrEnumeralCandidateType =
5688 HasArithmeticOrEnumeralCandidateType ||
5689 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005690 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005691
Chandler Carruth00a38332010-12-13 01:44:01 +00005692 // Exit early when no non-record types have been added to the candidate set
5693 // for any of the arguments to the operator.
5694 if (!HasNonRecordCandidateType)
5695 return;
5696
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005697 // Setup an object to manage the common state for building overloads.
5698 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
5699 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005700 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005701 CandidateTypes, CandidateSet);
5702
5703 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00005704 switch (Op) {
5705 case OO_None:
5706 case NUM_OVERLOADED_OPERATORS:
5707 assert(false && "Expected an overloaded operator");
5708 break;
5709
Chandler Carruth5184de02010-12-12 08:51:33 +00005710 case OO_New:
5711 case OO_Delete:
5712 case OO_Array_New:
5713 case OO_Array_Delete:
5714 case OO_Call:
5715 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
5716 break;
5717
5718 case OO_Comma:
5719 case OO_Arrow:
5720 // C++ [over.match.oper]p3:
5721 // -- For the operator ',', the unary operator '&', or the
5722 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00005723 break;
5724
5725 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00005726 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005727 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00005728 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00005729
5730 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00005731 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005732 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00005733 } else {
5734 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
5735 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5736 }
Douglas Gregord08452f2008-11-19 15:42:04 +00005737 break;
5738
Chandler Carruth5184de02010-12-12 08:51:33 +00005739 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00005740 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00005741 OpBuilder.addUnaryStarPointerOverloads();
5742 else
5743 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5744 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005745
Chandler Carruth5184de02010-12-12 08:51:33 +00005746 case OO_Slash:
5747 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00005748 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005749
5750 case OO_PlusPlus:
5751 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005752 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
5753 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00005754 break;
5755
Douglas Gregor84605ae2009-08-24 13:43:27 +00005756 case OO_EqualEqual:
5757 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005758 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00005759 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00005760
Douglas Gregora11693b2008-11-12 17:17:38 +00005761 case OO_Less:
5762 case OO_Greater:
5763 case OO_LessEqual:
5764 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005765 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00005766 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
5767 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005768
Douglas Gregora11693b2008-11-12 17:17:38 +00005769 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00005770 case OO_Caret:
5771 case OO_Pipe:
5772 case OO_LessLess:
5773 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005774 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00005775 break;
5776
Chandler Carruth5184de02010-12-12 08:51:33 +00005777 case OO_Amp: // '&' is either unary or binary
5778 if (NumArgs == 1)
5779 // C++ [over.match.oper]p3:
5780 // -- For the operator ',', the unary operator '&', or the
5781 // operator '->', the built-in candidates set is empty.
5782 break;
5783
5784 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
5785 break;
5786
5787 case OO_Tilde:
5788 OpBuilder.addUnaryTildePromotedIntegralOverloads();
5789 break;
5790
Douglas Gregora11693b2008-11-12 17:17:38 +00005791 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005792 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005793 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00005794
5795 case OO_PlusEqual:
5796 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005797 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005798 // Fall through.
5799
5800 case OO_StarEqual:
5801 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005802 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005803 break;
5804
5805 case OO_PercentEqual:
5806 case OO_LessLessEqual:
5807 case OO_GreaterGreaterEqual:
5808 case OO_AmpEqual:
5809 case OO_CaretEqual:
5810 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005811 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005812 break;
5813
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005814 case OO_Exclaim:
5815 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00005816 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005817
Douglas Gregora11693b2008-11-12 17:17:38 +00005818 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005819 case OO_PipePipe:
5820 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00005821 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005822
5823 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005824 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005825 break;
5826
5827 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005828 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005829 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005830
5831 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005832 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00005833 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5834 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005835 }
5836}
5837
Douglas Gregore254f902009-02-04 00:32:51 +00005838/// \brief Add function candidates found via argument-dependent lookup
5839/// to the set of overloading candidates.
5840///
5841/// This routine performs argument-dependent name lookup based on the
5842/// given function name (which may also be an operator name) and adds
5843/// all of the overload candidates found by ADL to the overload
5844/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005845void
Douglas Gregore254f902009-02-04 00:32:51 +00005846Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005847 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005848 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005849 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005850 OverloadCandidateSet& CandidateSet,
5851 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005852 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005853
John McCall91f61fc2010-01-26 06:04:06 +00005854 // FIXME: This approach for uniquing ADL results (and removing
5855 // redundant candidates from the set) relies on pointer-equality,
5856 // which means we need to key off the canonical decl. However,
5857 // always going back to the canonical decl might not get us the
5858 // right set of default arguments. What default arguments are
5859 // we supposed to consider on ADL candidates, anyway?
5860
Douglas Gregorcabea402009-09-22 15:41:20 +00005861 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005862 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005863
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005864 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005865 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5866 CandEnd = CandidateSet.end();
5867 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005868 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005869 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005870 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005871 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005872 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005873
5874 // For each of the ADL candidates we found, add it to the overload
5875 // set.
John McCall8fe68082010-01-26 07:16:45 +00005876 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005877 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005878 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005879 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005880 continue;
5881
John McCalla0296f72010-03-19 07:35:19 +00005882 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005883 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005884 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005885 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005886 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005887 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005888 }
Douglas Gregore254f902009-02-04 00:32:51 +00005889}
5890
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005891/// isBetterOverloadCandidate - Determines whether the first overload
5892/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005893bool
John McCall5c32be02010-08-24 20:38:10 +00005894isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00005895 const OverloadCandidate &Cand1,
5896 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005897 SourceLocation Loc,
5898 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005899 // Define viable functions to be better candidates than non-viable
5900 // functions.
5901 if (!Cand2.Viable)
5902 return Cand1.Viable;
5903 else if (!Cand1.Viable)
5904 return false;
5905
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005906 // C++ [over.match.best]p1:
5907 //
5908 // -- if F is a static member function, ICS1(F) is defined such
5909 // that ICS1(F) is neither better nor worse than ICS1(G) for
5910 // any function G, and, symmetrically, ICS1(G) is neither
5911 // better nor worse than ICS1(F).
5912 unsigned StartArg = 0;
5913 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5914 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005915
Douglas Gregord3cb3562009-07-07 23:38:56 +00005916 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005917 // A viable function F1 is defined to be a better function than another
5918 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005919 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005920 unsigned NumArgs = Cand1.Conversions.size();
5921 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5922 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005923 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00005924 switch (CompareImplicitConversionSequences(S,
5925 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005926 Cand2.Conversions[ArgIdx])) {
5927 case ImplicitConversionSequence::Better:
5928 // Cand1 has a better conversion sequence.
5929 HasBetterConversion = true;
5930 break;
5931
5932 case ImplicitConversionSequence::Worse:
5933 // Cand1 can't be better than Cand2.
5934 return false;
5935
5936 case ImplicitConversionSequence::Indistinguishable:
5937 // Do nothing.
5938 break;
5939 }
5940 }
5941
Mike Stump11289f42009-09-09 15:08:12 +00005942 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005943 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005944 if (HasBetterConversion)
5945 return true;
5946
Mike Stump11289f42009-09-09 15:08:12 +00005947 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005948 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005949 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005950 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5951 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005952
5953 // -- F1 and F2 are function template specializations, and the function
5954 // template for F1 is more specialized than the template for F2
5955 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005956 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005957 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00005958 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005959 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00005960 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5961 Cand2.Function->getPrimaryTemplate(),
5962 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005963 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00005964 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00005965 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00005966 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00005967 }
5968
Douglas Gregora1f013e2008-11-07 22:36:19 +00005969 // -- the context is an initialization by user-defined conversion
5970 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5971 // from the return type of F1 to the destination type (i.e.,
5972 // the type of the entity being initialized) is a better
5973 // conversion sequence than the standard conversion sequence
5974 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00005975 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005976 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005977 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00005978 switch (CompareStandardConversionSequences(S,
5979 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005980 Cand2.FinalConversion)) {
5981 case ImplicitConversionSequence::Better:
5982 // Cand1 has a better conversion sequence.
5983 return true;
5984
5985 case ImplicitConversionSequence::Worse:
5986 // Cand1 can't be better than Cand2.
5987 return false;
5988
5989 case ImplicitConversionSequence::Indistinguishable:
5990 // Do nothing
5991 break;
5992 }
5993 }
5994
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005995 return false;
5996}
5997
Mike Stump11289f42009-09-09 15:08:12 +00005998/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005999/// within an overload candidate set.
6000///
6001/// \param CandidateSet the set of candidate functions.
6002///
6003/// \param Loc the location of the function name (or operator symbol) for
6004/// which overload resolution occurs.
6005///
Mike Stump11289f42009-09-09 15:08:12 +00006006/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006007/// function, Best points to the candidate function found.
6008///
6009/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006010OverloadingResult
6011OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006012 iterator &Best,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006013 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006014 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006015 Best = end();
6016 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6017 if (Cand->Viable)
Douglas Gregord5b730c92010-09-12 08:07:23 +00006018 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
6019 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006020 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006021 }
6022
6023 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006024 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006025 return OR_No_Viable_Function;
6026
6027 // Make sure that this function is better than every other viable
6028 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006029 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006030 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006031 Cand != Best &&
Douglas Gregord5b730c92010-09-12 08:07:23 +00006032 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
6033 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006034 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006035 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006036 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006037 }
Mike Stump11289f42009-09-09 15:08:12 +00006038
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006039 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006040 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006041 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006042 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006043 return OR_Deleted;
6044
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006045 // C++ [basic.def.odr]p2:
6046 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00006047 // when referred to from a potentially-evaluated expression. [Note: this
6048 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006049 // (clause 13), user-defined conversions (12.3.2), allocation function for
6050 // placement new (5.3.4), as well as non-default initialization (8.5).
6051 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00006052 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006053
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006054 return OR_Success;
6055}
6056
John McCall53262c92010-01-12 02:15:36 +00006057namespace {
6058
6059enum OverloadCandidateKind {
6060 oc_function,
6061 oc_method,
6062 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006063 oc_function_template,
6064 oc_method_template,
6065 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006066 oc_implicit_default_constructor,
6067 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006068 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00006069};
6070
John McCalle1ac8d12010-01-13 00:25:19 +00006071OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6072 FunctionDecl *Fn,
6073 std::string &Description) {
6074 bool isTemplate = false;
6075
6076 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6077 isTemplate = true;
6078 Description = S.getTemplateArgumentBindingsText(
6079 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6080 }
John McCallfd0b2f82010-01-06 09:43:14 +00006081
6082 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006083 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006084 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006085
John McCall53262c92010-01-12 02:15:36 +00006086 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6087 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006088 }
6089
6090 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6091 // This actually gets spelled 'candidate function' for now, but
6092 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006093 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006094 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006095
Douglas Gregorec3bec02010-09-27 22:37:28 +00006096 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006097 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006098 return oc_implicit_copy_assignment;
6099 }
6100
John McCalle1ac8d12010-01-13 00:25:19 +00006101 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006102}
6103
6104} // end anonymous namespace
6105
6106// Notes the location of an overload candidate.
6107void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006108 std::string FnDesc;
6109 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6110 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6111 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00006112}
6113
John McCall0d1da222010-01-12 00:44:57 +00006114/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6115/// "lead" diagnostic; it will be given two arguments, the source and
6116/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006117void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6118 Sema &S,
6119 SourceLocation CaretLoc,
6120 const PartialDiagnostic &PDiag) const {
6121 S.Diag(CaretLoc, PDiag)
6122 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006123 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006124 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6125 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006126 }
John McCall12f97bc2010-01-08 04:41:39 +00006127}
6128
John McCall0d1da222010-01-12 00:44:57 +00006129namespace {
6130
John McCall6a61b522010-01-13 09:16:55 +00006131void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6132 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6133 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006134 assert(Cand->Function && "for now, candidate must be a function");
6135 FunctionDecl *Fn = Cand->Function;
6136
6137 // There's a conversion slot for the object argument if this is a
6138 // non-constructor method. Note that 'I' corresponds the
6139 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006140 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006141 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006142 if (I == 0)
6143 isObjectArgument = true;
6144 else
6145 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006146 }
6147
John McCalle1ac8d12010-01-13 00:25:19 +00006148 std::string FnDesc;
6149 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6150
John McCall6a61b522010-01-13 09:16:55 +00006151 Expr *FromExpr = Conv.Bad.FromExpr;
6152 QualType FromTy = Conv.Bad.getFromType();
6153 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006154
John McCallfb7ad0f2010-02-02 02:42:52 +00006155 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006156 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006157 Expr *E = FromExpr->IgnoreParens();
6158 if (isa<UnaryOperator>(E))
6159 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006160 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006161
6162 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6163 << (unsigned) FnKind << FnDesc
6164 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6165 << ToTy << Name << I+1;
6166 return;
6167 }
6168
John McCall6d174642010-01-23 08:10:49 +00006169 // Do some hand-waving analysis to see if the non-viability is due
6170 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006171 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6172 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6173 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6174 CToTy = RT->getPointeeType();
6175 else {
6176 // TODO: detect and diagnose the full richness of const mismatches.
6177 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6178 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6179 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6180 }
6181
6182 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6183 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6184 // It is dumb that we have to do this here.
6185 while (isa<ArrayType>(CFromTy))
6186 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6187 while (isa<ArrayType>(CToTy))
6188 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6189
6190 Qualifiers FromQs = CFromTy.getQualifiers();
6191 Qualifiers ToQs = CToTy.getQualifiers();
6192
6193 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6194 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6195 << (unsigned) FnKind << FnDesc
6196 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6197 << FromTy
6198 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6199 << (unsigned) isObjectArgument << I+1;
6200 return;
6201 }
6202
6203 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6204 assert(CVR && "unexpected qualifiers mismatch");
6205
6206 if (isObjectArgument) {
6207 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6208 << (unsigned) FnKind << FnDesc
6209 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6210 << FromTy << (CVR - 1);
6211 } else {
6212 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6213 << (unsigned) FnKind << FnDesc
6214 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6215 << FromTy << (CVR - 1) << I+1;
6216 }
6217 return;
6218 }
6219
John McCall6d174642010-01-23 08:10:49 +00006220 // Diagnose references or pointers to incomplete types differently,
6221 // since it's far from impossible that the incompleteness triggered
6222 // the failure.
6223 QualType TempFromTy = FromTy.getNonReferenceType();
6224 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6225 TempFromTy = PTy->getPointeeType();
6226 if (TempFromTy->isIncompleteType()) {
6227 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6228 << (unsigned) FnKind << FnDesc
6229 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6230 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6231 return;
6232 }
6233
Douglas Gregor56f2e342010-06-30 23:01:39 +00006234 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006235 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006236 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6237 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6238 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6239 FromPtrTy->getPointeeType()) &&
6240 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6241 !ToPtrTy->getPointeeType()->isIncompleteType() &&
6242 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
6243 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006244 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006245 }
6246 } else if (const ObjCObjectPointerType *FromPtrTy
6247 = FromTy->getAs<ObjCObjectPointerType>()) {
6248 if (const ObjCObjectPointerType *ToPtrTy
6249 = ToTy->getAs<ObjCObjectPointerType>())
6250 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6251 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6252 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6253 FromPtrTy->getPointeeType()) &&
6254 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006255 BaseToDerivedConversion = 2;
6256 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6257 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6258 !FromTy->isIncompleteType() &&
6259 !ToRefTy->getPointeeType()->isIncompleteType() &&
6260 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6261 BaseToDerivedConversion = 3;
6262 }
6263
6264 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00006265 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006266 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006267 << (unsigned) FnKind << FnDesc
6268 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006269 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006270 << FromTy << ToTy << I+1;
6271 return;
6272 }
6273
John McCall47000992010-01-14 03:28:57 +00006274 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006275 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6276 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006277 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006278 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00006279}
6280
6281void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6282 unsigned NumFormalArgs) {
6283 // TODO: treat calls to a missing default constructor as a special case
6284
6285 FunctionDecl *Fn = Cand->Function;
6286 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6287
6288 unsigned MinParams = Fn->getMinRequiredArguments();
6289
6290 // at least / at most / exactly
6291 unsigned mode, modeCount;
6292 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006293 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6294 (Cand->FailureKind == ovl_fail_bad_deduction &&
6295 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
Douglas Gregor7825bf32011-01-06 22:09:01 +00006296 if (MinParams != FnTy->getNumArgs() ||
6297 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00006298 mode = 0; // "at least"
6299 else
6300 mode = 2; // "exactly"
6301 modeCount = MinParams;
6302 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006303 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6304 (Cand->FailureKind == ovl_fail_bad_deduction &&
6305 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006306 if (MinParams != FnTy->getNumArgs())
6307 mode = 1; // "at most"
6308 else
6309 mode = 2; // "exactly"
6310 modeCount = FnTy->getNumArgs();
6311 }
6312
6313 std::string Description;
6314 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6315
6316 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00006317 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6318 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00006319}
6320
John McCall8b9ed552010-02-01 18:53:26 +00006321/// Diagnose a failed template-argument deduction.
6322void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6323 Expr **Args, unsigned NumArgs) {
6324 FunctionDecl *Fn = Cand->Function; // pattern
6325
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006326 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006327 NamedDecl *ParamD;
6328 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6329 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6330 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006331 switch (Cand->DeductionFailure.Result) {
6332 case Sema::TDK_Success:
6333 llvm_unreachable("TDK_success while diagnosing bad deduction");
6334
6335 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006336 assert(ParamD && "no parameter found for incomplete deduction result");
6337 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6338 << ParamD->getDeclName();
6339 return;
6340 }
6341
John McCall42d7d192010-08-05 09:05:08 +00006342 case Sema::TDK_Underqualified: {
6343 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6344 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6345
6346 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6347
6348 // Param will have been canonicalized, but it should just be a
6349 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00006350 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00006351 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00006352 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00006353 assert(S.Context.hasSameType(Param, NonCanonParam));
6354
6355 // Arg has also been canonicalized, but there's nothing we can do
6356 // about that. It also doesn't matter as much, because it won't
6357 // have any template parameters in it (because deduction isn't
6358 // done on dependent types).
6359 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6360
6361 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6362 << ParamD->getDeclName() << Arg << NonCanonParam;
6363 return;
6364 }
6365
6366 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00006367 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006368 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006369 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006370 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006371 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006372 which = 1;
6373 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006374 which = 2;
6375 }
6376
6377 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6378 << which << ParamD->getDeclName()
6379 << *Cand->DeductionFailure.getFirstArg()
6380 << *Cand->DeductionFailure.getSecondArg();
6381 return;
6382 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006383
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006384 case Sema::TDK_InvalidExplicitArguments:
6385 assert(ParamD && "no parameter found for invalid explicit arguments");
6386 if (ParamD->getDeclName())
6387 S.Diag(Fn->getLocation(),
6388 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6389 << ParamD->getDeclName();
6390 else {
6391 int index = 0;
6392 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6393 index = TTP->getIndex();
6394 else if (NonTypeTemplateParmDecl *NTTP
6395 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6396 index = NTTP->getIndex();
6397 else
6398 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6399 S.Diag(Fn->getLocation(),
6400 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6401 << (index + 1);
6402 }
6403 return;
6404
Douglas Gregor02eb4832010-05-08 18:13:28 +00006405 case Sema::TDK_TooManyArguments:
6406 case Sema::TDK_TooFewArguments:
6407 DiagnoseArityMismatch(S, Cand, NumArgs);
6408 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006409
6410 case Sema::TDK_InstantiationDepth:
6411 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6412 return;
6413
6414 case Sema::TDK_SubstitutionFailure: {
6415 std::string ArgString;
6416 if (TemplateArgumentList *Args
6417 = Cand->DeductionFailure.getTemplateArgumentList())
6418 ArgString = S.getTemplateArgumentBindingsText(
6419 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6420 *Args);
6421 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6422 << ArgString;
6423 return;
6424 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006425
John McCall8b9ed552010-02-01 18:53:26 +00006426 // TODO: diagnose these individually, then kill off
6427 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006428 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006429 case Sema::TDK_FailedOverloadResolution:
6430 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6431 return;
6432 }
6433}
6434
6435/// Generates a 'note' diagnostic for an overload candidate. We've
6436/// already generated a primary error at the call site.
6437///
6438/// It really does need to be a single diagnostic with its caret
6439/// pointed at the candidate declaration. Yes, this creates some
6440/// major challenges of technical writing. Yes, this makes pointing
6441/// out problems with specific arguments quite awkward. It's still
6442/// better than generating twenty screens of text for every failed
6443/// overload.
6444///
6445/// It would be great to be able to express per-candidate problems
6446/// more richly for those diagnostic clients that cared, but we'd
6447/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006448void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6449 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006450 FunctionDecl *Fn = Cand->Function;
6451
John McCall12f97bc2010-01-08 04:41:39 +00006452 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00006453 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006454 std::string FnDesc;
6455 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006456
6457 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006458 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00006459 return;
John McCall12f97bc2010-01-08 04:41:39 +00006460 }
6461
John McCalle1ac8d12010-01-13 00:25:19 +00006462 // We don't really have anything else to say about viable candidates.
6463 if (Cand->Viable) {
6464 S.NoteOverloadCandidate(Fn);
6465 return;
6466 }
John McCall0d1da222010-01-12 00:44:57 +00006467
John McCall6a61b522010-01-13 09:16:55 +00006468 switch (Cand->FailureKind) {
6469 case ovl_fail_too_many_arguments:
6470 case ovl_fail_too_few_arguments:
6471 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006472
John McCall6a61b522010-01-13 09:16:55 +00006473 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006474 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6475
John McCallfe796dd2010-01-23 05:17:32 +00006476 case ovl_fail_trivial_conversion:
6477 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006478 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006479 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006480
John McCall65eb8792010-02-25 01:37:24 +00006481 case ovl_fail_bad_conversion: {
6482 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6483 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006484 if (Cand->Conversions[I].isBad())
6485 return DiagnoseBadConversion(S, Cand, I);
6486
6487 // FIXME: this currently happens when we're called from SemaInit
6488 // when user-conversion overload fails. Figure out how to handle
6489 // those conditions and diagnose them well.
6490 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006491 }
John McCall65eb8792010-02-25 01:37:24 +00006492 }
John McCalld3224162010-01-08 00:58:21 +00006493}
6494
6495void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6496 // Desugar the type of the surrogate down to a function type,
6497 // retaining as many typedefs as possible while still showing
6498 // the function type (and, therefore, its parameter types).
6499 QualType FnType = Cand->Surrogate->getConversionType();
6500 bool isLValueReference = false;
6501 bool isRValueReference = false;
6502 bool isPointer = false;
6503 if (const LValueReferenceType *FnTypeRef =
6504 FnType->getAs<LValueReferenceType>()) {
6505 FnType = FnTypeRef->getPointeeType();
6506 isLValueReference = true;
6507 } else if (const RValueReferenceType *FnTypeRef =
6508 FnType->getAs<RValueReferenceType>()) {
6509 FnType = FnTypeRef->getPointeeType();
6510 isRValueReference = true;
6511 }
6512 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6513 FnType = FnTypePtr->getPointeeType();
6514 isPointer = true;
6515 }
6516 // Desugar down to a function type.
6517 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6518 // Reconstruct the pointer/reference as appropriate.
6519 if (isPointer) FnType = S.Context.getPointerType(FnType);
6520 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6521 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6522
6523 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6524 << FnType;
6525}
6526
6527void NoteBuiltinOperatorCandidate(Sema &S,
6528 const char *Opc,
6529 SourceLocation OpLoc,
6530 OverloadCandidate *Cand) {
6531 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6532 std::string TypeStr("operator");
6533 TypeStr += Opc;
6534 TypeStr += "(";
6535 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6536 if (Cand->Conversions.size() == 1) {
6537 TypeStr += ")";
6538 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6539 } else {
6540 TypeStr += ", ";
6541 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6542 TypeStr += ")";
6543 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6544 }
6545}
6546
6547void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6548 OverloadCandidate *Cand) {
6549 unsigned NoOperands = Cand->Conversions.size();
6550 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6551 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006552 if (ICS.isBad()) break; // all meaningless after first invalid
6553 if (!ICS.isAmbiguous()) continue;
6554
John McCall5c32be02010-08-24 20:38:10 +00006555 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006556 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006557 }
6558}
6559
John McCall3712d9e2010-01-15 23:32:50 +00006560SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6561 if (Cand->Function)
6562 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006563 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006564 return Cand->Surrogate->getLocation();
6565 return SourceLocation();
6566}
6567
John McCallad2587a2010-01-12 00:48:53 +00006568struct CompareOverloadCandidatesForDisplay {
6569 Sema &S;
6570 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006571
6572 bool operator()(const OverloadCandidate *L,
6573 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006574 // Fast-path this check.
6575 if (L == R) return false;
6576
John McCall12f97bc2010-01-08 04:41:39 +00006577 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006578 if (L->Viable) {
6579 if (!R->Viable) return true;
6580
6581 // TODO: introduce a tri-valued comparison for overload
6582 // candidates. Would be more worthwhile if we had a sort
6583 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006584 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6585 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006586 } else if (R->Viable)
6587 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006588
John McCall3712d9e2010-01-15 23:32:50 +00006589 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006590
John McCall3712d9e2010-01-15 23:32:50 +00006591 // Criteria by which we can sort non-viable candidates:
6592 if (!L->Viable) {
6593 // 1. Arity mismatches come after other candidates.
6594 if (L->FailureKind == ovl_fail_too_many_arguments ||
6595 L->FailureKind == ovl_fail_too_few_arguments)
6596 return false;
6597 if (R->FailureKind == ovl_fail_too_many_arguments ||
6598 R->FailureKind == ovl_fail_too_few_arguments)
6599 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006600
John McCallfe796dd2010-01-23 05:17:32 +00006601 // 2. Bad conversions come first and are ordered by the number
6602 // of bad conversions and quality of good conversions.
6603 if (L->FailureKind == ovl_fail_bad_conversion) {
6604 if (R->FailureKind != ovl_fail_bad_conversion)
6605 return true;
6606
6607 // If there's any ordering between the defined conversions...
6608 // FIXME: this might not be transitive.
6609 assert(L->Conversions.size() == R->Conversions.size());
6610
6611 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006612 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6613 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006614 switch (CompareImplicitConversionSequences(S,
6615 L->Conversions[I],
6616 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006617 case ImplicitConversionSequence::Better:
6618 leftBetter++;
6619 break;
6620
6621 case ImplicitConversionSequence::Worse:
6622 leftBetter--;
6623 break;
6624
6625 case ImplicitConversionSequence::Indistinguishable:
6626 break;
6627 }
6628 }
6629 if (leftBetter > 0) return true;
6630 if (leftBetter < 0) return false;
6631
6632 } else if (R->FailureKind == ovl_fail_bad_conversion)
6633 return false;
6634
John McCall3712d9e2010-01-15 23:32:50 +00006635 // TODO: others?
6636 }
6637
6638 // Sort everything else by location.
6639 SourceLocation LLoc = GetLocationForCandidate(L);
6640 SourceLocation RLoc = GetLocationForCandidate(R);
6641
6642 // Put candidates without locations (e.g. builtins) at the end.
6643 if (LLoc.isInvalid()) return false;
6644 if (RLoc.isInvalid()) return true;
6645
6646 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006647 }
6648};
6649
John McCallfe796dd2010-01-23 05:17:32 +00006650/// CompleteNonViableCandidate - Normally, overload resolution only
6651/// computes up to the first
6652void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6653 Expr **Args, unsigned NumArgs) {
6654 assert(!Cand->Viable);
6655
6656 // Don't do anything on failures other than bad conversion.
6657 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6658
6659 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006660 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006661 unsigned ConvCount = Cand->Conversions.size();
6662 while (true) {
6663 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6664 ConvIdx++;
6665 if (Cand->Conversions[ConvIdx - 1].isBad())
6666 break;
6667 }
6668
6669 if (ConvIdx == ConvCount)
6670 return;
6671
John McCall65eb8792010-02-25 01:37:24 +00006672 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6673 "remaining conversion is initialized?");
6674
Douglas Gregoradc7a702010-04-16 17:45:54 +00006675 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006676 // operation somehow.
6677 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006678
6679 const FunctionProtoType* Proto;
6680 unsigned ArgIdx = ConvIdx;
6681
6682 if (Cand->IsSurrogate) {
6683 QualType ConvType
6684 = Cand->Surrogate->getConversionType().getNonReferenceType();
6685 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6686 ConvType = ConvPtrType->getPointeeType();
6687 Proto = ConvType->getAs<FunctionProtoType>();
6688 ArgIdx--;
6689 } else if (Cand->Function) {
6690 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6691 if (isa<CXXMethodDecl>(Cand->Function) &&
6692 !isa<CXXConstructorDecl>(Cand->Function))
6693 ArgIdx--;
6694 } else {
6695 // Builtin binary operator with a bad first conversion.
6696 assert(ConvCount <= 3);
6697 for (; ConvIdx != ConvCount; ++ConvIdx)
6698 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006699 = TryCopyInitialization(S, Args[ConvIdx],
6700 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6701 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006702 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006703 return;
6704 }
6705
6706 // Fill in the rest of the conversions.
6707 unsigned NumArgsInProto = Proto->getNumArgs();
6708 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6709 if (ArgIdx < NumArgsInProto)
6710 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006711 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6712 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006713 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006714 else
6715 Cand->Conversions[ConvIdx].setEllipsis();
6716 }
6717}
6718
John McCalld3224162010-01-08 00:58:21 +00006719} // end anonymous namespace
6720
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006721/// PrintOverloadCandidates - When overload resolution fails, prints
6722/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006723/// set.
John McCall5c32be02010-08-24 20:38:10 +00006724void OverloadCandidateSet::NoteCandidates(Sema &S,
6725 OverloadCandidateDisplayKind OCD,
6726 Expr **Args, unsigned NumArgs,
6727 const char *Opc,
6728 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006729 // Sort the candidates by viability and position. Sorting directly would
6730 // be prohibitive, so we make a set of pointers and sort those.
6731 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00006732 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6733 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00006734 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006735 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006736 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00006737 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006738 if (Cand->Function || Cand->IsSurrogate)
6739 Cands.push_back(Cand);
6740 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6741 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006742 }
6743 }
6744
John McCallad2587a2010-01-12 00:48:53 +00006745 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00006746 CompareOverloadCandidatesForDisplay(S));
John McCall12f97bc2010-01-08 04:41:39 +00006747
John McCall0d1da222010-01-12 00:44:57 +00006748 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006749
John McCall12f97bc2010-01-08 04:41:39 +00006750 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00006751 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006752 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006753 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6754 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006755
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006756 // Set an arbitrary limit on the number of candidate functions we'll spam
6757 // the user with. FIXME: This limit should depend on details of the
6758 // candidate list.
6759 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6760 break;
6761 }
6762 ++CandsShown;
6763
John McCalld3224162010-01-08 00:58:21 +00006764 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00006765 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006766 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00006767 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006768 else {
6769 assert(Cand->Viable &&
6770 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006771 // Generally we only see ambiguities including viable builtin
6772 // operators if overload resolution got screwed up by an
6773 // ambiguous user-defined conversion.
6774 //
6775 // FIXME: It's quite possible for different conversions to see
6776 // different ambiguities, though.
6777 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00006778 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00006779 ReportedAmbiguousConversions = true;
6780 }
John McCalld3224162010-01-08 00:58:21 +00006781
John McCall0d1da222010-01-12 00:44:57 +00006782 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00006783 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006784 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006785 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006786
6787 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00006788 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006789}
6790
John McCalla0296f72010-03-19 07:35:19 +00006791static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006792 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006793 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006794
John McCalla0296f72010-03-19 07:35:19 +00006795 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006796}
6797
Douglas Gregorcd695e52008-11-10 20:40:00 +00006798/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6799/// an overloaded function (C++ [over.over]), where @p From is an
6800/// expression with overloaded function type and @p ToType is the type
6801/// we're trying to resolve to. For example:
6802///
6803/// @code
6804/// int f(double);
6805/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006806///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006807/// int (*pfd)(double) = f; // selects f(double)
6808/// @endcode
6809///
6810/// This routine returns the resulting FunctionDecl if it could be
6811/// resolved, and NULL otherwise. When @p Complain is true, this
6812/// routine will emit diagnostics if there is an error.
6813FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006814Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006815 bool Complain,
6816 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006817 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006818 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006819 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006820 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006821 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006822 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006823 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006824 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006825 FunctionType = MemTypePtr->getPointeeType();
6826 IsMember = true;
6827 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006828
Douglas Gregorcd695e52008-11-10 20:40:00 +00006829 // C++ [over.over]p1:
6830 // [...] [Note: any redundant set of parentheses surrounding the
6831 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006832 // C++ [over.over]p1:
6833 // [...] The overloaded function name can be preceded by the &
6834 // operator.
John McCall7d460512010-08-24 23:26:21 +00006835 // However, remember whether the expression has member-pointer form:
6836 // C++ [expr.unary.op]p4:
6837 // A pointer to member is only formed when an explicit & is used
6838 // and its operand is a qualified-id not enclosed in
6839 // parentheses.
John McCall8d08b9b2010-08-27 09:08:28 +00006840 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6841 OverloadExpr *OvlExpr = Ovl.Expression;
John McCall7d460512010-08-24 23:26:21 +00006842
Douglas Gregor064fdb22010-04-14 23:11:21 +00006843 // We expect a pointer or reference to function, or a function pointer.
6844 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6845 if (!FunctionType->isFunctionType()) {
6846 if (Complain)
6847 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6848 << OvlExpr->getName() << ToType;
6849
6850 return 0;
6851 }
6852
John McCall24d18942010-08-24 22:52:39 +00006853 // If the overload expression doesn't have the form of a pointer to
John McCall7d460512010-08-24 23:26:21 +00006854 // member, don't try to convert it to a pointer-to-member type.
John McCall8d08b9b2010-08-27 09:08:28 +00006855 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCall24d18942010-08-24 22:52:39 +00006856 if (!Complain) return 0;
6857
6858 // TODO: Should we condition this on whether any functions might
6859 // have matched, or is it more appropriate to do that in callers?
6860 // TODO: a fixit wouldn't hurt.
6861 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6862 << ToType << OvlExpr->getSourceRange();
6863 return 0;
6864 }
6865
6866 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6867 if (OvlExpr->hasExplicitTemplateArgs()) {
6868 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6869 ExplicitTemplateArgs = &ETABuffer;
6870 }
6871
Douglas Gregor064fdb22010-04-14 23:11:21 +00006872 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006873
Douglas Gregorcd695e52008-11-10 20:40:00 +00006874 // Look through all of the overloaded functions, searching for one
6875 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006876 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006877 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006878
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006879 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006880 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6881 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006882 // Look through any using declarations to find the underlying function.
6883 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6884
Douglas Gregorcd695e52008-11-10 20:40:00 +00006885 // C++ [over.over]p3:
6886 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006887 // targets of type "pointer-to-function" or "reference-to-function."
6888 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006889 // type "pointer-to-member-function."
6890 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006891
Mike Stump11289f42009-09-09 15:08:12 +00006892 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006893 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006894 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006895 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006896 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006897 // static when converting to member pointer.
6898 if (Method->isStatic() == IsMember)
6899 continue;
6900 } else if (IsMember)
6901 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006902
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006903 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006904 // If the name is a function template, template argument deduction is
6905 // done (14.8.2.2), and if the argument deduction succeeds, the
6906 // resulting template argument list is used to generate a single
6907 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006908 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00006909 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006910 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006911 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006912 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006913 FunctionType, Specialization, Info)) {
6914 // FIXME: make a note of the failed deduction for diagnostics.
6915 (void)Result;
6916 } else {
Douglas Gregor4ed49f32010-09-29 21:14:36 +00006917 // Template argument deduction ensures that we have an exact match.
6918 // This function template specicalization works.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006919 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006920 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006921 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006922 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor9b146582009-07-08 20:55:45 +00006923 }
John McCalld14a8642009-11-21 08:51:07 +00006924
6925 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006926 }
Mike Stump11289f42009-09-09 15:08:12 +00006927
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006928 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006929 // Skip non-static functions when converting to pointer, and static
6930 // when converting to member pointer.
6931 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006932 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006933
6934 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006935 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006936 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006937 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006938 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006939
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006940 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006941 QualType ResultTy;
6942 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6943 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6944 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006945 Matches.push_back(std::make_pair(I.getPair(),
6946 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006947 FoundNonTemplateFunction = true;
6948 }
Mike Stump11289f42009-09-09 15:08:12 +00006949 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006950 }
6951
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006952 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006953 if (Matches.empty()) {
6954 if (Complain) {
6955 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6956 << OvlExpr->getName() << FunctionType;
6957 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6958 E = OvlExpr->decls_end();
6959 I != E; ++I)
6960 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6961 NoteOverloadCandidate(F);
6962 }
6963
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006964 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006965 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006966 FunctionDecl *Result = Matches[0].second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006967 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006968 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006969 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006970 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006971 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006972 return Result;
6973 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006974
6975 // C++ [over.over]p4:
6976 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006977 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006978 // [...] and any given function template specialization F1 is
6979 // eliminated if the set contains a second function template
6980 // specialization whose function template is more specialized
6981 // than the function template of F1 according to the partial
6982 // ordering rules of 14.5.5.2.
6983
6984 // The algorithm specified above is quadratic. We instead use a
6985 // two-pass algorithm (similar to the one used to identify the
6986 // best viable function in an overload set) that identifies the
6987 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006988
6989 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6990 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6991 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006992
6993 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006994 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00006995 TPOC_Other, 0, From->getLocStart(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006996 PDiag(),
6997 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006998 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006999 PDiag(diag::note_ovl_candidate)
7000 << (unsigned) oc_function_template);
Douglas Gregorbdd7b232010-09-12 08:16:09 +00007001 if (Result == MatchesCopy.end())
7002 return 0;
7003
John McCall58cc69d2010-01-27 01:50:18 +00007004 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00007005 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007006 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00007007 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00007008 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007009 }
Mike Stump11289f42009-09-09 15:08:12 +00007010
Douglas Gregorfae1d712009-09-26 03:56:17 +00007011 // [...] any function template specializations in the set are
7012 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00007013 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00007014 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00007015 ++I;
7016 else {
John McCalla0296f72010-03-19 07:35:19 +00007017 Matches[I] = Matches[--N];
7018 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00007019 }
7020 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00007021
Mike Stump11289f42009-09-09 15:08:12 +00007022 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007023 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00007024 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00007025 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00007026 FoundResult = Matches[0].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007027 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00007028 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
7029 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007030 }
Mike Stump11289f42009-09-09 15:08:12 +00007031
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007032 // FIXME: We should probably return the same thing that BestViableFunction
7033 // returns (even if we issue the diagnostics here).
Douglas Gregore81f58e2010-11-08 03:40:48 +00007034 if (Complain) {
7035 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
7036 << Matches[0].second->getDeclName();
7037 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7038 NoteOverloadCandidate(Matches[I].second);
7039 }
7040
Douglas Gregorcd695e52008-11-10 20:40:00 +00007041 return 0;
7042}
7043
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007044/// \brief Given an expression that refers to an overloaded function, try to
7045/// resolve that overloaded function expression down to a single function.
7046///
7047/// This routine can only resolve template-ids that refer to a single function
7048/// template, where that template-id refers to a single template whose template
7049/// arguments are either provided by the template-id or have defaults,
7050/// as described in C++0x [temp.arg.explicit]p3.
7051FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
7052 // C++ [over.over]p1:
7053 // [...] [Note: any redundant set of parentheses surrounding the
7054 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007055 // C++ [over.over]p1:
7056 // [...] The overloaded function name can be preceded by the &
7057 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00007058
7059 if (From->getType() != Context.OverloadTy)
7060 return 0;
7061
John McCall8d08b9b2010-08-27 09:08:28 +00007062 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007063
7064 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00007065 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007066 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007067
7068 TemplateArgumentListInfo ExplicitTemplateArgs;
7069 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007070
7071 // Look through all of the overloaded functions, searching for one
7072 // whose type matches exactly.
7073 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00007074 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7075 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007076 // C++0x [temp.arg.explicit]p3:
7077 // [...] In contexts where deduction is done and fails, or in contexts
7078 // where deduction is not done, if a template argument list is
7079 // specified and it, along with any default template arguments,
7080 // identifies a single function template specialization, then the
7081 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00007082 FunctionTemplateDecl *FunctionTemplate
7083 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007084
7085 // C++ [over.over]p2:
7086 // If the name is a function template, template argument deduction is
7087 // done (14.8.2.2), and if the argument deduction succeeds, the
7088 // resulting template argument list is used to generate a single
7089 // function template specialization, which is added to the set of
7090 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007091 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00007092 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007093 if (TemplateDeductionResult Result
7094 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7095 Specialization, Info)) {
7096 // FIXME: make a note of the failed deduction for diagnostics.
7097 (void)Result;
7098 continue;
7099 }
7100
7101 // Multiple matches; we can't resolve to a single declaration.
7102 if (Matched)
7103 return 0;
7104
7105 Matched = Specialization;
7106 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007107
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007108 return Matched;
7109}
7110
Douglas Gregorcabea402009-09-22 15:41:20 +00007111/// \brief Add a single candidate to the overload set.
7112static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00007113 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00007114 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007115 Expr **Args, unsigned NumArgs,
7116 OverloadCandidateSet &CandidateSet,
7117 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00007118 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00007119 if (isa<UsingShadowDecl>(Callee))
7120 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7121
Douglas Gregorcabea402009-09-22 15:41:20 +00007122 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00007123 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00007124 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007125 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007126 return;
John McCalld14a8642009-11-21 08:51:07 +00007127 }
7128
7129 if (FunctionTemplateDecl *FuncTemplate
7130 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00007131 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7132 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007133 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00007134 return;
7135 }
7136
7137 assert(false && "unhandled case in overloaded call candidate");
7138
7139 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00007140}
7141
7142/// \brief Add the overload candidates named by callee and/or found by argument
7143/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00007144void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00007145 Expr **Args, unsigned NumArgs,
7146 OverloadCandidateSet &CandidateSet,
7147 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00007148
7149#ifndef NDEBUG
7150 // Verify that ArgumentDependentLookup is consistent with the rules
7151 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00007152 //
Douglas Gregorcabea402009-09-22 15:41:20 +00007153 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7154 // and let Y be the lookup set produced by argument dependent
7155 // lookup (defined as follows). If X contains
7156 //
7157 // -- a declaration of a class member, or
7158 //
7159 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00007160 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00007161 //
7162 // -- a declaration that is neither a function or a function
7163 // template
7164 //
7165 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00007166
John McCall57500772009-12-16 12:17:52 +00007167 if (ULE->requiresADL()) {
7168 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7169 E = ULE->decls_end(); I != E; ++I) {
7170 assert(!(*I)->getDeclContext()->isRecord());
7171 assert(isa<UsingShadowDecl>(*I) ||
7172 !(*I)->getDeclContext()->isFunctionOrMethod());
7173 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00007174 }
7175 }
7176#endif
7177
John McCall57500772009-12-16 12:17:52 +00007178 // It would be nice to avoid this copy.
7179 TemplateArgumentListInfo TABuffer;
7180 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7181 if (ULE->hasExplicitTemplateArgs()) {
7182 ULE->copyTemplateArgumentsInto(TABuffer);
7183 ExplicitTemplateArgs = &TABuffer;
7184 }
7185
7186 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7187 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00007188 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007189 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00007190 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00007191
John McCall57500772009-12-16 12:17:52 +00007192 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00007193 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7194 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007195 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007196 CandidateSet,
7197 PartialOverloading);
7198}
John McCalld681c392009-12-16 08:11:27 +00007199
7200/// Attempts to recover from a call where no functions were found.
7201///
7202/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00007203static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007204BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00007205 UnresolvedLookupExpr *ULE,
7206 SourceLocation LParenLoc,
7207 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007208 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00007209
7210 CXXScopeSpec SS;
7211 if (ULE->getQualifier()) {
7212 SS.setScopeRep(ULE->getQualifier());
7213 SS.setRange(ULE->getQualifierRange());
7214 }
7215
John McCall57500772009-12-16 12:17:52 +00007216 TemplateArgumentListInfo TABuffer;
7217 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7218 if (ULE->hasExplicitTemplateArgs()) {
7219 ULE->copyTemplateArgumentsInto(TABuffer);
7220 ExplicitTemplateArgs = &TABuffer;
7221 }
7222
John McCalld681c392009-12-16 08:11:27 +00007223 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7224 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00007225 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00007226 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00007227
John McCall57500772009-12-16 12:17:52 +00007228 assert(!R.empty() && "lookup results empty despite recovery");
7229
7230 // Build an implicit member call if appropriate. Just drop the
7231 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00007232 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00007233 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00007234 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7235 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00007236 else if (ExplicitTemplateArgs)
7237 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7238 else
7239 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7240
7241 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007242 return ExprError();
John McCall57500772009-12-16 12:17:52 +00007243
7244 // This shouldn't cause an infinite loop because we're giving it
7245 // an expression with non-empty lookup results, which should never
7246 // end up here.
John McCallb268a282010-08-23 23:25:46 +00007247 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007248 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007249}
Douglas Gregor4038cf42010-06-08 17:35:15 +00007250
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007251/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00007252/// (which eventually refers to the declaration Func) and the call
7253/// arguments Args/NumArgs, attempt to resolve the function call down
7254/// to a specific function. If overload resolution succeeds, returns
7255/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00007256/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007257/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00007258ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007259Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00007260 SourceLocation LParenLoc,
7261 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007262 SourceLocation RParenLoc) {
7263#ifndef NDEBUG
7264 if (ULE->requiresADL()) {
7265 // To do ADL, we must have found an unqualified name.
7266 assert(!ULE->getQualifier() && "qualified name with ADL");
7267
7268 // We don't perform ADL for implicit declarations of builtins.
7269 // Verify that this was correctly set up.
7270 FunctionDecl *F;
7271 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7272 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7273 F->getBuiltinID() && F->isImplicit())
7274 assert(0 && "performing ADL for builtin");
7275
7276 // We don't perform ADL in C.
7277 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7278 }
7279#endif
7280
John McCallbc077cf2010-02-08 23:07:23 +00007281 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007282
John McCall57500772009-12-16 12:17:52 +00007283 // Add the functions denoted by the callee to the set of candidate
7284 // functions, including those from argument-dependent lookup.
7285 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007286
7287 // If we found nothing, try to recover.
7288 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7289 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007290 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007291 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007292 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007293
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007294 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007295 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007296 case OR_Success: {
7297 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00007298 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007299 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7300 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007301 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007302 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
7303 RParenLoc);
John McCall57500772009-12-16 12:17:52 +00007304 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007305
7306 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007307 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007308 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007309 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007310 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007311 break;
7312
7313 case OR_Ambiguous:
7314 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007315 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007316 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007317 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007318
7319 case OR_Deleted:
7320 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7321 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00007322 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00007323 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007324 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007325 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007326 }
7327
Douglas Gregorb412e172010-07-25 18:17:45 +00007328 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007329 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007330}
7331
John McCall4c4c1df2010-01-26 03:27:55 +00007332static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007333 return Functions.size() > 1 ||
7334 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7335}
7336
Douglas Gregor084d8552009-03-13 23:49:33 +00007337/// \brief Create a unary operation that may resolve to an overloaded
7338/// operator.
7339///
7340/// \param OpLoc The location of the operator itself (e.g., '*').
7341///
7342/// \param OpcIn The UnaryOperator::Opcode that describes this
7343/// operator.
7344///
7345/// \param Functions The set of non-member functions that will be
7346/// considered by overload resolution. The caller needs to build this
7347/// set based on the context using, e.g.,
7348/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7349/// set should not contain any member functions; those will be added
7350/// by CreateOverloadedUnaryOp().
7351///
7352/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007353ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007354Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7355 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007356 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007357 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007358
7359 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7360 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7361 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007362 // TODO: provide better source location info.
7363 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007364
John McCalle26a8722010-12-04 08:14:53 +00007365 if (Input->getObjectKind() == OK_ObjCProperty)
7366 ConvertPropertyForRValue(Input);
7367
Douglas Gregor084d8552009-03-13 23:49:33 +00007368 Expr *Args[2] = { Input, 0 };
7369 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007370
Douglas Gregor084d8552009-03-13 23:49:33 +00007371 // For post-increment and post-decrement, add the implicit '0' as
7372 // the second argument, so that we know this is a post-increment or
7373 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007374 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007375 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007376 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7377 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007378 NumArgs = 2;
7379 }
7380
7381 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007382 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007383 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00007384 Opc,
7385 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007386 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00007387 OpLoc));
7388
John McCall58cc69d2010-01-27 01:50:18 +00007389 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007390 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007391 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007392 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007393 /*ADL*/ true, IsOverloaded(Fns),
7394 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007395 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7396 &Args[0], NumArgs,
7397 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007398 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00007399 OpLoc));
7400 }
7401
7402 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007403 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007404
7405 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007406 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007407
7408 // Add operator candidates that are member functions.
7409 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7410
John McCall4c4c1df2010-01-26 03:27:55 +00007411 // Add candidates from ADL.
7412 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007413 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007414 /*ExplicitTemplateArgs*/ 0,
7415 CandidateSet);
7416
Douglas Gregor084d8552009-03-13 23:49:33 +00007417 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007418 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007419
7420 // Perform overload resolution.
7421 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007422 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007423 case OR_Success: {
7424 // We found a built-in operator or an overloaded operator.
7425 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007426
Douglas Gregor084d8552009-03-13 23:49:33 +00007427 if (FnDecl) {
7428 // We matched an overloaded operator. Build a call to that
7429 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007430
Douglas Gregor084d8552009-03-13 23:49:33 +00007431 // Convert the arguments.
7432 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007433 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007434
John McCall16df1e52010-03-30 21:47:33 +00007435 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7436 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007437 return ExprError();
7438 } else {
7439 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007440 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007441 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007442 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007443 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00007444 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007445 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007446 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007447 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007448 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007449 }
7450
John McCall4fa0d5f2010-05-06 18:15:07 +00007451 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7452
John McCall7decc9e2010-11-18 06:31:45 +00007453 // Determine the result type.
7454 QualType ResultTy = FnDecl->getResultType();
7455 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7456 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00007457
Douglas Gregor084d8552009-03-13 23:49:33 +00007458 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007459 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007460
Eli Friedman030eee42009-11-18 03:58:17 +00007461 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007462 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007463 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007464 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007465
John McCallb268a282010-08-23 23:25:46 +00007466 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007467 FnDecl))
7468 return ExprError();
7469
John McCallb268a282010-08-23 23:25:46 +00007470 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007471 } else {
7472 // We matched a built-in operator. Convert the arguments, then
7473 // break out so that we will build the appropriate built-in
7474 // operator node.
7475 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007476 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007477 return ExprError();
7478
7479 break;
7480 }
7481 }
7482
7483 case OR_No_Viable_Function:
7484 // No viable function; fall through to handling this as a
7485 // built-in operator, which will produce an error message for us.
7486 break;
7487
7488 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007489 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregor084d8552009-03-13 23:49:33 +00007490 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007491 << Input->getType()
Douglas Gregor084d8552009-03-13 23:49:33 +00007492 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007493 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7494 Args, NumArgs,
7495 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007496 return ExprError();
7497
7498 case OR_Deleted:
7499 Diag(OpLoc, diag::err_ovl_deleted_oper)
7500 << Best->Function->isDeleted()
7501 << UnaryOperator::getOpcodeStr(Opc)
7502 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007503 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007504 return ExprError();
7505 }
7506
7507 // Either we found no viable overloaded operator or we matched a
7508 // built-in operator. In either case, fall through to trying to
7509 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007510 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007511}
7512
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007513/// \brief Create a binary operation that may resolve to an overloaded
7514/// operator.
7515///
7516/// \param OpLoc The location of the operator itself (e.g., '+').
7517///
7518/// \param OpcIn The BinaryOperator::Opcode that describes this
7519/// operator.
7520///
7521/// \param Functions The set of non-member functions that will be
7522/// considered by overload resolution. The caller needs to build this
7523/// set based on the context using, e.g.,
7524/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7525/// set should not contain any member functions; those will be added
7526/// by CreateOverloadedBinOp().
7527///
7528/// \param LHS Left-hand argument.
7529/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00007530ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007531Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007532 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00007533 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007534 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007535 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00007536 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007537
7538 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7539 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7540 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7541
7542 // If either side is type-dependent, create an appropriate dependent
7543 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00007544 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00007545 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00007546 // If there are no functions to store, just build a dependent
7547 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00007548 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00007549 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00007550 Context.DependentTy,
7551 VK_RValue, OK_Ordinary,
7552 OpLoc));
Douglas Gregor5287f092009-11-05 00:51:44 +00007553
7554 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7555 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007556 VK_LValue,
7557 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00007558 Context.DependentTy,
7559 Context.DependentTy,
7560 OpLoc));
7561 }
John McCall4c4c1df2010-01-26 03:27:55 +00007562
7563 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00007564 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007565 // TODO: provide better source location info in DNLoc component.
7566 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00007567 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007568 = UnresolvedLookupExpr::Create(Context, NamingClass, 0, SourceRange(),
7569 OpNameInfo, /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007570 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007571 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00007572 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007573 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007574 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007575 OpLoc));
7576 }
7577
John McCalle26a8722010-12-04 08:14:53 +00007578 // Always do property rvalue conversions on the RHS.
7579 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7580 ConvertPropertyForRValue(Args[1]);
7581
7582 // The LHS is more complicated.
7583 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
7584
7585 // There's a tension for assignment operators between primitive
7586 // property assignment and the overloaded operators.
7587 if (BinaryOperator::isAssignmentOp(Opc)) {
7588 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7589
7590 // Is the property "logically" settable?
7591 bool Settable = (PRE->isExplicitProperty() ||
7592 PRE->getImplicitPropertySetter());
7593
7594 // To avoid gratuitously inventing semantics, use the primitive
7595 // unless it isn't. Thoughts in case we ever really care:
7596 // - If the property isn't logically settable, we have to
7597 // load and hope.
7598 // - If the property is settable and this is simple assignment,
7599 // we really should use the primitive.
7600 // - If the property is settable, then we could try overloading
7601 // on a generic lvalue of the appropriate type; if it works
7602 // out to a builtin candidate, we would do that same operation
7603 // on the property, and otherwise just error.
7604 if (Settable)
7605 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7606 }
7607
7608 ConvertPropertyForRValue(Args[0]);
7609 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007610
Sebastian Redl6a96bf72009-11-18 23:10:33 +00007611 // If this is the assignment operator, we only perform overload resolution
7612 // if the left-hand side is a class or enumeration type. This is actually
7613 // a hack. The standard requires that we do overload resolution between the
7614 // various built-in candidates, but as DR507 points out, this can lead to
7615 // problems. So we do it this way, which pretty much follows what GCC does.
7616 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00007617 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00007618 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007619
John McCalle26a8722010-12-04 08:14:53 +00007620 // If this is the .* operator, which is not overloadable, just
7621 // create a built-in binary operator.
7622 if (Opc == BO_PtrMemD)
7623 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7624
Douglas Gregor084d8552009-03-13 23:49:33 +00007625 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007626 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007627
7628 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007629 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007630
7631 // Add operator candidates that are member functions.
7632 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7633
John McCall4c4c1df2010-01-26 03:27:55 +00007634 // Add candidates from ADL.
7635 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7636 Args, 2,
7637 /*ExplicitTemplateArgs*/ 0,
7638 CandidateSet);
7639
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007640 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007641 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007642
7643 // Perform overload resolution.
7644 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007645 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00007646 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007647 // We found a built-in operator or an overloaded operator.
7648 FunctionDecl *FnDecl = Best->Function;
7649
7650 if (FnDecl) {
7651 // We matched an overloaded operator. Build a call to that
7652 // operator.
7653
7654 // Convert the arguments.
7655 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00007656 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00007657 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007658
Chandler Carruth8e543b32010-12-12 08:17:55 +00007659 ExprResult Arg1 =
7660 PerformCopyInitialization(
7661 InitializedEntity::InitializeParameter(Context,
7662 FnDecl->getParamDecl(0)),
7663 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007664 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007665 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007666
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007667 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007668 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007669 return ExprError();
7670
7671 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007672 } else {
7673 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00007674 ExprResult Arg0 = PerformCopyInitialization(
7675 InitializedEntity::InitializeParameter(Context,
7676 FnDecl->getParamDecl(0)),
7677 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007678 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007679 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007680
Chandler Carruth8e543b32010-12-12 08:17:55 +00007681 ExprResult Arg1 =
7682 PerformCopyInitialization(
7683 InitializedEntity::InitializeParameter(Context,
7684 FnDecl->getParamDecl(1)),
7685 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007686 if (Arg1.isInvalid())
7687 return ExprError();
7688 Args[0] = LHS = Arg0.takeAs<Expr>();
7689 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007690 }
7691
John McCall4fa0d5f2010-05-06 18:15:07 +00007692 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7693
John McCall7decc9e2010-11-18 06:31:45 +00007694 // Determine the result type.
7695 QualType ResultTy = FnDecl->getResultType();
7696 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7697 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007698
7699 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007700 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007701
John McCallb268a282010-08-23 23:25:46 +00007702 CXXOperatorCallExpr *TheCall =
7703 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007704 Args, 2, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007705
John McCallb268a282010-08-23 23:25:46 +00007706 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007707 FnDecl))
7708 return ExprError();
7709
John McCallb268a282010-08-23 23:25:46 +00007710 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007711 } else {
7712 // We matched a built-in operator. Convert the arguments, then
7713 // break out so that we will build the appropriate built-in
7714 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00007715 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007716 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00007717 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007718 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007719 return ExprError();
7720
7721 break;
7722 }
7723 }
7724
Douglas Gregor66950a32009-09-30 21:46:01 +00007725 case OR_No_Viable_Function: {
7726 // C++ [over.match.oper]p9:
7727 // If the operator is the operator , [...] and there are no
7728 // viable functions, then the operator is assumed to be the
7729 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00007730 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00007731 break;
7732
Chandler Carruth8e543b32010-12-12 08:17:55 +00007733 // For class as left operand for assignment or compound assigment
7734 // operator do not fall through to handling in built-in, but report that
7735 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007736 ExprResult Result = ExprError();
Douglas Gregor66950a32009-09-30 21:46:01 +00007737 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00007738 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007739 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7740 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007741 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007742 } else {
7743 // No viable function; try to create a built-in operation, which will
7744 // produce an error. Then, show the non-viable candidates.
7745 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007746 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007747 assert(Result.isInvalid() &&
7748 "C++ binary operator overloading is missing candidates!");
7749 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00007750 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7751 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007752 return move(Result);
7753 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007754
7755 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007756 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007757 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007758 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00007759 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007760 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7761 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007762 return ExprError();
7763
7764 case OR_Deleted:
7765 Diag(OpLoc, diag::err_ovl_deleted_oper)
7766 << Best->Function->isDeleted()
7767 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007768 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007769 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007770 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007771 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007772
Douglas Gregor66950a32009-09-30 21:46:01 +00007773 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007774 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007775}
7776
John McCalldadc5752010-08-24 06:29:42 +00007777ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007778Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7779 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007780 Expr *Base, Expr *Idx) {
7781 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007782 DeclarationName OpName =
7783 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7784
7785 // If either side is type-dependent, create an appropriate dependent
7786 // expression.
7787 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7788
John McCall58cc69d2010-01-27 01:50:18 +00007789 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007790 // CHECKME: no 'operator' keyword?
7791 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7792 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007793 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007794 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007795 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007796 /*ADL*/ true, /*Overloaded*/ false,
7797 UnresolvedSetIterator(),
7798 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007799 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007800
Sebastian Redladba46e2009-10-29 20:17:01 +00007801 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7802 Args, 2,
7803 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007804 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00007805 RLoc));
7806 }
7807
John McCalle26a8722010-12-04 08:14:53 +00007808 if (Args[0]->getObjectKind() == OK_ObjCProperty)
7809 ConvertPropertyForRValue(Args[0]);
7810 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7811 ConvertPropertyForRValue(Args[1]);
7812
Sebastian Redladba46e2009-10-29 20:17:01 +00007813 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007814 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007815
7816 // Subscript can only be overloaded as a member function.
7817
7818 // Add operator candidates that are member functions.
7819 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7820
7821 // Add builtin operator candidates.
7822 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7823
7824 // Perform overload resolution.
7825 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007826 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00007827 case OR_Success: {
7828 // We found a built-in operator or an overloaded operator.
7829 FunctionDecl *FnDecl = Best->Function;
7830
7831 if (FnDecl) {
7832 // We matched an overloaded operator. Build a call to that
7833 // operator.
7834
John McCalla0296f72010-03-19 07:35:19 +00007835 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007836 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007837
Sebastian Redladba46e2009-10-29 20:17:01 +00007838 // Convert the arguments.
7839 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007840 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007841 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007842 return ExprError();
7843
Anders Carlssona68e51e2010-01-29 18:37:50 +00007844 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007845 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007846 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007847 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00007848 FnDecl->getParamDecl(0)),
7849 SourceLocation(),
7850 Owned(Args[1]));
7851 if (InputInit.isInvalid())
7852 return ExprError();
7853
7854 Args[1] = InputInit.takeAs<Expr>();
7855
Sebastian Redladba46e2009-10-29 20:17:01 +00007856 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00007857 QualType ResultTy = FnDecl->getResultType();
7858 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7859 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007860
7861 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007862 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007863
John McCallb268a282010-08-23 23:25:46 +00007864 CXXOperatorCallExpr *TheCall =
7865 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7866 FnExpr, Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00007867 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007868
John McCallb268a282010-08-23 23:25:46 +00007869 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007870 FnDecl))
7871 return ExprError();
7872
John McCallb268a282010-08-23 23:25:46 +00007873 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007874 } else {
7875 // We matched a built-in operator. Convert the arguments, then
7876 // break out so that we will build the appropriate built-in
7877 // operator node.
7878 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007879 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007880 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007881 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007882 return ExprError();
7883
7884 break;
7885 }
7886 }
7887
7888 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007889 if (CandidateSet.empty())
7890 Diag(LLoc, diag::err_ovl_no_oper)
7891 << Args[0]->getType() << /*subscript*/ 0
7892 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7893 else
7894 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7895 << Args[0]->getType()
7896 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007897 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7898 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00007899 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007900 }
7901
7902 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007903 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
7904 << "[]"
7905 << Args[0]->getType() << Args[1]->getType()
7906 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007907 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7908 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007909 return ExprError();
7910
7911 case OR_Deleted:
7912 Diag(LLoc, diag::err_ovl_deleted_oper)
7913 << Best->Function->isDeleted() << "[]"
7914 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007915 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7916 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007917 return ExprError();
7918 }
7919
7920 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00007921 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007922}
7923
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007924/// BuildCallToMemberFunction - Build a call to a member
7925/// function. MemExpr is the expression that refers to the member
7926/// function (and includes the object parameter), Args/NumArgs are the
7927/// arguments to the function call (not including the object
7928/// parameter). The caller needs to validate that the member
7929/// expression refers to a member function or an overloaded member
7930/// function.
John McCalldadc5752010-08-24 06:29:42 +00007931ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007932Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7933 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007934 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007935 // Dig out the member expression. This holds both the object
7936 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007937 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7938
John McCall10eae182009-11-30 22:42:35 +00007939 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007940 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007941 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007942 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007943 if (isa<MemberExpr>(NakedMemExpr)) {
7944 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007945 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007946 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007947 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007948 } else {
7949 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007950 Qualifier = UnresExpr->getQualifier();
7951
John McCall6e9f8f62009-12-03 04:06:58 +00007952 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007953
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007954 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007955 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007956
John McCall2d74de92009-12-01 22:10:20 +00007957 // FIXME: avoid copy.
7958 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7959 if (UnresExpr->hasExplicitTemplateArgs()) {
7960 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7961 TemplateArgs = &TemplateArgsBuffer;
7962 }
7963
John McCall10eae182009-11-30 22:42:35 +00007964 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7965 E = UnresExpr->decls_end(); I != E; ++I) {
7966
John McCall6e9f8f62009-12-03 04:06:58 +00007967 NamedDecl *Func = *I;
7968 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7969 if (isa<UsingShadowDecl>(Func))
7970 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7971
Francois Pichet64225792011-01-18 05:04:39 +00007972 // Microsoft supports direct constructor calls.
7973 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
7974 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
7975 CandidateSet);
7976 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007977 // If explicit template arguments were provided, we can't call a
7978 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007979 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007980 continue;
7981
John McCalla0296f72010-03-19 07:35:19 +00007982 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007983 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007984 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007985 } else {
John McCall10eae182009-11-30 22:42:35 +00007986 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007987 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007988 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007989 CandidateSet,
7990 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007991 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007992 }
Mike Stump11289f42009-09-09 15:08:12 +00007993
John McCall10eae182009-11-30 22:42:35 +00007994 DeclarationName DeclName = UnresExpr->getMemberName();
7995
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007996 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007997 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00007998 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007999 case OR_Success:
8000 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008001 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00008002 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008003 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008004 break;
8005
8006 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00008007 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008008 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008009 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008010 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008011 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008012 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008013
8014 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00008015 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008016 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008017 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008018 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008019 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008020
8021 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00008022 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00008023 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00008024 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008025 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008026 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008027 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008028 }
8029
John McCall16df1e52010-03-30 21:47:33 +00008030 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00008031
John McCall2d74de92009-12-01 22:10:20 +00008032 // If overload resolution picked a static member, build a
8033 // non-member call based on that function.
8034 if (Method->isStatic()) {
8035 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8036 Args, NumArgs, RParenLoc);
8037 }
8038
John McCall10eae182009-11-30 22:42:35 +00008039 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008040 }
8041
John McCall7decc9e2010-11-18 06:31:45 +00008042 QualType ResultType = Method->getResultType();
8043 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8044 ResultType = ResultType.getNonLValueExprType(Context);
8045
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008046 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00008047 CXXMemberCallExpr *TheCall =
8048 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008049 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008050
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008051 // Check for a valid return type.
8052 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00008053 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00008054 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008055
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008056 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00008057 // We only need to do this if there was actually an overload; otherwise
8058 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00008059 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00008060 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00008061 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
8062 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00008063 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008064 MemExpr->setBase(ObjectArg);
8065
8066 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00008067 const FunctionProtoType *Proto =
8068 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00008069 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008070 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00008071 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008072
John McCallb268a282010-08-23 23:25:46 +00008073 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00008074 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00008075
John McCallb268a282010-08-23 23:25:46 +00008076 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008077}
8078
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008079/// BuildCallToObjectOfClassType - Build a call to an object of class
8080/// type (C++ [over.call.object]), which can end up invoking an
8081/// overloaded function call operator (@c operator()) or performing a
8082/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00008083ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008084Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00008085 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008086 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008087 SourceLocation RParenLoc) {
John McCalle26a8722010-12-04 08:14:53 +00008088 if (Object->getObjectKind() == OK_ObjCProperty)
8089 ConvertPropertyForRValue(Object);
8090
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008091 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008092 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00008093
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008094 // C++ [over.call.object]p1:
8095 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00008096 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008097 // candidate functions includes at least the function call
8098 // operators of T. The function call operators of T are obtained by
8099 // ordinary lookup of the name operator() in the context of
8100 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00008101 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00008102 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008103
8104 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00008105 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008106 << Object->getSourceRange()))
8107 return true;
8108
John McCall27b18f82009-11-17 02:14:36 +00008109 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8110 LookupQualifiedName(R, Record->getDecl());
8111 R.suppressDiagnostics();
8112
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008113 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00008114 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008115 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00008116 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00008117 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00008118 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008119
Douglas Gregorab7897a2008-11-19 22:57:39 +00008120 // C++ [over.call.object]p2:
8121 // In addition, for each conversion function declared in T of the
8122 // form
8123 //
8124 // operator conversion-type-id () cv-qualifier;
8125 //
8126 // where cv-qualifier is the same cv-qualification as, or a
8127 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00008128 // denotes the type "pointer to function of (P1,...,Pn) returning
8129 // R", or the type "reference to pointer to function of
8130 // (P1,...,Pn) returning R", or the type "reference to function
8131 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00008132 // is also considered as a candidate function. Similarly,
8133 // surrogate call functions are added to the set of candidate
8134 // functions for each conversion function declared in an
8135 // accessible base class provided the function is not hidden
8136 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00008137 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00008138 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00008139 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00008140 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00008141 NamedDecl *D = *I;
8142 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8143 if (isa<UsingShadowDecl>(D))
8144 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8145
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008146 // Skip over templated conversion functions; they aren't
8147 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00008148 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008149 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00008150
John McCall6e9f8f62009-12-03 04:06:58 +00008151 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00008152
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008153 // Strip the reference type (if any) and then the pointer type (if
8154 // any) to get down to what might be a function type.
8155 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8156 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8157 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00008158
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008159 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00008160 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00008161 Object->getType(), Args, NumArgs,
8162 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008163 }
Mike Stump11289f42009-09-09 15:08:12 +00008164
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008165 // Perform overload resolution.
8166 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008167 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
8168 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008169 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00008170 // Overload resolution succeeded; we'll build the appropriate call
8171 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008172 break;
8173
8174 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00008175 if (CandidateSet.empty())
8176 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8177 << Object->getType() << /*call*/ 1
8178 << Object->getSourceRange();
8179 else
8180 Diag(Object->getSourceRange().getBegin(),
8181 diag::err_ovl_no_viable_object_call)
8182 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008183 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008184 break;
8185
8186 case OR_Ambiguous:
8187 Diag(Object->getSourceRange().getBegin(),
8188 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008189 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008190 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008191 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008192
8193 case OR_Deleted:
8194 Diag(Object->getSourceRange().getBegin(),
8195 diag::err_ovl_deleted_object_call)
8196 << Best->Function->isDeleted()
8197 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008198 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008199 break;
Mike Stump11289f42009-09-09 15:08:12 +00008200 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008201
Douglas Gregorb412e172010-07-25 18:17:45 +00008202 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008203 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008204
Douglas Gregorab7897a2008-11-19 22:57:39 +00008205 if (Best->Function == 0) {
8206 // Since there is no function declaration, this is one of the
8207 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00008208 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00008209 = cast<CXXConversionDecl>(
8210 Best->Conversions[0].UserDefined.ConversionFunction);
8211
John McCalla0296f72010-03-19 07:35:19 +00008212 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008213 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008214
Douglas Gregorab7897a2008-11-19 22:57:39 +00008215 // We selected one of the surrogate functions that converts the
8216 // object parameter to a function pointer. Perform the conversion
8217 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00008218
8219 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00008220 // and then call it.
Douglas Gregor668443e2011-01-20 00:18:04 +00008221 ExprResult Call = BuildCXXMemberCallExpr(Object, Best->FoundDecl, Conv);
8222 if (Call.isInvalid())
8223 return ExprError();
8224
8225 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008226 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008227 }
8228
John McCalla0296f72010-03-19 07:35:19 +00008229 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008230 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008231
Douglas Gregorab7897a2008-11-19 22:57:39 +00008232 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8233 // that calls this method, using Object for the implicit object
8234 // parameter and passing along the remaining arguments.
8235 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008236 const FunctionProtoType *Proto =
8237 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008238
8239 unsigned NumArgsInProto = Proto->getNumArgs();
8240 unsigned NumArgsToCheck = NumArgs;
8241
8242 // Build the full argument list for the method call (the
8243 // implicit object parameter is placed at the beginning of the
8244 // list).
8245 Expr **MethodArgs;
8246 if (NumArgs < NumArgsInProto) {
8247 NumArgsToCheck = NumArgsInProto;
8248 MethodArgs = new Expr*[NumArgsInProto + 1];
8249 } else {
8250 MethodArgs = new Expr*[NumArgs + 1];
8251 }
8252 MethodArgs[0] = Object;
8253 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8254 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00008255
John McCall7decc9e2010-11-18 06:31:45 +00008256 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008257
8258 // Once we've built TheCall, all of the expressions are properly
8259 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00008260 QualType ResultTy = Method->getResultType();
8261 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8262 ResultTy = ResultTy.getNonLValueExprType(Context);
8263
John McCallb268a282010-08-23 23:25:46 +00008264 CXXOperatorCallExpr *TheCall =
8265 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
8266 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00008267 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008268 delete [] MethodArgs;
8269
John McCallb268a282010-08-23 23:25:46 +00008270 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00008271 Method))
8272 return true;
8273
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008274 // We may have default arguments. If so, we need to allocate more
8275 // slots in the call for them.
8276 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00008277 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008278 else if (NumArgs > NumArgsInProto)
8279 NumArgsToCheck = NumArgsInProto;
8280
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008281 bool IsError = false;
8282
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008283 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008284 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008285 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008286 TheCall->setArg(0, Object);
8287
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008288
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008289 // Check the argument types.
8290 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008291 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008292 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008293 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00008294
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008295 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008296
John McCalldadc5752010-08-24 06:29:42 +00008297 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008298 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008299 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008300 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00008301 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008302
8303 IsError |= InputInit.isInvalid();
8304 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008305 } else {
John McCalldadc5752010-08-24 06:29:42 +00008306 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008307 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8308 if (DefArg.isInvalid()) {
8309 IsError = true;
8310 break;
8311 }
8312
8313 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008314 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008315
8316 TheCall->setArg(i + 1, Arg);
8317 }
8318
8319 // If this is a variadic call, handle args passed through "...".
8320 if (Proto->isVariadic()) {
8321 // Promote the arguments (C99 6.5.2.2p7).
8322 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8323 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00008324 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008325 TheCall->setArg(i + 1, Arg);
8326 }
8327 }
8328
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008329 if (IsError) return true;
8330
John McCallb268a282010-08-23 23:25:46 +00008331 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00008332 return true;
8333
John McCalle172be52010-08-24 06:09:16 +00008334 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008335}
8336
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008337/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00008338/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008339/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00008340ExprResult
John McCallb268a282010-08-23 23:25:46 +00008341Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008342 assert(Base->getType()->isRecordType() &&
8343 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00008344
John McCalle26a8722010-12-04 08:14:53 +00008345 if (Base->getObjectKind() == OK_ObjCProperty)
8346 ConvertPropertyForRValue(Base);
8347
John McCallbc077cf2010-02-08 23:07:23 +00008348 SourceLocation Loc = Base->getExprLoc();
8349
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008350 // C++ [over.ref]p1:
8351 //
8352 // [...] An expression x->m is interpreted as (x.operator->())->m
8353 // for a class object x of type T if T::operator->() exists and if
8354 // the operator is selected as the best match function by the
8355 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00008356 DeclarationName OpName =
8357 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00008358 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008359 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00008360
John McCallbc077cf2010-02-08 23:07:23 +00008361 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00008362 PDiag(diag::err_typecheck_incomplete_tag)
8363 << Base->getSourceRange()))
8364 return ExprError();
8365
John McCall27b18f82009-11-17 02:14:36 +00008366 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8367 LookupQualifiedName(R, BaseRecord->getDecl());
8368 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00008369
8370 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00008371 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008372 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008373 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00008374 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008375
8376 // Perform overload resolution.
8377 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008378 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008379 case OR_Success:
8380 // Overload resolution succeeded; we'll build the call below.
8381 break;
8382
8383 case OR_No_Viable_Function:
8384 if (CandidateSet.empty())
8385 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008386 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008387 else
8388 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008389 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008390 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008391 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008392
8393 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008394 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8395 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008396 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008397 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008398
8399 case OR_Deleted:
8400 Diag(OpLoc, diag::err_ovl_deleted_oper)
8401 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00008402 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008403 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008404 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008405 }
8406
John McCalla0296f72010-03-19 07:35:19 +00008407 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008408 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00008409
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008410 // Convert the object parameter.
8411 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008412 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8413 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00008414 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00008415
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008416 // Build the operator call.
John McCall7decc9e2010-11-18 06:31:45 +00008417 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008418
John McCall7decc9e2010-11-18 06:31:45 +00008419 QualType ResultTy = Method->getResultType();
8420 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8421 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00008422 CXXOperatorCallExpr *TheCall =
8423 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008424 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008425
John McCallb268a282010-08-23 23:25:46 +00008426 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008427 Method))
8428 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008429 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008430}
8431
Douglas Gregorcd695e52008-11-10 20:40:00 +00008432/// FixOverloadedFunctionReference - E is an expression that refers to
8433/// a C++ overloaded function (possibly with some parentheses and
8434/// perhaps a '&' around it). We have resolved the overloaded function
8435/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008436/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00008437Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00008438 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00008439 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008440 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8441 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008442 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008443 return PE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008444
8445 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8446 }
8447
8448 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008449 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8450 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00008451 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008452 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00008453 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00008454 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00008455 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008456 return ICE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008457
John McCallcf142162010-08-07 06:22:56 +00008458 return ImplicitCastExpr::Create(Context, ICE->getType(),
8459 ICE->getCastKind(),
8460 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00008461 ICE->getValueKind());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008462 }
8463
8464 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00008465 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008466 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008467 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8468 if (Method->isStatic()) {
8469 // Do nothing: static member functions aren't any different
8470 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008471 } else {
John McCalle66edc12009-11-24 19:00:30 +00008472 // Fix the sub expression, which really has to be an
8473 // UnresolvedLookupExpr holding an overloaded member function
8474 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008475 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8476 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008477 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008478 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008479
John McCalld14a8642009-11-21 08:51:07 +00008480 assert(isa<DeclRefExpr>(SubExpr)
8481 && "fixed to something other than a decl ref");
8482 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8483 && "fixed to a member ref with no nested name qualifier");
8484
8485 // We have taken the address of a pointer to member
8486 // function. Perform the computation here so that we get the
8487 // appropriate pointer to member type.
8488 QualType ClassType
8489 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8490 QualType MemPtrType
8491 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8492
John McCall7decc9e2010-11-18 06:31:45 +00008493 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8494 VK_RValue, OK_Ordinary,
8495 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008496 }
8497 }
John McCall16df1e52010-03-30 21:47:33 +00008498 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8499 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008500 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008501 return UnOp;
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008502
John McCalle3027922010-08-25 11:45:40 +00008503 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008504 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00008505 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008506 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008507 }
John McCalld14a8642009-11-21 08:51:07 +00008508
8509 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00008510 // FIXME: avoid copy.
8511 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00008512 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00008513 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8514 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00008515 }
8516
John McCalld14a8642009-11-21 08:51:07 +00008517 return DeclRefExpr::Create(Context,
8518 ULE->getQualifier(),
8519 ULE->getQualifierRange(),
8520 Fn,
8521 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00008522 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008523 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008524 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00008525 }
8526
John McCall10eae182009-11-30 22:42:35 +00008527 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00008528 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00008529 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8530 if (MemExpr->hasExplicitTemplateArgs()) {
8531 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8532 TemplateArgs = &TemplateArgsBuffer;
8533 }
John McCall6b51f282009-11-23 01:53:49 +00008534
John McCall2d74de92009-12-01 22:10:20 +00008535 Expr *Base;
8536
John McCall7decc9e2010-11-18 06:31:45 +00008537 // If we're filling in a static method where we used to have an
8538 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00008539 if (MemExpr->isImplicitAccess()) {
8540 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8541 return DeclRefExpr::Create(Context,
8542 MemExpr->getQualifier(),
8543 MemExpr->getQualifierRange(),
8544 Fn,
8545 MemExpr->getMemberLoc(),
8546 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008547 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008548 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00008549 } else {
8550 SourceLocation Loc = MemExpr->getMemberLoc();
8551 if (MemExpr->getQualifier())
8552 Loc = MemExpr->getQualifierRange().getBegin();
8553 Base = new (Context) CXXThisExpr(Loc,
8554 MemExpr->getBaseType(),
8555 /*isImplicit=*/true);
8556 }
John McCall2d74de92009-12-01 22:10:20 +00008557 } else
John McCallc3007a22010-10-26 07:05:15 +00008558 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00008559
8560 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008561 MemExpr->isArrow(),
8562 MemExpr->getQualifier(),
8563 MemExpr->getQualifierRange(),
8564 Fn,
John McCall16df1e52010-03-30 21:47:33 +00008565 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008566 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00008567 TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008568 Fn->getType(),
8569 cast<CXXMethodDecl>(Fn)->isStatic()
8570 ? VK_LValue : VK_RValue,
8571 OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008572 }
8573
John McCallc3007a22010-10-26 07:05:15 +00008574 llvm_unreachable("Invalid reference to overloaded function");
8575 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008576}
8577
John McCalldadc5752010-08-24 06:29:42 +00008578ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8579 DeclAccessPair Found,
8580 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00008581 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008582}
8583
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008584} // end namespace clang