blob: 60873cd969d849834df81186d3ca47599151f33c [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,
Douglas Gregor58281352011-01-27 00:58:17 +000049 StandardConversionSequence &SCS,
50 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000051static OverloadingResult
52IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
53 UserDefinedConversionSequence& User,
54 OverloadCandidateSet& Conversions,
55 bool AllowExplicit);
56
57
58static ImplicitConversionSequence::CompareKind
59CompareStandardConversionSequences(Sema &S,
60 const StandardConversionSequence& SCS1,
61 const StandardConversionSequence& SCS2);
62
63static ImplicitConversionSequence::CompareKind
64CompareQualificationConversions(Sema &S,
65 const StandardConversionSequence& SCS1,
66 const StandardConversionSequence& SCS2);
67
68static ImplicitConversionSequence::CompareKind
69CompareDerivedToBaseConversions(Sema &S,
70 const StandardConversionSequence& SCS1,
71 const StandardConversionSequence& SCS2);
72
73
74
Douglas Gregor5251f1b2008-10-21 16:13:35 +000075/// GetConversionCategory - Retrieve the implicit conversion
76/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000077ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000078GetConversionCategory(ImplicitConversionKind Kind) {
79 static const ImplicitConversionCategory
80 Category[(int)ICK_Num_Conversion_Kinds] = {
81 ICC_Identity,
82 ICC_Lvalue_Transformation,
83 ICC_Lvalue_Transformation,
84 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000085 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000086 ICC_Qualification_Adjustment,
87 ICC_Promotion,
88 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000089 ICC_Promotion,
90 ICC_Conversion,
91 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092 ICC_Conversion,
93 ICC_Conversion,
94 ICC_Conversion,
95 ICC_Conversion,
96 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000097 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000098 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000099 ICC_Conversion,
100 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 ICC_Conversion
102 };
103 return Category[(int)Kind];
104}
105
106/// GetConversionRank - Retrieve the implicit conversion rank
107/// corresponding to the given implicit conversion kind.
108ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
109 static const ImplicitConversionRank
110 Rank[(int)ICK_Num_Conversion_Kinds] = {
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
115 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000116 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 ICR_Promotion,
118 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000119 ICR_Promotion,
120 ICR_Conversion,
121 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
126 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000127 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000128 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000129 ICR_Conversion,
130 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000131 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000132 };
133 return Rank[(int)Kind];
134}
135
136/// GetImplicitConversionName - Return the name of this kind of
137/// implicit conversion.
138const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000139 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000140 "No conversion",
141 "Lvalue-to-rvalue",
142 "Array-to-pointer",
143 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000144 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145 "Qualification",
146 "Integral promotion",
147 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000148 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000149 "Integral conversion",
150 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000151 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000152 "Floating-integral conversion",
153 "Pointer conversion",
154 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000155 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000156 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000157 "Derived-to-base conversion",
158 "Vector conversion",
159 "Vector splat",
160 "Complex-real conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000161 };
162 return Name[Kind];
163}
164
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000165/// StandardConversionSequence - Set the standard conversion
166/// sequence to the identity conversion.
167void StandardConversionSequence::setAsIdentityConversion() {
168 First = ICK_Identity;
169 Second = ICK_Identity;
170 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000171 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000172 ReferenceBinding = false;
173 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000174 IsLvalueReference = true;
175 BindsToFunctionLvalue = false;
176 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000177 BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000178 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000179}
180
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000181/// getRank - Retrieve the rank of this standard conversion sequence
182/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
183/// implicit conversions.
184ImplicitConversionRank StandardConversionSequence::getRank() const {
185 ImplicitConversionRank Rank = ICR_Exact_Match;
186 if (GetConversionRank(First) > Rank)
187 Rank = GetConversionRank(First);
188 if (GetConversionRank(Second) > Rank)
189 Rank = GetConversionRank(Second);
190 if (GetConversionRank(Third) > Rank)
191 Rank = GetConversionRank(Third);
192 return Rank;
193}
194
195/// isPointerConversionToBool - Determines whether this conversion is
196/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000197/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000198/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000199bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000200 // Note that FromType has not necessarily been transformed by the
201 // array-to-pointer or function-to-pointer implicit conversions, so
202 // check for their presence as well as checking whether FromType is
203 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000204 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000205 (getFromType()->isPointerType() ||
206 getFromType()->isObjCObjectPointerType() ||
207 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000208 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000209 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
210 return true;
211
212 return false;
213}
214
Douglas Gregor5c407d92008-10-23 00:40:37 +0000215/// isPointerConversionToVoidPointer - Determines whether this
216/// conversion is a conversion of a pointer to a void pointer. This is
217/// used as part of the ranking of standard conversion sequences (C++
218/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000219bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000220StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000221isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000222 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000223 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000224
225 // Note that FromType has not necessarily been transformed by the
226 // array-to-pointer implicit conversion, so check for its presence
227 // and redo the conversion to get a pointer.
228 if (First == ICK_Array_To_Pointer)
229 FromType = Context.getArrayDecayedType(FromType);
230
John McCall75851b12010-10-26 06:40:27 +0000231 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000232 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000233 return ToPtrType->getPointeeType()->isVoidType();
234
235 return false;
236}
237
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000238/// DebugPrint - Print this standard conversion sequence to standard
239/// error. Useful for debugging overloading issues.
240void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000241 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000242 bool PrintedSomething = false;
243 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000244 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000245 PrintedSomething = true;
246 }
247
248 if (Second != ICK_Identity) {
249 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000251 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000252 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000253
254 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000255 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000256 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000257 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000258 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000259 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000260 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000261 PrintedSomething = true;
262 }
263
264 if (Third != ICK_Identity) {
265 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000266 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000267 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000268 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000269 PrintedSomething = true;
270 }
271
272 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000273 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000274 }
275}
276
277/// DebugPrint - Print this user-defined conversion sequence to standard
278/// error. Useful for debugging overloading issues.
279void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000280 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000281 if (Before.First || Before.Second || Before.Third) {
282 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000283 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000284 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000285 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000286 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000287 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000288 After.DebugPrint();
289 }
290}
291
292/// DebugPrint - Print this implicit conversion sequence to standard
293/// error. Useful for debugging overloading issues.
294void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000295 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000296 switch (ConversionKind) {
297 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000298 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000299 Standard.DebugPrint();
300 break;
301 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000302 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000303 UserDefined.DebugPrint();
304 break;
305 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000306 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000307 break;
John McCall0d1da222010-01-12 00:44:57 +0000308 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000309 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000310 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000311 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000312 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000313 break;
314 }
315
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000316 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000317}
318
John McCall0d1da222010-01-12 00:44:57 +0000319void AmbiguousConversionSequence::construct() {
320 new (&conversions()) ConversionSet();
321}
322
323void AmbiguousConversionSequence::destruct() {
324 conversions().~ConversionSet();
325}
326
327void
328AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
329 FromTypePtr = O.FromTypePtr;
330 ToTypePtr = O.ToTypePtr;
331 new (&conversions()) ConversionSet(O.conversions());
332}
333
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000334namespace {
335 // Structure used by OverloadCandidate::DeductionFailureInfo to store
336 // template parameter and template argument information.
337 struct DFIParamWithArguments {
338 TemplateParameter Param;
339 TemplateArgument FirstArg;
340 TemplateArgument SecondArg;
341 };
342}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000343
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000344/// \brief Convert from Sema's representation of template deduction information
345/// to the form used in overload-candidate information.
346OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000347static MakeDeductionFailureInfo(ASTContext &Context,
348 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000349 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000350 OverloadCandidate::DeductionFailureInfo Result;
351 Result.Result = static_cast<unsigned>(TDK);
352 Result.Data = 0;
353 switch (TDK) {
354 case Sema::TDK_Success:
355 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000356 case Sema::TDK_TooManyArguments:
357 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000358 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000359
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000360 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000361 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000362 Result.Data = Info.Param.getOpaqueValue();
363 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000364
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000365 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000366 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000367 // FIXME: Should allocate from normal heap so that we can free this later.
368 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000369 Saved->Param = Info.Param;
370 Saved->FirstArg = Info.FirstArg;
371 Saved->SecondArg = Info.SecondArg;
372 Result.Data = Saved;
373 break;
374 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000375
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000376 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000377 Result.Data = Info.take();
378 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000379
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000380 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000381 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000382 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000384
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000385 return Result;
386}
John McCall0d1da222010-01-12 00:44:57 +0000387
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000388void OverloadCandidate::DeductionFailureInfo::Destroy() {
389 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
390 case Sema::TDK_Success:
391 case Sema::TDK_InstantiationDepth:
392 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000393 case Sema::TDK_TooManyArguments:
394 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000395 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000396 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000397
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000398 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000399 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000400 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000401 Data = 0;
402 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000403
404 case Sema::TDK_SubstitutionFailure:
405 // FIXME: Destroy the template arugment list?
406 Data = 0;
407 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000408
Douglas Gregor461761d2010-05-08 18:20:53 +0000409 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000410 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000411 case Sema::TDK_FailedOverloadResolution:
412 break;
413 }
414}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000415
416TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000417OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
418 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
419 case Sema::TDK_Success:
420 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000421 case Sema::TDK_TooManyArguments:
422 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000423 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000424 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000425
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000426 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000427 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000428 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000429
430 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000431 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000432 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000433
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000434 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000435 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000436 case Sema::TDK_FailedOverloadResolution:
437 break;
438 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000439
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000440 return TemplateParameter();
441}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000442
Douglas Gregord09efd42010-05-08 20:07:26 +0000443TemplateArgumentList *
444OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
445 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
446 case Sema::TDK_Success:
447 case Sema::TDK_InstantiationDepth:
448 case Sema::TDK_TooManyArguments:
449 case Sema::TDK_TooFewArguments:
450 case Sema::TDK_Incomplete:
451 case Sema::TDK_InvalidExplicitArguments:
452 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000453 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000454 return 0;
455
456 case Sema::TDK_SubstitutionFailure:
457 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000458
Douglas Gregord09efd42010-05-08 20:07:26 +0000459 // Unhandled
460 case Sema::TDK_NonDeducedMismatch:
461 case Sema::TDK_FailedOverloadResolution:
462 break;
463 }
464
465 return 0;
466}
467
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000468const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
469 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
470 case Sema::TDK_Success:
471 case Sema::TDK_InstantiationDepth:
472 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000473 case Sema::TDK_TooManyArguments:
474 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000475 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000476 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000477 return 0;
478
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000479 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000480 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000481 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000482
Douglas Gregor461761d2010-05-08 18:20:53 +0000483 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000484 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000485 case Sema::TDK_FailedOverloadResolution:
486 break;
487 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000488
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000489 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000490}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000491
492const TemplateArgument *
493OverloadCandidate::DeductionFailureInfo::getSecondArg() {
494 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
495 case Sema::TDK_Success:
496 case Sema::TDK_InstantiationDepth:
497 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000498 case Sema::TDK_TooManyArguments:
499 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000500 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000501 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000502 return 0;
503
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000504 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000505 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000506 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
507
Douglas Gregor461761d2010-05-08 18:20:53 +0000508 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000509 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000510 case Sema::TDK_FailedOverloadResolution:
511 break;
512 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000513
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000514 return 0;
515}
516
517void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000518 inherited::clear();
519 Functions.clear();
520}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000521
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000522// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000523// overload of the declarations in Old. This routine returns false if
524// New and Old cannot be overloaded, e.g., if New has the same
525// signature as some function in Old (C++ 1.3.10) or if the Old
526// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000527// it does return false, MatchedDecl will point to the decl that New
528// cannot be overloaded with. This decl may be a UsingShadowDecl on
529// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000530//
531// Example: Given the following input:
532//
533// void f(int, float); // #1
534// void f(int, int); // #2
535// int f(int, int); // #3
536//
537// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000538// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000539//
John McCall3d988d92009-12-02 08:47:38 +0000540// When we process #2, Old contains only the FunctionDecl for #1. By
541// comparing the parameter types, we see that #1 and #2 are overloaded
542// (since they have different signatures), so this routine returns
543// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000544//
John McCall3d988d92009-12-02 08:47:38 +0000545// When we process #3, Old is an overload set containing #1 and #2. We
546// compare the signatures of #3 to #1 (they're overloaded, so we do
547// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
548// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000549// signature), IsOverload returns false and MatchedDecl will be set to
550// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000551//
552// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
553// into a class by a using declaration. The rules for whether to hide
554// shadow declarations ignore some properties which otherwise figure
555// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000556Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000557Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
558 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000559 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000560 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000561 NamedDecl *OldD = *I;
562
563 bool OldIsUsingDecl = false;
564 if (isa<UsingShadowDecl>(OldD)) {
565 OldIsUsingDecl = true;
566
567 // We can always introduce two using declarations into the same
568 // context, even if they have identical signatures.
569 if (NewIsUsingDecl) continue;
570
571 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
572 }
573
574 // If either declaration was introduced by a using declaration,
575 // we'll need to use slightly different rules for matching.
576 // Essentially, these rules are the normal rules, except that
577 // function templates hide function templates with different
578 // return types or template parameter lists.
579 bool UseMemberUsingDeclRules =
580 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
581
John McCall3d988d92009-12-02 08:47:38 +0000582 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000583 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
584 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
585 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
586 continue;
587 }
588
John McCalldaa3d6b2009-12-09 03:35:25 +0000589 Match = *I;
590 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000591 }
John McCall3d988d92009-12-02 08:47:38 +0000592 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000593 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
594 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
595 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
596 continue;
597 }
598
John McCalldaa3d6b2009-12-09 03:35:25 +0000599 Match = *I;
600 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000601 }
John McCalla8987a2942010-11-10 03:01:53 +0000602 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000603 // We can overload with these, which can show up when doing
604 // redeclaration checks for UsingDecls.
605 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000606 } else if (isa<TagDecl>(OldD)) {
607 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000608 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
609 // Optimistically assume that an unresolved using decl will
610 // overload; if it doesn't, we'll have to diagnose during
611 // template instantiation.
612 } else {
John McCall1f82f242009-11-18 22:49:29 +0000613 // (C++ 13p1):
614 // Only function declarations can be overloaded; object and type
615 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000616 Match = *I;
617 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000618 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000619 }
John McCall1f82f242009-11-18 22:49:29 +0000620
John McCalldaa3d6b2009-12-09 03:35:25 +0000621 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000622}
623
John McCalle9cccd82010-06-16 08:42:20 +0000624bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
625 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000626 // If both of the functions are extern "C", then they are not
627 // overloads.
628 if (Old->isExternC() && New->isExternC())
629 return false;
630
John McCall1f82f242009-11-18 22:49:29 +0000631 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
632 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
633
634 // C++ [temp.fct]p2:
635 // A function template can be overloaded with other function templates
636 // and with normal (non-template) functions.
637 if ((OldTemplate == 0) != (NewTemplate == 0))
638 return true;
639
640 // Is the function New an overload of the function Old?
641 QualType OldQType = Context.getCanonicalType(Old->getType());
642 QualType NewQType = Context.getCanonicalType(New->getType());
643
644 // Compare the signatures (C++ 1.3.10) of the two functions to
645 // determine whether they are overloads. If we find any mismatch
646 // in the signature, they are overloads.
647
648 // If either of these functions is a K&R-style function (no
649 // prototype), then we consider them to have matching signatures.
650 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
651 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
652 return false;
653
John McCall424cec92011-01-19 06:33:43 +0000654 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
655 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000656
657 // The signature of a function includes the types of its
658 // parameters (C++ 1.3.10), which includes the presence or absence
659 // of the ellipsis; see C++ DR 357).
660 if (OldQType != NewQType &&
661 (OldType->getNumArgs() != NewType->getNumArgs() ||
662 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000663 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000664 return true;
665
666 // C++ [temp.over.link]p4:
667 // The signature of a function template consists of its function
668 // signature, its return type and its template parameter list. The names
669 // of the template parameters are significant only for establishing the
670 // relationship between the template parameters and the rest of the
671 // signature.
672 //
673 // We check the return type and template parameter lists for function
674 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000675 //
676 // However, we don't consider either of these when deciding whether
677 // a member introduced by a shadow declaration is hidden.
678 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000679 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
680 OldTemplate->getTemplateParameters(),
681 false, TPL_TemplateMatch) ||
682 OldType->getResultType() != NewType->getResultType()))
683 return true;
684
685 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000686 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000687 //
688 // As part of this, also check whether one of the member functions
689 // is static, in which case they are not overloads (C++
690 // 13.1p2). While not part of the definition of the signature,
691 // this check is important to determine whether these functions
692 // can be overloaded.
693 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
694 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
695 if (OldMethod && NewMethod &&
696 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000697 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000698 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
699 if (!UseUsingDeclRules &&
700 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
701 (OldMethod->getRefQualifier() == RQ_None ||
702 NewMethod->getRefQualifier() == RQ_None)) {
703 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704 // - Member function declarations with the same name and the same
705 // parameter-type-list as well as member function template
706 // declarations with the same name, the same parameter-type-list, and
707 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000708 // them, but not all, have a ref-qualifier (8.3.5).
709 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
710 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
711 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000713
John McCall1f82f242009-11-18 22:49:29 +0000714 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000715 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716
John McCall1f82f242009-11-18 22:49:29 +0000717 // The signatures match; this is not an overload.
718 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000719}
720
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000721/// TryImplicitConversion - Attempt to perform an implicit conversion
722/// from the given expression (Expr) to the given type (ToType). This
723/// function returns an implicit conversion sequence that can be used
724/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000725///
726/// void f(float f);
727/// void g(int i) { f(i); }
728///
729/// this routine would produce an implicit conversion sequence to
730/// describe the initialization of f from i, which will be a standard
731/// conversion sequence containing an lvalue-to-rvalue conversion (C++
732/// 4.1) followed by a floating-integral conversion (C++ 4.9).
733//
734/// Note that this routine only determines how the conversion can be
735/// performed; it does not actually perform the conversion. As such,
736/// it will not produce any diagnostics if no conversion is available,
737/// but will instead return an implicit conversion sequence of kind
738/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000739///
740/// If @p SuppressUserConversions, then user-defined conversions are
741/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000742/// If @p AllowExplicit, then explicit user-defined conversions are
743/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000744static ImplicitConversionSequence
745TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
746 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000747 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000748 bool InOverloadResolution,
749 bool CStyle) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000750 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000751 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +0000752 ICS.Standard, CStyle)) {
John McCall0d1da222010-01-12 00:44:57 +0000753 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000754 return ICS;
755 }
756
John McCall5c32be02010-08-24 20:38:10 +0000757 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000758 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000759 return ICS;
760 }
761
Douglas Gregor836a7e82010-08-11 02:15:33 +0000762 // C++ [over.ics.user]p4:
763 // A conversion of an expression of class type to the same class
764 // type is given Exact Match rank, and a conversion of an
765 // expression of class type to a base class of that type is
766 // given Conversion rank, in spite of the fact that a copy/move
767 // constructor (i.e., a user-defined conversion function) is
768 // called for those cases.
769 QualType FromType = From->getType();
770 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000771 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
772 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000773 ICS.setStandard();
774 ICS.Standard.setAsIdentityConversion();
775 ICS.Standard.setFromType(FromType);
776 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000777
Douglas Gregor5ab11652010-04-17 22:01:05 +0000778 // We don't actually check at this point whether there is a valid
779 // copy/move constructor, since overloading just assumes that it
780 // exists. When we actually perform initialization, we'll find the
781 // appropriate constructor to copy the returned object, if needed.
782 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000783
Douglas Gregor5ab11652010-04-17 22:01:05 +0000784 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000785 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000786 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000787
Douglas Gregor836a7e82010-08-11 02:15:33 +0000788 return ICS;
789 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000790
Douglas Gregor836a7e82010-08-11 02:15:33 +0000791 if (SuppressUserConversions) {
792 // We're not in the case above, so there is no conversion that
793 // we can perform.
794 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000795 return ICS;
796 }
797
798 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000799 OverloadCandidateSet Conversions(From->getExprLoc());
800 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000801 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000802 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000803
804 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000805 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000806 // C++ [over.ics.user]p4:
807 // A conversion of an expression of class type to the same class
808 // type is given Exact Match rank, and a conversion of an
809 // expression of class type to a base class of that type is
810 // given Conversion rank, in spite of the fact that a copy
811 // constructor (i.e., a user-defined conversion function) is
812 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000813 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000814 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000815 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000816 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
817 QualType ToCanon
818 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000819 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000820 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000821 // Turn this into a "standard" conversion sequence, so that it
822 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000823 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000824 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000825 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000826 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000827 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000828 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000829 ICS.Standard.Second = ICK_Derived_To_Base;
830 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000831 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000832
833 // C++ [over.best.ics]p4:
834 // However, when considering the argument of a user-defined
835 // conversion function that is a candidate by 13.3.1.3 when
836 // invoked for the copying of the temporary in the second step
837 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
838 // 13.3.1.6 in all cases, only standard conversion sequences and
839 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000840 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000841 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000842 }
John McCalle8c8cd22010-01-13 22:30:33 +0000843 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000844 ICS.setAmbiguous();
845 ICS.Ambiguous.setFromType(From->getType());
846 ICS.Ambiguous.setToType(ToType);
847 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
848 Cand != Conversions.end(); ++Cand)
849 if (Cand->Viable)
850 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000851 } else {
John McCall65eb8792010-02-25 01:37:24 +0000852 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000853 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000854
855 return ICS;
856}
857
John McCall5c32be02010-08-24 20:38:10 +0000858bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
859 const InitializedEntity &Entity,
860 Expr *Initializer,
861 bool SuppressUserConversions,
862 bool AllowExplicitConversions,
Douglas Gregor58281352011-01-27 00:58:17 +0000863 bool InOverloadResolution,
864 bool CStyle) {
John McCall5c32be02010-08-24 20:38:10 +0000865 ImplicitConversionSequence ICS
866 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
867 SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000868 AllowExplicitConversions,
Douglas Gregor58281352011-01-27 00:58:17 +0000869 InOverloadResolution,
870 CStyle);
John McCall5c32be02010-08-24 20:38:10 +0000871 if (ICS.isBad()) return true;
872
873 // Perform the actual conversion.
874 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
875 return false;
876}
877
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000878/// PerformImplicitConversion - Perform an implicit conversion of the
879/// expression From to the type ToType. Returns true if there was an
880/// error, false otherwise. The expression From is replaced with the
881/// converted expression. Flavor is the kind of conversion we're
882/// performing, used in the error message. If @p AllowExplicit,
883/// explicit user-defined conversions are permitted.
884bool
885Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
886 AssignmentAction Action, bool AllowExplicit) {
887 ImplicitConversionSequence ICS;
888 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
889}
890
891bool
892Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
893 AssignmentAction Action, bool AllowExplicit,
894 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000895 ICS = clang::TryImplicitConversion(*this, From, ToType,
896 /*SuppressUserConversions=*/false,
897 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000898 /*InOverloadResolution=*/false,
899 /*CStyle=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000900 return PerformImplicitConversion(From, ToType, ICS, Action);
901}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000902
903/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000904/// conversion that strips "noreturn" off the nested function type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000905static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000906 QualType ToType, QualType &ResultTy) {
907 if (Context.hasSameUnqualifiedType(FromType, ToType))
908 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000909
John McCall991eb4b2010-12-21 00:44:39 +0000910 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
911 // where F adds one of the following at most once:
912 // - a pointer
913 // - a member pointer
914 // - a block pointer
915 CanQualType CanTo = Context.getCanonicalType(ToType);
916 CanQualType CanFrom = Context.getCanonicalType(FromType);
917 Type::TypeClass TyClass = CanTo->getTypeClass();
918 if (TyClass != CanFrom->getTypeClass()) return false;
919 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
920 if (TyClass == Type::Pointer) {
921 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
922 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
923 } else if (TyClass == Type::BlockPointer) {
924 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
925 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
926 } else if (TyClass == Type::MemberPointer) {
927 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
928 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
929 } else {
930 return false;
931 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000932
John McCall991eb4b2010-12-21 00:44:39 +0000933 TyClass = CanTo->getTypeClass();
934 if (TyClass != CanFrom->getTypeClass()) return false;
935 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
936 return false;
937 }
938
939 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
940 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
941 if (!EInfo.getNoReturn()) return false;
942
943 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
944 assert(QualType(FromFn, 0).isCanonical());
945 if (QualType(FromFn, 0) != CanTo) return false;
946
947 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000948 return true;
949}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000950
Douglas Gregor46188682010-05-18 22:42:18 +0000951/// \brief Determine whether the conversion from FromType to ToType is a valid
952/// vector conversion.
953///
954/// \param ICK Will be set to the vector conversion kind, if this is a vector
955/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000956static bool IsVectorConversion(ASTContext &Context, QualType FromType,
957 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +0000958 // We need at least one of these types to be a vector type to have a vector
959 // conversion.
960 if (!ToType->isVectorType() && !FromType->isVectorType())
961 return false;
962
963 // Identical types require no conversions.
964 if (Context.hasSameUnqualifiedType(FromType, ToType))
965 return false;
966
967 // There are no conversions between extended vector types, only identity.
968 if (ToType->isExtVectorType()) {
969 // There are no conversions between extended vector types other than the
970 // identity conversion.
971 if (FromType->isExtVectorType())
972 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000973
Douglas Gregor46188682010-05-18 22:42:18 +0000974 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000975 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000976 ICK = ICK_Vector_Splat;
977 return true;
978 }
979 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000980
981 // We can perform the conversion between vector types in the following cases:
982 // 1)vector types are equivalent AltiVec and GCC vector types
983 // 2)lax vector conversions are permitted and the vector types are of the
984 // same size
985 if (ToType->isVectorType() && FromType->isVectorType()) {
986 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000987 (Context.getLangOptions().LaxVectorConversions &&
988 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000989 ICK = ICK_Vector_Conversion;
990 return true;
991 }
Douglas Gregor46188682010-05-18 22:42:18 +0000992 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000993
Douglas Gregor46188682010-05-18 22:42:18 +0000994 return false;
995}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000996
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000997/// IsStandardConversion - Determines whether there is a standard
998/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
999/// expression From to the type ToType. Standard conversion sequences
1000/// only consider non-class types; for conversions that involve class
1001/// types, use TryImplicitConversion. If a conversion exists, SCS will
1002/// contain the standard conversion sequence required to perform this
1003/// conversion and this routine will return true. Otherwise, this
1004/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001005static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1006 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001007 StandardConversionSequence &SCS,
1008 bool CStyle) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001009 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001010
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001011 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001012 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001013 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001014 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001015 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001016 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001017
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001018 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001019 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001020 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001021 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001022 return false;
1023
Mike Stump11289f42009-09-09 15:08:12 +00001024 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001025 }
1026
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001027 // The first conversion can be an lvalue-to-rvalue conversion,
1028 // array-to-pointer conversion, or function-to-pointer conversion
1029 // (C++ 4p1).
1030
John McCall5c32be02010-08-24 20:38:10 +00001031 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001032 DeclAccessPair AccessPair;
1033 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001034 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001035 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001036 // We were able to resolve the address of the overloaded function,
1037 // so we can convert to the type of that function.
1038 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001039
1040 // we can sometimes resolve &foo<int> regardless of ToType, so check
1041 // if the type matches (identity) or we are converting to bool
1042 if (!S.Context.hasSameUnqualifiedType(
1043 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1044 QualType resultTy;
1045 // if the function type matches except for [[noreturn]], it's ok
1046 if (!IsNoReturnConversion(S.Context, FromType,
1047 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1048 // otherwise, only a boolean conversion is standard
1049 if (!ToType->isBooleanType())
1050 return false;
1051
1052 }
1053
Douglas Gregor980fb162010-04-29 18:24:40 +00001054 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
1055 if (!Method->isStatic()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001056 const Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +00001057 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1058 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +00001059 }
1060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001061
Douglas Gregor980fb162010-04-29 18:24:40 +00001062 // If the "from" expression takes the address of the overloaded
1063 // function, update the type of the resulting expression accordingly.
1064 if (FromType->getAs<FunctionType>())
1065 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +00001066 if (UnOp->getOpcode() == UO_AddrOf)
John McCall5c32be02010-08-24 20:38:10 +00001067 FromType = S.Context.getPointerType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001068
Douglas Gregor980fb162010-04-29 18:24:40 +00001069 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00001070 assert(S.Context.hasSameType(FromType,
1071 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001072 } else {
1073 return false;
1074 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001075 }
Mike Stump11289f42009-09-09 15:08:12 +00001076 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001077 // An lvalue (3.10) of a non-function, non-array type T can be
1078 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001079 bool argIsLValue = From->isLValue();
1080 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001081 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001082 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001083 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001084
1085 // If T is a non-class type, the type of the rvalue is the
1086 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001087 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1088 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001089 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001090 } else if (FromType->isArrayType()) {
1091 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001092 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001093
1094 // An lvalue or rvalue of type "array of N T" or "array of unknown
1095 // bound of T" can be converted to an rvalue of type "pointer to
1096 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001097 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001098
John McCall5c32be02010-08-24 20:38:10 +00001099 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001100 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001101 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001102
1103 // For the purpose of ranking in overload resolution
1104 // (13.3.3.1.1), this conversion is considered an
1105 // array-to-pointer conversion followed by a qualification
1106 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001107 SCS.Second = ICK_Identity;
1108 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001109 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001110 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001111 }
John McCall086a4642010-11-24 05:12:34 +00001112 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001113 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001114 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001115
1116 // An lvalue of function type T can be converted to an rvalue of
1117 // type "pointer to T." The result is a pointer to the
1118 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001119 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001120 } else {
1121 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001122 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001123 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001124 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001125
1126 // The second conversion can be an integral promotion, floating
1127 // point promotion, integral conversion, floating point conversion,
1128 // floating-integral conversion, pointer conversion,
1129 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001130 // For overloading in C, this can also be a "compatible-type"
1131 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001132 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001133 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001134 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001135 // The unqualified versions of the types are the same: there's no
1136 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001137 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001138 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001139 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001140 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001141 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001142 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001143 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001144 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001145 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001146 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001147 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001148 SCS.Second = ICK_Complex_Promotion;
1149 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001150 } else if (ToType->isBooleanType() &&
1151 (FromType->isArithmeticType() ||
1152 FromType->isAnyPointerType() ||
1153 FromType->isBlockPointerType() ||
1154 FromType->isMemberPointerType() ||
1155 FromType->isNullPtrType())) {
1156 // Boolean conversions (C++ 4.12).
1157 SCS.Second = ICK_Boolean_Conversion;
1158 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001159 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001160 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001161 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001162 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001163 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001164 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001165 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001166 SCS.Second = ICK_Complex_Conversion;
1167 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001168 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1169 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001170 // Complex-real conversions (C99 6.3.1.7)
1171 SCS.Second = ICK_Complex_Real;
1172 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001173 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001174 // Floating point conversions (C++ 4.8).
1175 SCS.Second = ICK_Floating_Conversion;
1176 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001177 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001178 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001179 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001180 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001181 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001182 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001183 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001184 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1185 SCS.Second = ICK_Block_Pointer_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001186 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1187 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001188 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001189 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001190 SCS.IncompatibleObjC = IncompatibleObjC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001191 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001192 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001193 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001194 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001195 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001196 SCS.Second = SecondICK;
1197 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001198 } else if (!S.getLangOptions().CPlusPlus &&
1199 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001200 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001201 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001202 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001203 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001204 // Treat a conversion that strips "noreturn" as an identity conversion.
1205 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001206 } else {
1207 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001208 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001209 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001210 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001211
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001212 QualType CanonFrom;
1213 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001214 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor58281352011-01-27 00:58:17 +00001215 if (S.IsQualificationConversion(FromType, ToType, CStyle)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001216 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001217 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001218 CanonFrom = S.Context.getCanonicalType(FromType);
1219 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001220 } else {
1221 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001222 SCS.Third = ICK_Identity;
1223
Mike Stump11289f42009-09-09 15:08:12 +00001224 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001225 // [...] Any difference in top-level cv-qualification is
1226 // subsumed by the initialization itself and does not constitute
1227 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001228 CanonFrom = S.Context.getCanonicalType(FromType);
1229 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001230 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001231 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001232 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1233 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001234 FromType = ToType;
1235 CanonFrom = CanonTo;
1236 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001237 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001238 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001239
1240 // If we have not converted the argument type to the parameter type,
1241 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001242 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001243 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001244
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001245 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001246}
1247
1248/// IsIntegralPromotion - Determines whether the conversion from the
1249/// expression From (whose potentially-adjusted type is FromType) to
1250/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1251/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001252bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001253 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001254 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001255 if (!To) {
1256 return false;
1257 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001258
1259 // An rvalue of type char, signed char, unsigned char, short int, or
1260 // unsigned short int can be converted to an rvalue of type int if
1261 // int can represent all the values of the source type; otherwise,
1262 // the source rvalue can be converted to an rvalue of type unsigned
1263 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001264 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1265 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001266 if (// We can promote any signed, promotable integer type to an int
1267 (FromType->isSignedIntegerType() ||
1268 // We can promote any unsigned integer type whose size is
1269 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001270 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001271 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001272 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001273 }
1274
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001275 return To->getKind() == BuiltinType::UInt;
1276 }
1277
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001278 // C++0x [conv.prom]p3:
1279 // A prvalue of an unscoped enumeration type whose underlying type is not
1280 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1281 // following types that can represent all the values of the enumeration
1282 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1283 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001284 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001285 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001286 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001287 // with lowest integer conversion rank (4.13) greater than the rank of long
1288 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001289 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001290 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1291 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1292 // provided for a scoped enumeration.
1293 if (FromEnumType->getDecl()->isScoped())
1294 return false;
1295
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001296 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001297 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001298 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001299 return Context.hasSameUnqualifiedType(ToType,
1300 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001301 }
John McCall56774992009-12-09 09:09:27 +00001302
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001303 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001304 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1305 // to an rvalue a prvalue of the first of the following types that can
1306 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001307 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001308 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001309 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001310 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001311 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001312 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001313 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001314 // Determine whether the type we're converting from is signed or
1315 // unsigned.
1316 bool FromIsSigned;
1317 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001318
John McCall56774992009-12-09 09:09:27 +00001319 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1320 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001321
1322 // The types we'll try to promote to, in the appropriate
1323 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001324 QualType PromoteTypes[6] = {
1325 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001326 Context.LongTy, Context.UnsignedLongTy ,
1327 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001328 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001329 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001330 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1331 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001332 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001333 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1334 // We found the type that we can promote to. If this is the
1335 // type we wanted, we have a promotion. Otherwise, no
1336 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001337 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001338 }
1339 }
1340 }
1341
1342 // An rvalue for an integral bit-field (9.6) can be converted to an
1343 // rvalue of type int if int can represent all the values of the
1344 // bit-field; otherwise, it can be converted to unsigned int if
1345 // unsigned int can represent all the values of the bit-field. If
1346 // the bit-field is larger yet, no integral promotion applies to
1347 // it. If the bit-field has an enumerated type, it is treated as any
1348 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001349 // FIXME: We should delay checking of bit-fields until we actually perform the
1350 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001351 using llvm::APSInt;
1352 if (From)
1353 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001354 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001355 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001356 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1357 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1358 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001359
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001360 // Are we promoting to an int from a bitfield that fits in an int?
1361 if (BitWidth < ToSize ||
1362 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1363 return To->getKind() == BuiltinType::Int;
1364 }
Mike Stump11289f42009-09-09 15:08:12 +00001365
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001366 // Are we promoting to an unsigned int from an unsigned bitfield
1367 // that fits into an unsigned int?
1368 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1369 return To->getKind() == BuiltinType::UInt;
1370 }
Mike Stump11289f42009-09-09 15:08:12 +00001371
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001372 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001373 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001374 }
Mike Stump11289f42009-09-09 15:08:12 +00001375
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001376 // An rvalue of type bool can be converted to an rvalue of type int,
1377 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001378 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001379 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001380 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001381
1382 return false;
1383}
1384
1385/// IsFloatingPointPromotion - Determines whether the conversion from
1386/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1387/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001388bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001389 /// An rvalue of type float can be converted to an rvalue of type
1390 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001391 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1392 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001393 if (FromBuiltin->getKind() == BuiltinType::Float &&
1394 ToBuiltin->getKind() == BuiltinType::Double)
1395 return true;
1396
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001397 // C99 6.3.1.5p1:
1398 // When a float is promoted to double or long double, or a
1399 // double is promoted to long double [...].
1400 if (!getLangOptions().CPlusPlus &&
1401 (FromBuiltin->getKind() == BuiltinType::Float ||
1402 FromBuiltin->getKind() == BuiltinType::Double) &&
1403 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1404 return true;
1405 }
1406
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001407 return false;
1408}
1409
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001410/// \brief Determine if a conversion is a complex promotion.
1411///
1412/// A complex promotion is defined as a complex -> complex conversion
1413/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001414/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001415bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001416 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001417 if (!FromComplex)
1418 return false;
1419
John McCall9dd450b2009-09-21 23:43:11 +00001420 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001421 if (!ToComplex)
1422 return false;
1423
1424 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001425 ToComplex->getElementType()) ||
1426 IsIntegralPromotion(0, FromComplex->getElementType(),
1427 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001428}
1429
Douglas Gregor237f96c2008-11-26 23:31:11 +00001430/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1431/// the pointer type FromPtr to a pointer to type ToPointee, with the
1432/// same type qualifiers as FromPtr has on its pointee type. ToType,
1433/// if non-empty, will be a pointer to ToType that may or may not have
1434/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001435static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001436BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001437 QualType ToPointee, QualType ToType,
1438 ASTContext &Context) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001439 assert((FromPtr->getTypeClass() == Type::Pointer ||
1440 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1441 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001442
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001443 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1444 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1445 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001446
1447 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001448 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001449 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001450 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001451
1452 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001453 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001454 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001455 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001456 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001457
1458 // Build a pointer to ToPointee. It has the right qualifiers
1459 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001460 if (isa<ObjCObjectPointerType>(ToType))
1461 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001462 return Context.getPointerType(ToPointee);
1463 }
1464
1465 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001466 QualType QualifiedCanonToPointee
1467 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001468
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001469 if (isa<ObjCObjectPointerType>(ToType))
1470 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1471 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001472}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001473
Mike Stump11289f42009-09-09 15:08:12 +00001474static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001475 bool InOverloadResolution,
1476 ASTContext &Context) {
1477 // Handle value-dependent integral null pointer constants correctly.
1478 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1479 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001480 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001481 return !InOverloadResolution;
1482
Douglas Gregor56751b52009-09-25 04:25:58 +00001483 return Expr->isNullPointerConstant(Context,
1484 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1485 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001486}
Mike Stump11289f42009-09-09 15:08:12 +00001487
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001488/// IsPointerConversion - Determines whether the conversion of the
1489/// expression From, which has the (possibly adjusted) type FromType,
1490/// can be converted to the type ToType via a pointer conversion (C++
1491/// 4.10). If so, returns true and places the converted type (that
1492/// might differ from ToType in its cv-qualifiers at some level) into
1493/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001494///
Douglas Gregora29dc052008-11-27 01:19:21 +00001495/// This routine also supports conversions to and from block pointers
1496/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1497/// pointers to interfaces. FIXME: Once we've determined the
1498/// appropriate overloading rules for Objective-C, we may want to
1499/// split the Objective-C checks into a different routine; however,
1500/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001501/// conversions, so for now they live here. IncompatibleObjC will be
1502/// set if the conversion is an allowed Objective-C conversion that
1503/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001504bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001505 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001506 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001507 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001508 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001509 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1510 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001511 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001512
Mike Stump11289f42009-09-09 15:08:12 +00001513 // Conversion from a null pointer constant to any Objective-C pointer type.
1514 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001515 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001516 ConvertedType = ToType;
1517 return true;
1518 }
1519
Douglas Gregor231d1c62008-11-27 00:15:41 +00001520 // Blocks: Block pointers can be converted to void*.
1521 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001522 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001523 ConvertedType = ToType;
1524 return true;
1525 }
1526 // Blocks: A null pointer constant can be converted to a block
1527 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001528 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001529 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001530 ConvertedType = ToType;
1531 return true;
1532 }
1533
Sebastian Redl576fd422009-05-10 18:38:11 +00001534 // If the left-hand-side is nullptr_t, the right side can be a null
1535 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001536 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001537 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001538 ConvertedType = ToType;
1539 return true;
1540 }
1541
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001542 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001543 if (!ToTypePtr)
1544 return false;
1545
1546 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001547 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001548 ConvertedType = ToType;
1549 return true;
1550 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001551
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001552 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001553 // , including objective-c pointers.
1554 QualType ToPointeeType = ToTypePtr->getPointeeType();
1555 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001556 ConvertedType = BuildSimilarlyQualifiedPointerType(
1557 FromType->getAs<ObjCObjectPointerType>(),
1558 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001559 ToType, Context);
1560 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001561 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001562 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001563 if (!FromTypePtr)
1564 return false;
1565
1566 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001567
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001568 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001569 // pointer conversion, so don't do all of the work below.
1570 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1571 return false;
1572
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001573 // An rvalue of type "pointer to cv T," where T is an object type,
1574 // can be converted to an rvalue of type "pointer to cv void" (C++
1575 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001576 if (FromPointeeType->isIncompleteOrObjectType() &&
1577 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001578 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001579 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001580 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001581 return true;
1582 }
1583
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001584 // When we're overloading in C, we allow a special kind of pointer
1585 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001586 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001587 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001588 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001589 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001590 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001591 return true;
1592 }
1593
Douglas Gregor5c407d92008-10-23 00:40:37 +00001594 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001595 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001596 // An rvalue of type "pointer to cv D," where D is a class type,
1597 // can be converted to an rvalue of type "pointer to cv B," where
1598 // B is a base class (clause 10) of D. If B is an inaccessible
1599 // (clause 11) or ambiguous (10.2) base class of D, a program that
1600 // necessitates this conversion is ill-formed. The result of the
1601 // conversion is a pointer to the base class sub-object of the
1602 // derived class object. The null pointer value is converted to
1603 // the null pointer value of the destination type.
1604 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001605 // Note that we do not check for ambiguity or inaccessibility
1606 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001607 if (getLangOptions().CPlusPlus &&
1608 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001609 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001610 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001611 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001612 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001613 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001614 ToType, Context);
1615 return true;
1616 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001617
Douglas Gregora119f102008-12-19 19:13:09 +00001618 return false;
1619}
1620
1621/// isObjCPointerConversion - Determines whether this is an
1622/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1623/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001624bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001625 QualType& ConvertedType,
1626 bool &IncompatibleObjC) {
1627 if (!getLangOptions().ObjC1)
1628 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001629
Steve Naroff7cae42b2009-07-10 23:34:53 +00001630 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001631 const ObjCObjectPointerType* ToObjCPtr =
1632 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001633 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001634 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001635
Steve Naroff7cae42b2009-07-10 23:34:53 +00001636 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001637 // If the pointee types are the same (ignoring qualifications),
1638 // then this is not a pointer conversion.
1639 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1640 FromObjCPtr->getPointeeType()))
1641 return false;
1642
Steve Naroff1329fa02009-07-15 18:40:39 +00001643 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001644 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001645 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001646 ConvertedType = ToType;
1647 return true;
1648 }
1649 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001650 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001651 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001652 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001653 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001654 ConvertedType = ToType;
1655 return true;
1656 }
1657 // Objective C++: We're able to convert from a pointer to an
1658 // interface to a pointer to a different interface.
1659 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001660 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1661 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1662 if (getLangOptions().CPlusPlus && LHS && RHS &&
1663 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1664 FromObjCPtr->getPointeeType()))
1665 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001666 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001667 ToObjCPtr->getPointeeType(),
1668 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001669 return true;
1670 }
1671
1672 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1673 // Okay: this is some kind of implicit downcast of Objective-C
1674 // interfaces, which is permitted. However, we're going to
1675 // complain about it.
1676 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001677 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001678 ToObjCPtr->getPointeeType(),
1679 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001680 return true;
1681 }
Mike Stump11289f42009-09-09 15:08:12 +00001682 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001683 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001684 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001685 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001686 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001687 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001688 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001689 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001690 // to a block pointer type.
1691 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1692 ConvertedType = ToType;
1693 return true;
1694 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001695 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001697 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001698 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001699 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001700 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001701 ConvertedType = ToType;
1702 return true;
1703 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001704 else
Douglas Gregora119f102008-12-19 19:13:09 +00001705 return false;
1706
Douglas Gregor033f56d2008-12-23 00:53:59 +00001707 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001708 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001709 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001710 else if (const BlockPointerType *FromBlockPtr =
1711 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001712 FromPointeeType = FromBlockPtr->getPointeeType();
1713 else
Douglas Gregora119f102008-12-19 19:13:09 +00001714 return false;
1715
Douglas Gregora119f102008-12-19 19:13:09 +00001716 // If we have pointers to pointers, recursively check whether this
1717 // is an Objective-C conversion.
1718 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1719 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1720 IncompatibleObjC)) {
1721 // We always complain about this conversion.
1722 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001723 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregora119f102008-12-19 19:13:09 +00001724 return true;
1725 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001726 // Allow conversion of pointee being objective-c pointer to another one;
1727 // as in I* to id.
1728 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1729 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1730 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1731 IncompatibleObjC)) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001732 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001733 return true;
1734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001735
Douglas Gregor033f56d2008-12-23 00:53:59 +00001736 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001737 // differences in the argument and result types are in Objective-C
1738 // pointer conversions. If so, we permit the conversion (but
1739 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001740 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001741 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001742 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001743 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001744 if (FromFunctionType && ToFunctionType) {
1745 // If the function types are exactly the same, this isn't an
1746 // Objective-C pointer conversion.
1747 if (Context.getCanonicalType(FromPointeeType)
1748 == Context.getCanonicalType(ToPointeeType))
1749 return false;
1750
1751 // Perform the quick checks that will tell us whether these
1752 // function types are obviously different.
1753 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1754 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1755 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1756 return false;
1757
1758 bool HasObjCConversion = false;
1759 if (Context.getCanonicalType(FromFunctionType->getResultType())
1760 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1761 // Okay, the types match exactly. Nothing to do.
1762 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1763 ToFunctionType->getResultType(),
1764 ConvertedType, IncompatibleObjC)) {
1765 // Okay, we have an Objective-C pointer conversion.
1766 HasObjCConversion = true;
1767 } else {
1768 // Function types are too different. Abort.
1769 return false;
1770 }
Mike Stump11289f42009-09-09 15:08:12 +00001771
Douglas Gregora119f102008-12-19 19:13:09 +00001772 // Check argument types.
1773 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1774 ArgIdx != NumArgs; ++ArgIdx) {
1775 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1776 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1777 if (Context.getCanonicalType(FromArgType)
1778 == Context.getCanonicalType(ToArgType)) {
1779 // Okay, the types match exactly. Nothing to do.
1780 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1781 ConvertedType, IncompatibleObjC)) {
1782 // Okay, we have an Objective-C pointer conversion.
1783 HasObjCConversion = true;
1784 } else {
1785 // Argument types are too different. Abort.
1786 return false;
1787 }
1788 }
1789
1790 if (HasObjCConversion) {
1791 // We had an Objective-C conversion. Allow this pointer
1792 // conversion, but complain about it.
1793 ConvertedType = ToType;
1794 IncompatibleObjC = true;
1795 return true;
1796 }
1797 }
1798
Sebastian Redl72b597d2009-01-25 19:43:20 +00001799 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001800}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001801
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001802bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1803 QualType& ConvertedType) {
1804 QualType ToPointeeType;
1805 if (const BlockPointerType *ToBlockPtr =
1806 ToType->getAs<BlockPointerType>())
1807 ToPointeeType = ToBlockPtr->getPointeeType();
1808 else
1809 return false;
1810
1811 QualType FromPointeeType;
1812 if (const BlockPointerType *FromBlockPtr =
1813 FromType->getAs<BlockPointerType>())
1814 FromPointeeType = FromBlockPtr->getPointeeType();
1815 else
1816 return false;
1817 // We have pointer to blocks, check whether the only
1818 // differences in the argument and result types are in Objective-C
1819 // pointer conversions. If so, we permit the conversion.
1820
1821 const FunctionProtoType *FromFunctionType
1822 = FromPointeeType->getAs<FunctionProtoType>();
1823 const FunctionProtoType *ToFunctionType
1824 = ToPointeeType->getAs<FunctionProtoType>();
1825
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001826 if (!FromFunctionType || !ToFunctionType)
1827 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001828
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001829 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001830 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001831
1832 // Perform the quick checks that will tell us whether these
1833 // function types are obviously different.
1834 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1835 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
1836 return false;
1837
1838 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
1839 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
1840 if (FromEInfo != ToEInfo)
1841 return false;
1842
1843 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00001844 if (Context.hasSameType(FromFunctionType->getResultType(),
1845 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001846 // Okay, the types match exactly. Nothing to do.
1847 } else {
1848 QualType RHS = FromFunctionType->getResultType();
1849 QualType LHS = ToFunctionType->getResultType();
1850 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
1851 !RHS.hasQualifiers() && LHS.hasQualifiers())
1852 LHS = LHS.getUnqualifiedType();
1853
1854 if (Context.hasSameType(RHS,LHS)) {
1855 // OK exact match.
1856 } else if (isObjCPointerConversion(RHS, LHS,
1857 ConvertedType, IncompatibleObjC)) {
1858 if (IncompatibleObjC)
1859 return false;
1860 // Okay, we have an Objective-C pointer conversion.
1861 }
1862 else
1863 return false;
1864 }
1865
1866 // Check argument types.
1867 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1868 ArgIdx != NumArgs; ++ArgIdx) {
1869 IncompatibleObjC = false;
1870 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1871 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1872 if (Context.hasSameType(FromArgType, ToArgType)) {
1873 // Okay, the types match exactly. Nothing to do.
1874 } else if (isObjCPointerConversion(ToArgType, FromArgType,
1875 ConvertedType, IncompatibleObjC)) {
1876 if (IncompatibleObjC)
1877 return false;
1878 // Okay, we have an Objective-C pointer conversion.
1879 } else
1880 // Argument types are too different. Abort.
1881 return false;
1882 }
1883 ConvertedType = ToType;
1884 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001885}
1886
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001887/// FunctionArgTypesAreEqual - This routine checks two function proto types
1888/// for equlity of their argument types. Caller has already checked that
1889/// they have same number of arguments. This routine assumes that Objective-C
1890/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001891bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00001892 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001893 if (!getLangOptions().ObjC1)
1894 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1895 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001896
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001897 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1898 N = NewType->arg_type_begin(),
1899 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1900 QualType ToType = (*O);
1901 QualType FromType = (*N);
1902 if (ToType != FromType) {
1903 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1904 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001905 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1906 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1907 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1908 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001909 continue;
1910 }
John McCall8b07ec22010-05-15 11:32:37 +00001911 else if (const ObjCObjectPointerType *PTTo =
1912 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001913 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00001914 FromType->getAs<ObjCObjectPointerType>())
1915 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1916 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001918 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001919 }
1920 }
1921 return true;
1922}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001923
Douglas Gregor39c16d42008-10-24 04:54:22 +00001924/// CheckPointerConversion - Check the pointer conversion from the
1925/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001926/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001927/// conversions for which IsPointerConversion has already returned
1928/// true. It returns true and produces a diagnostic if there was an
1929/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001930bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001931 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001932 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001933 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001934 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001935 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001936
John McCall8cb679e2010-11-15 09:13:47 +00001937 Kind = CK_BitCast;
1938
Douglas Gregor4038cf42010-06-08 17:35:15 +00001939 if (CXXBoolLiteralExpr* LitBool
1940 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001941 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregor4038cf42010-06-08 17:35:15 +00001942 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1943 << ToType;
1944
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001945 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1946 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001947 QualType FromPointeeType = FromPtrType->getPointeeType(),
1948 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001949
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001950 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1951 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001952 // We must have a derived-to-base conversion. Check an
1953 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001954 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1955 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001956 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001957 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001958 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001959
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001960 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00001961 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001962 }
1963 }
Mike Stump11289f42009-09-09 15:08:12 +00001964 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00001965 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001966 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001967 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001968 // Objective-C++ conversions are always okay.
1969 // FIXME: We should have a different class of conversions for the
1970 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001971 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001972 return false;
John McCall8cb679e2010-11-15 09:13:47 +00001973 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001974 }
John McCall8cb679e2010-11-15 09:13:47 +00001975
1976 // We shouldn't fall into this case unless it's valid for other
1977 // reasons.
1978 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1979 Kind = CK_NullToPointer;
1980
Douglas Gregor39c16d42008-10-24 04:54:22 +00001981 return false;
1982}
1983
Sebastian Redl72b597d2009-01-25 19:43:20 +00001984/// IsMemberPointerConversion - Determines whether the conversion of the
1985/// expression From, which has the (possibly adjusted) type FromType, can be
1986/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1987/// If so, returns true and places the converted type (that might differ from
1988/// ToType in its cv-qualifiers at some level) into ConvertedType.
1989bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001990 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001991 bool InOverloadResolution,
1992 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001993 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001994 if (!ToTypePtr)
1995 return false;
1996
1997 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001998 if (From->isNullPointerConstant(Context,
1999 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2000 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002001 ConvertedType = ToType;
2002 return true;
2003 }
2004
2005 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002006 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002007 if (!FromTypePtr)
2008 return false;
2009
2010 // A pointer to member of B can be converted to a pointer to member of D,
2011 // where D is derived from B (C++ 4.11p2).
2012 QualType FromClass(FromTypePtr->getClass(), 0);
2013 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002014
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002015 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2016 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2017 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002018 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2019 ToClass.getTypePtr());
2020 return true;
2021 }
2022
2023 return false;
2024}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002025
Sebastian Redl72b597d2009-01-25 19:43:20 +00002026/// CheckMemberPointerConversion - Check the member pointer conversion from the
2027/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002028/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002029/// for which IsMemberPointerConversion has already returned true. It returns
2030/// true and produces a diagnostic if there was an error, or returns false
2031/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002032bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002033 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002034 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002035 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002036 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002037 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002038 if (!FromPtrType) {
2039 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002040 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002041 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002042 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002043 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002044 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002045 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002046
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002047 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002048 assert(ToPtrType && "No member pointer cast has a target type "
2049 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002050
Sebastian Redled8f2002009-01-28 18:33:18 +00002051 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2052 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002053
Sebastian Redled8f2002009-01-28 18:33:18 +00002054 // FIXME: What about dependent types?
2055 assert(FromClass->isRecordType() && "Pointer into non-class.");
2056 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002057
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002058 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002059 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002060 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2061 assert(DerivationOkay &&
2062 "Should not have been called if derivation isn't OK.");
2063 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002064
Sebastian Redled8f2002009-01-28 18:33:18 +00002065 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2066 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002067 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2068 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2069 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2070 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002071 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002072
Douglas Gregor89ee6822009-02-28 01:32:25 +00002073 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002074 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2075 << FromClass << ToClass << QualType(VBase, 0)
2076 << From->getSourceRange();
2077 return true;
2078 }
2079
John McCall5b0829a2010-02-10 09:31:12 +00002080 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002081 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2082 Paths.front(),
2083 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002084
Anders Carlssond7923c62009-08-22 23:33:40 +00002085 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002086 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002087 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002088 return false;
2089}
2090
Douglas Gregor9a657932008-10-21 23:43:52 +00002091/// IsQualificationConversion - Determines whether the conversion from
2092/// an rvalue of type FromType to ToType is a qualification conversion
2093/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00002094bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002095Sema::IsQualificationConversion(QualType FromType, QualType ToType,
Douglas Gregor58281352011-01-27 00:58:17 +00002096 bool CStyle) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002097 FromType = Context.getCanonicalType(FromType);
2098 ToType = Context.getCanonicalType(ToType);
2099
2100 // If FromType and ToType are the same type, this is not a
2101 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002102 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002103 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002104
Douglas Gregor9a657932008-10-21 23:43:52 +00002105 // (C++ 4.4p4):
2106 // A conversion can add cv-qualifiers at levels other than the first
2107 // in multi-level pointers, subject to the following rules: [...]
2108 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002109 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002110 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002111 // Within each iteration of the loop, we check the qualifiers to
2112 // determine if this still looks like a qualification
2113 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002114 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002115 // until there are no more pointers or pointers-to-members left to
2116 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002117 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002118
2119 // -- for every j > 0, if const is in cv 1,j then const is in cv
2120 // 2,j, and similarly for volatile.
Douglas Gregor58281352011-01-27 00:58:17 +00002121 if (!CStyle && !ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00002122 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002123
Douglas Gregor9a657932008-10-21 23:43:52 +00002124 // -- if the cv 1,j and cv 2,j are different, then const is in
2125 // every cv for 0 < k < j.
Douglas Gregor58281352011-01-27 00:58:17 +00002126 if (!CStyle && FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002127 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002128 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002129
Douglas Gregor9a657932008-10-21 23:43:52 +00002130 // Keep track of whether all prior cv-qualifiers in the "to" type
2131 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002132 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00002133 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002134 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002135
2136 // We are left with FromType and ToType being the pointee types
2137 // after unwrapping the original FromType and ToType the same number
2138 // of types. If we unwrapped any pointers, and if FromType and
2139 // ToType have the same unqualified type (since we checked
2140 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002141 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002142}
2143
Douglas Gregor576e98c2009-01-30 23:27:23 +00002144/// Determines whether there is a user-defined conversion sequence
2145/// (C++ [over.ics.user]) that converts expression From to the type
2146/// ToType. If such a conversion exists, User will contain the
2147/// user-defined conversion sequence that performs such a conversion
2148/// and this routine will return true. Otherwise, this routine returns
2149/// false and User is unspecified.
2150///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002151/// \param AllowExplicit true if the conversion should consider C++0x
2152/// "explicit" conversion functions as well as non-explicit conversion
2153/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002154static OverloadingResult
2155IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2156 UserDefinedConversionSequence& User,
2157 OverloadCandidateSet& CandidateSet,
2158 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002159 // Whether we will only visit constructors.
2160 bool ConstructorsOnly = false;
2161
2162 // If the type we are conversion to is a class type, enumerate its
2163 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002164 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002165 // C++ [over.match.ctor]p1:
2166 // When objects of class type are direct-initialized (8.5), or
2167 // copy-initialized from an expression of the same or a
2168 // derived class type (8.5), overload resolution selects the
2169 // constructor. [...] For copy-initialization, the candidate
2170 // functions are all the converting constructors (12.3.1) of
2171 // that class. The argument list is the expression-list within
2172 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002173 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002174 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002175 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002176 ConstructorsOnly = true;
2177
John McCall5c32be02010-08-24 20:38:10 +00002178 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002179 // We're not going to find any constructors.
2180 } else if (CXXRecordDecl *ToRecordDecl
2181 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002182 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002183 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002184 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002185 NamedDecl *D = *Con;
2186 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2187
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002188 // Find the constructor (which may be a template).
2189 CXXConstructorDecl *Constructor = 0;
2190 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002191 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002192 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002193 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002194 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2195 else
John McCalla0296f72010-03-19 07:35:19 +00002196 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002197
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002198 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002199 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002200 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002201 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2202 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002203 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002204 /*SuppressUserConversions=*/
2205 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002206 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002207 // Allow one user-defined conversion when user specifies a
2208 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002209 S.AddOverloadCandidate(Constructor, FoundDecl,
2210 &From, 1, CandidateSet,
2211 /*SuppressUserConversions=*/
2212 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002213 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002214 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002215 }
2216 }
2217
Douglas Gregor5ab11652010-04-17 22:01:05 +00002218 // Enumerate conversion functions, if we're allowed to.
2219 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002220 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2221 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002222 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002223 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002224 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002225 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002226 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2227 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002228 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002229 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002230 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002231 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002232 DeclAccessPair FoundDecl = I.getPair();
2233 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002234 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2235 if (isa<UsingShadowDecl>(D))
2236 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2237
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002238 CXXConversionDecl *Conv;
2239 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002240 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2241 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002242 else
John McCallda4458e2010-03-31 01:36:47 +00002243 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002244
2245 if (AllowExplicit || !Conv->isExplicit()) {
2246 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002247 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2248 ActingContext, From, ToType,
2249 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002250 else
John McCall5c32be02010-08-24 20:38:10 +00002251 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2252 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002253 }
2254 }
2255 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002256 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002257
2258 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002259 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002260 case OR_Success:
2261 // Record the standard conversion we used and the conversion function.
2262 if (CXXConstructorDecl *Constructor
2263 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2264 // C++ [over.ics.user]p1:
2265 // If the user-defined conversion is specified by a
2266 // constructor (12.3.1), the initial standard conversion
2267 // sequence converts the source type to the type required by
2268 // the argument of the constructor.
2269 //
2270 QualType ThisType = Constructor->getThisType(S.Context);
2271 if (Best->Conversions[0].isEllipsis())
2272 User.EllipsisConversion = true;
2273 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002274 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002275 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002276 }
John McCall5c32be02010-08-24 20:38:10 +00002277 User.ConversionFunction = Constructor;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002278 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002279 User.After.setAsIdentityConversion();
2280 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2281 User.After.setAllToTypes(ToType);
2282 return OR_Success;
2283 } else if (CXXConversionDecl *Conversion
2284 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2285 // C++ [over.ics.user]p1:
2286 //
2287 // [...] If the user-defined conversion is specified by a
2288 // conversion function (12.3.2), the initial standard
2289 // conversion sequence converts the source type to the
2290 // implicit object parameter of the conversion function.
2291 User.Before = Best->Conversions[0].Standard;
2292 User.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002293 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002294 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002295
John McCall5c32be02010-08-24 20:38:10 +00002296 // C++ [over.ics.user]p2:
2297 // The second standard conversion sequence converts the
2298 // result of the user-defined conversion to the target type
2299 // for the sequence. Since an implicit conversion sequence
2300 // is an initialization, the special rules for
2301 // initialization by user-defined conversion apply when
2302 // selecting the best user-defined conversion for a
2303 // user-defined conversion sequence (see 13.3.3 and
2304 // 13.3.3.1).
2305 User.After = Best->FinalConversion;
2306 return OR_Success;
2307 } else {
2308 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002309 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002310 }
2311
John McCall5c32be02010-08-24 20:38:10 +00002312 case OR_No_Viable_Function:
2313 return OR_No_Viable_Function;
2314 case OR_Deleted:
2315 // No conversion here! We're done.
2316 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002317
John McCall5c32be02010-08-24 20:38:10 +00002318 case OR_Ambiguous:
2319 return OR_Ambiguous;
2320 }
2321
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002322 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002323}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002324
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002325bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002326Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002327 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002328 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002329 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002330 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002331 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002332 if (OvResult == OR_Ambiguous)
2333 Diag(From->getSourceRange().getBegin(),
2334 diag::err_typecheck_ambiguous_condition)
2335 << From->getType() << ToType << From->getSourceRange();
2336 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2337 Diag(From->getSourceRange().getBegin(),
2338 diag::err_typecheck_nonviable_condition)
2339 << From->getType() << ToType << From->getSourceRange();
2340 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002341 return false;
John McCall5c32be02010-08-24 20:38:10 +00002342 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002343 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002344}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002345
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002346/// CompareImplicitConversionSequences - Compare two implicit
2347/// conversion sequences to determine whether one is better than the
2348/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002349static ImplicitConversionSequence::CompareKind
2350CompareImplicitConversionSequences(Sema &S,
2351 const ImplicitConversionSequence& ICS1,
2352 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002353{
2354 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2355 // conversion sequences (as defined in 13.3.3.1)
2356 // -- a standard conversion sequence (13.3.3.1.1) is a better
2357 // conversion sequence than a user-defined conversion sequence or
2358 // an ellipsis conversion sequence, and
2359 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2360 // conversion sequence than an ellipsis conversion sequence
2361 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002362 //
John McCall0d1da222010-01-12 00:44:57 +00002363 // C++0x [over.best.ics]p10:
2364 // For the purpose of ranking implicit conversion sequences as
2365 // described in 13.3.3.2, the ambiguous conversion sequence is
2366 // treated as a user-defined sequence that is indistinguishable
2367 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002368 if (ICS1.getKindRank() < ICS2.getKindRank())
2369 return ImplicitConversionSequence::Better;
2370 else if (ICS2.getKindRank() < ICS1.getKindRank())
2371 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002372
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002373 // The following checks require both conversion sequences to be of
2374 // the same kind.
2375 if (ICS1.getKind() != ICS2.getKind())
2376 return ImplicitConversionSequence::Indistinguishable;
2377
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002378 // Two implicit conversion sequences of the same form are
2379 // indistinguishable conversion sequences unless one of the
2380 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002381 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002382 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002383 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002384 // User-defined conversion sequence U1 is a better conversion
2385 // sequence than another user-defined conversion sequence U2 if
2386 // they contain the same user-defined conversion function or
2387 // constructor and if the second standard conversion sequence of
2388 // U1 is better than the second standard conversion sequence of
2389 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002390 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002391 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002392 return CompareStandardConversionSequences(S,
2393 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002394 ICS2.UserDefined.After);
2395 }
2396
2397 return ImplicitConversionSequence::Indistinguishable;
2398}
2399
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002400static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2401 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2402 Qualifiers Quals;
2403 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002404 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002405 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002406
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002407 return Context.hasSameUnqualifiedType(T1, T2);
2408}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002409
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002410// Per 13.3.3.2p3, compare the given standard conversion sequences to
2411// determine if one is a proper subset of the other.
2412static ImplicitConversionSequence::CompareKind
2413compareStandardConversionSubsets(ASTContext &Context,
2414 const StandardConversionSequence& SCS1,
2415 const StandardConversionSequence& SCS2) {
2416 ImplicitConversionSequence::CompareKind Result
2417 = ImplicitConversionSequence::Indistinguishable;
2418
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002419 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002420 // any non-identity conversion sequence
2421 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2422 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2423 return ImplicitConversionSequence::Better;
2424 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2425 return ImplicitConversionSequence::Worse;
2426 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002427
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002428 if (SCS1.Second != SCS2.Second) {
2429 if (SCS1.Second == ICK_Identity)
2430 Result = ImplicitConversionSequence::Better;
2431 else if (SCS2.Second == ICK_Identity)
2432 Result = ImplicitConversionSequence::Worse;
2433 else
2434 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002435 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002436 return ImplicitConversionSequence::Indistinguishable;
2437
2438 if (SCS1.Third == SCS2.Third) {
2439 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2440 : ImplicitConversionSequence::Indistinguishable;
2441 }
2442
2443 if (SCS1.Third == ICK_Identity)
2444 return Result == ImplicitConversionSequence::Worse
2445 ? ImplicitConversionSequence::Indistinguishable
2446 : ImplicitConversionSequence::Better;
2447
2448 if (SCS2.Third == ICK_Identity)
2449 return Result == ImplicitConversionSequence::Better
2450 ? ImplicitConversionSequence::Indistinguishable
2451 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002452
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002453 return ImplicitConversionSequence::Indistinguishable;
2454}
2455
Douglas Gregore696ebb2011-01-26 14:52:12 +00002456/// \brief Determine whether one of the given reference bindings is better
2457/// than the other based on what kind of bindings they are.
2458static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2459 const StandardConversionSequence &SCS2) {
2460 // C++0x [over.ics.rank]p3b4:
2461 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2462 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002463 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002464 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002465 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002466 // reference*.
2467 //
2468 // FIXME: Rvalue references. We're going rogue with the above edits,
2469 // because the semantics in the current C++0x working paper (N3225 at the
2470 // time of this writing) break the standard definition of std::forward
2471 // and std::reference_wrapper when dealing with references to functions.
2472 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002473 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2474 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2475 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002476
Douglas Gregore696ebb2011-01-26 14:52:12 +00002477 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2478 SCS2.IsLvalueReference) ||
2479 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2480 !SCS2.IsLvalueReference);
2481}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002482
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002483/// CompareStandardConversionSequences - Compare two standard
2484/// conversion sequences to determine whether one is better than the
2485/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002486static ImplicitConversionSequence::CompareKind
2487CompareStandardConversionSequences(Sema &S,
2488 const StandardConversionSequence& SCS1,
2489 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002490{
2491 // Standard conversion sequence S1 is a better conversion sequence
2492 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2493
2494 // -- S1 is a proper subsequence of S2 (comparing the conversion
2495 // sequences in the canonical form defined by 13.3.3.1.1,
2496 // excluding any Lvalue Transformation; the identity conversion
2497 // sequence is considered to be a subsequence of any
2498 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002499 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002500 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002501 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002502
2503 // -- the rank of S1 is better than the rank of S2 (by the rules
2504 // defined below), or, if not that,
2505 ImplicitConversionRank Rank1 = SCS1.getRank();
2506 ImplicitConversionRank Rank2 = SCS2.getRank();
2507 if (Rank1 < Rank2)
2508 return ImplicitConversionSequence::Better;
2509 else if (Rank2 < Rank1)
2510 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002511
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002512 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2513 // are indistinguishable unless one of the following rules
2514 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002515
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002516 // A conversion that is not a conversion of a pointer, or
2517 // pointer to member, to bool is better than another conversion
2518 // that is such a conversion.
2519 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2520 return SCS2.isPointerConversionToBool()
2521 ? ImplicitConversionSequence::Better
2522 : ImplicitConversionSequence::Worse;
2523
Douglas Gregor5c407d92008-10-23 00:40:37 +00002524 // C++ [over.ics.rank]p4b2:
2525 //
2526 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002527 // conversion of B* to A* is better than conversion of B* to
2528 // void*, and conversion of A* to void* is better than conversion
2529 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002530 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002531 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002532 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002533 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002534 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2535 // Exactly one of the conversion sequences is a conversion to
2536 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002537 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2538 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002539 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2540 // Neither conversion sequence converts to a void pointer; compare
2541 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002542 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002543 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002544 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002545 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2546 // Both conversion sequences are conversions to void
2547 // pointers. Compare the source types to determine if there's an
2548 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002549 QualType FromType1 = SCS1.getFromType();
2550 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002551
2552 // Adjust the types we're converting from via the array-to-pointer
2553 // conversion, if we need to.
2554 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002555 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002556 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002557 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002558
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002559 QualType FromPointee1
2560 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2561 QualType FromPointee2
2562 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002563
John McCall5c32be02010-08-24 20:38:10 +00002564 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002565 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002566 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002567 return ImplicitConversionSequence::Worse;
2568
2569 // Objective-C++: If one interface is more specific than the
2570 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002571 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2572 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002573 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002574 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002575 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002576 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002577 return ImplicitConversionSequence::Worse;
2578 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002579 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002580
2581 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2582 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002583 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002584 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002585 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002586
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002587 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002588 // Check for a better reference binding based on the kind of bindings.
2589 if (isBetterReferenceBindingKind(SCS1, SCS2))
2590 return ImplicitConversionSequence::Better;
2591 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2592 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002593
Sebastian Redlb28b4072009-03-22 23:49:27 +00002594 // C++ [over.ics.rank]p3b4:
2595 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2596 // which the references refer are the same type except for
2597 // top-level cv-qualifiers, and the type to which the reference
2598 // initialized by S2 refers is more cv-qualified than the type
2599 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002600 QualType T1 = SCS1.getToType(2);
2601 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002602 T1 = S.Context.getCanonicalType(T1);
2603 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002604 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002605 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2606 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002607 if (UnqualT1 == UnqualT2) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00002608 // If the type is an array type, promote the element qualifiers to the
2609 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002610 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002611 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002612 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002613 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002614 if (T2.isMoreQualifiedThan(T1))
2615 return ImplicitConversionSequence::Better;
2616 else if (T1.isMoreQualifiedThan(T2))
2617 return ImplicitConversionSequence::Worse;
2618 }
2619 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002620
2621 return ImplicitConversionSequence::Indistinguishable;
2622}
2623
2624/// CompareQualificationConversions - Compares two standard conversion
2625/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002626/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2627ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002628CompareQualificationConversions(Sema &S,
2629 const StandardConversionSequence& SCS1,
2630 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002631 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002632 // -- S1 and S2 differ only in their qualification conversion and
2633 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2634 // cv-qualification signature of type T1 is a proper subset of
2635 // the cv-qualification signature of type T2, and S1 is not the
2636 // deprecated string literal array-to-pointer conversion (4.2).
2637 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2638 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2639 return ImplicitConversionSequence::Indistinguishable;
2640
2641 // FIXME: the example in the standard doesn't use a qualification
2642 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002643 QualType T1 = SCS1.getToType(2);
2644 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002645 T1 = S.Context.getCanonicalType(T1);
2646 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002647 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002648 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2649 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002650
2651 // If the types are the same, we won't learn anything by unwrapped
2652 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002653 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002654 return ImplicitConversionSequence::Indistinguishable;
2655
Chandler Carruth607f38e2009-12-29 07:16:59 +00002656 // If the type is an array type, promote the element qualifiers to the type
2657 // for comparison.
2658 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002659 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002660 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002661 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002662
Mike Stump11289f42009-09-09 15:08:12 +00002663 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002664 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002665 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002666 // Within each iteration of the loop, we check the qualifiers to
2667 // determine if this still looks like a qualification
2668 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002669 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002670 // until there are no more pointers or pointers-to-members left
2671 // to unwrap. This essentially mimics what
2672 // IsQualificationConversion does, but here we're checking for a
2673 // strict subset of qualifiers.
2674 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2675 // The qualifiers are the same, so this doesn't tell us anything
2676 // about how the sequences rank.
2677 ;
2678 else if (T2.isMoreQualifiedThan(T1)) {
2679 // T1 has fewer qualifiers, so it could be the better sequence.
2680 if (Result == ImplicitConversionSequence::Worse)
2681 // Neither has qualifiers that are a subset of the other's
2682 // qualifiers.
2683 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002684
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002685 Result = ImplicitConversionSequence::Better;
2686 } else if (T1.isMoreQualifiedThan(T2)) {
2687 // T2 has fewer qualifiers, so it could be the better sequence.
2688 if (Result == ImplicitConversionSequence::Better)
2689 // Neither has qualifiers that are a subset of the other's
2690 // qualifiers.
2691 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002692
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002693 Result = ImplicitConversionSequence::Worse;
2694 } else {
2695 // Qualifiers are disjoint.
2696 return ImplicitConversionSequence::Indistinguishable;
2697 }
2698
2699 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002700 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002701 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002702 }
2703
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002704 // Check that the winning standard conversion sequence isn't using
2705 // the deprecated string literal array to pointer conversion.
2706 switch (Result) {
2707 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002708 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002709 Result = ImplicitConversionSequence::Indistinguishable;
2710 break;
2711
2712 case ImplicitConversionSequence::Indistinguishable:
2713 break;
2714
2715 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002716 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002717 Result = ImplicitConversionSequence::Indistinguishable;
2718 break;
2719 }
2720
2721 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002722}
2723
Douglas Gregor5c407d92008-10-23 00:40:37 +00002724/// CompareDerivedToBaseConversions - Compares two standard conversion
2725/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002726/// various kinds of derived-to-base conversions (C++
2727/// [over.ics.rank]p4b3). As part of these checks, we also look at
2728/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002729ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002730CompareDerivedToBaseConversions(Sema &S,
2731 const StandardConversionSequence& SCS1,
2732 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002733 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002734 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002735 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002736 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002737
2738 // Adjust the types we're converting from via the array-to-pointer
2739 // conversion, if we need to.
2740 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002741 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002742 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002743 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002744
2745 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002746 FromType1 = S.Context.getCanonicalType(FromType1);
2747 ToType1 = S.Context.getCanonicalType(ToType1);
2748 FromType2 = S.Context.getCanonicalType(FromType2);
2749 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002750
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002751 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002752 //
2753 // If class B is derived directly or indirectly from class A and
2754 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002755 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002756 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002757 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002758 SCS2.Second == ICK_Pointer_Conversion &&
2759 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2760 FromType1->isPointerType() && FromType2->isPointerType() &&
2761 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002762 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002763 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002764 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002765 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002766 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002767 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002768 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002769 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002770
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002771 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002772 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002773 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002774 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002775 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002776 return ImplicitConversionSequence::Worse;
2777 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002778
2779 // -- conversion of B* to A* is better than conversion of C* to A*,
2780 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002781 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002782 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002783 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002784 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00002785 }
2786 } else if (SCS1.Second == ICK_Pointer_Conversion &&
2787 SCS2.Second == ICK_Pointer_Conversion) {
2788 const ObjCObjectPointerType *FromPtr1
2789 = FromType1->getAs<ObjCObjectPointerType>();
2790 const ObjCObjectPointerType *FromPtr2
2791 = FromType2->getAs<ObjCObjectPointerType>();
2792 const ObjCObjectPointerType *ToPtr1
2793 = ToType1->getAs<ObjCObjectPointerType>();
2794 const ObjCObjectPointerType *ToPtr2
2795 = ToType2->getAs<ObjCObjectPointerType>();
2796
2797 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
2798 // Apply the same conversion ranking rules for Objective-C pointer types
2799 // that we do for C++ pointers to class types. However, we employ the
2800 // Objective-C pseudo-subtyping relationship used for assignment of
2801 // Objective-C pointer types.
2802 bool FromAssignLeft
2803 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
2804 bool FromAssignRight
2805 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
2806 bool ToAssignLeft
2807 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
2808 bool ToAssignRight
2809 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
2810
2811 // A conversion to an a non-id object pointer type or qualified 'id'
2812 // type is better than a conversion to 'id'.
2813 if (ToPtr1->isObjCIdType() &&
2814 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
2815 return ImplicitConversionSequence::Worse;
2816 if (ToPtr2->isObjCIdType() &&
2817 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
2818 return ImplicitConversionSequence::Better;
2819
2820 // A conversion to a non-id object pointer type is better than a
2821 // conversion to a qualified 'id' type
2822 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
2823 return ImplicitConversionSequence::Worse;
2824 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
2825 return ImplicitConversionSequence::Better;
2826
2827 // A conversion to an a non-Class object pointer type or qualified 'Class'
2828 // type is better than a conversion to 'Class'.
2829 if (ToPtr1->isObjCClassType() &&
2830 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
2831 return ImplicitConversionSequence::Worse;
2832 if (ToPtr2->isObjCClassType() &&
2833 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
2834 return ImplicitConversionSequence::Better;
2835
2836 // A conversion to a non-Class object pointer type is better than a
2837 // conversion to a qualified 'Class' type.
2838 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
2839 return ImplicitConversionSequence::Worse;
2840 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
2841 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00002842
Douglas Gregor058d3de2011-01-31 18:51:41 +00002843 // -- "conversion of C* to B* is better than conversion of C* to A*,"
2844 if (S.Context.hasSameType(FromType1, FromType2) &&
2845 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
2846 (ToAssignLeft != ToAssignRight))
2847 return ToAssignLeft? ImplicitConversionSequence::Worse
2848 : ImplicitConversionSequence::Better;
2849
2850 // -- "conversion of B* to A* is better than conversion of C* to A*,"
2851 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
2852 (FromAssignLeft != FromAssignRight))
2853 return FromAssignLeft? ImplicitConversionSequence::Better
2854 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002855 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002856 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00002857
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002858 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002859 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2860 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2861 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002862 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002863 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002864 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002865 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002866 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002867 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002868 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002869 ToType2->getAs<MemberPointerType>();
2870 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2871 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2872 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2873 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2874 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2875 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2876 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2877 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002878 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002879 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002880 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002881 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002882 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002883 return ImplicitConversionSequence::Better;
2884 }
2885 // conversion of B::* to C::* is better than conversion of A::* to C::*
2886 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002887 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002888 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002889 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002890 return ImplicitConversionSequence::Worse;
2891 }
2892 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002893
Douglas Gregor5ab11652010-04-17 22:01:05 +00002894 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002895 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002896 // -- binding of an expression of type C to a reference of type
2897 // B& is better than binding an expression of type C to a
2898 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002899 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2900 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2901 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002902 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002903 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002904 return ImplicitConversionSequence::Worse;
2905 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002906
Douglas Gregor2fe98832008-11-03 19:09:14 +00002907 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002908 // -- binding of an expression of type B to a reference of type
2909 // A& is better than binding an expression of type C to a
2910 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002911 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2912 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2913 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002914 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002915 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002916 return ImplicitConversionSequence::Worse;
2917 }
2918 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002919
Douglas Gregor5c407d92008-10-23 00:40:37 +00002920 return ImplicitConversionSequence::Indistinguishable;
2921}
2922
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002923/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2924/// determine whether they are reference-related,
2925/// reference-compatible, reference-compatible with added
2926/// qualification, or incompatible, for use in C++ initialization by
2927/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2928/// type, and the first type (T1) is the pointee type of the reference
2929/// type being initialized.
2930Sema::ReferenceCompareResult
2931Sema::CompareReferenceRelationship(SourceLocation Loc,
2932 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002933 bool &DerivedToBase,
2934 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002935 assert(!OrigT1->isReferenceType() &&
2936 "T1 must be the pointee type of the reference type");
2937 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2938
2939 QualType T1 = Context.getCanonicalType(OrigT1);
2940 QualType T2 = Context.getCanonicalType(OrigT2);
2941 Qualifiers T1Quals, T2Quals;
2942 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2943 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2944
2945 // C++ [dcl.init.ref]p4:
2946 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2947 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2948 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002949 DerivedToBase = false;
2950 ObjCConversion = false;
2951 if (UnqualT1 == UnqualT2) {
2952 // Nothing to do.
2953 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002954 IsDerivedFrom(UnqualT2, UnqualT1))
2955 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002956 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2957 UnqualT2->isObjCObjectOrInterfaceType() &&
2958 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2959 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002960 else
2961 return Ref_Incompatible;
2962
2963 // At this point, we know that T1 and T2 are reference-related (at
2964 // least).
2965
2966 // If the type is an array type, promote the element qualifiers to the type
2967 // for comparison.
2968 if (isa<ArrayType>(T1) && T1Quals)
2969 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2970 if (isa<ArrayType>(T2) && T2Quals)
2971 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2972
2973 // C++ [dcl.init.ref]p4:
2974 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2975 // reference-related to T2 and cv1 is the same cv-qualification
2976 // as, or greater cv-qualification than, cv2. For purposes of
2977 // overload resolution, cases for which cv1 is greater
2978 // cv-qualification than cv2 are identified as
2979 // reference-compatible with added qualification (see 13.3.3.2).
2980 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2981 return Ref_Compatible;
2982 else if (T1.isMoreQualifiedThan(T2))
2983 return Ref_Compatible_With_Added_Qualification;
2984 else
2985 return Ref_Related;
2986}
2987
Douglas Gregor836a7e82010-08-11 02:15:33 +00002988/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002989/// with DeclType. Return true if something definite is found.
2990static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002991FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2992 QualType DeclType, SourceLocation DeclLoc,
2993 Expr *Init, QualType T2, bool AllowRvalues,
2994 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002995 assert(T2->isRecordType() && "Can only find conversions of record types.");
2996 CXXRecordDecl *T2RecordDecl
2997 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2998
2999 OverloadCandidateSet CandidateSet(DeclLoc);
3000 const UnresolvedSetImpl *Conversions
3001 = T2RecordDecl->getVisibleConversionFunctions();
3002 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3003 E = Conversions->end(); I != E; ++I) {
3004 NamedDecl *D = *I;
3005 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3006 if (isa<UsingShadowDecl>(D))
3007 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3008
3009 FunctionTemplateDecl *ConvTemplate
3010 = dyn_cast<FunctionTemplateDecl>(D);
3011 CXXConversionDecl *Conv;
3012 if (ConvTemplate)
3013 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3014 else
3015 Conv = cast<CXXConversionDecl>(D);
3016
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003017 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003018 // explicit conversions, skip it.
3019 if (!AllowExplicit && Conv->isExplicit())
3020 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003021
Douglas Gregor836a7e82010-08-11 02:15:33 +00003022 if (AllowRvalues) {
3023 bool DerivedToBase = false;
3024 bool ObjCConversion = false;
3025 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003026 S.CompareReferenceRelationship(
3027 DeclLoc,
3028 Conv->getConversionType().getNonReferenceType()
3029 .getUnqualifiedType(),
3030 DeclType.getNonReferenceType().getUnqualifiedType(),
3031 DerivedToBase, ObjCConversion) ==
3032 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003033 continue;
3034 } else {
3035 // If the conversion function doesn't return a reference type,
3036 // it can't be considered for this conversion. An rvalue reference
3037 // is only acceptable if its referencee is a function type.
3038
3039 const ReferenceType *RefType =
3040 Conv->getConversionType()->getAs<ReferenceType>();
3041 if (!RefType ||
3042 (!RefType->isLValueReferenceType() &&
3043 !RefType->getPointeeType()->isFunctionType()))
3044 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003046
Douglas Gregor836a7e82010-08-11 02:15:33 +00003047 if (ConvTemplate)
3048 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003049 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003050 else
3051 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003052 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003053 }
3054
3055 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003056 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003057 case OR_Success:
3058 // C++ [over.ics.ref]p1:
3059 //
3060 // [...] If the parameter binds directly to the result of
3061 // applying a conversion function to the argument
3062 // expression, the implicit conversion sequence is a
3063 // user-defined conversion sequence (13.3.3.1.2), with the
3064 // second standard conversion sequence either an identity
3065 // conversion or, if the conversion function returns an
3066 // entity of a type that is a derived class of the parameter
3067 // type, a derived-to-base Conversion.
3068 if (!Best->FinalConversion.DirectBinding)
3069 return false;
3070
3071 ICS.setUserDefined();
3072 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3073 ICS.UserDefined.After = Best->FinalConversion;
3074 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003075 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redld92badf2010-06-30 18:13:39 +00003076 ICS.UserDefined.EllipsisConversion = false;
3077 assert(ICS.UserDefined.After.ReferenceBinding &&
3078 ICS.UserDefined.After.DirectBinding &&
3079 "Expected a direct reference binding!");
3080 return true;
3081
3082 case OR_Ambiguous:
3083 ICS.setAmbiguous();
3084 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3085 Cand != CandidateSet.end(); ++Cand)
3086 if (Cand->Viable)
3087 ICS.Ambiguous.addConversion(Cand->Function);
3088 return true;
3089
3090 case OR_No_Viable_Function:
3091 case OR_Deleted:
3092 // There was no suitable conversion, or we found a deleted
3093 // conversion; continue with other checks.
3094 return false;
3095 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003096
Eric Christopheraba9fb22010-06-30 18:36:32 +00003097 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003098}
3099
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003100/// \brief Compute an implicit conversion sequence for reference
3101/// initialization.
3102static ImplicitConversionSequence
3103TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3104 SourceLocation DeclLoc,
3105 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003106 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003107 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3108
3109 // Most paths end in a failed conversion.
3110 ImplicitConversionSequence ICS;
3111 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3112
3113 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3114 QualType T2 = Init->getType();
3115
3116 // If the initializer is the address of an overloaded function, try
3117 // to resolve the overloaded function. If all goes well, T2 is the
3118 // type of the resulting function.
3119 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3120 DeclAccessPair Found;
3121 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3122 false, Found))
3123 T2 = Fn->getType();
3124 }
3125
3126 // Compute some basic properties of the types and the initializer.
3127 bool isRValRef = DeclType->isRValueReferenceType();
3128 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003129 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003130 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003131 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003132 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
3133 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003134
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003135
Sebastian Redld92badf2010-06-30 18:13:39 +00003136 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003137 // A reference to type "cv1 T1" is initialized by an expression
3138 // of type "cv2 T2" as follows:
3139
Sebastian Redld92badf2010-06-30 18:13:39 +00003140 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003141 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003142 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3143 // reference-compatible with "cv2 T2," or
3144 //
3145 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3146 if (InitCategory.isLValue() &&
3147 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003148 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003149 // When a parameter of reference type binds directly (8.5.3)
3150 // to an argument expression, the implicit conversion sequence
3151 // is the identity conversion, unless the argument expression
3152 // has a type that is a derived class of the parameter type,
3153 // in which case the implicit conversion sequence is a
3154 // derived-to-base Conversion (13.3.3.1).
3155 ICS.setStandard();
3156 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003157 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3158 : ObjCConversion? ICK_Compatible_Conversion
3159 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003160 ICS.Standard.Third = ICK_Identity;
3161 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3162 ICS.Standard.setToType(0, T2);
3163 ICS.Standard.setToType(1, T1);
3164 ICS.Standard.setToType(2, T1);
3165 ICS.Standard.ReferenceBinding = true;
3166 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003167 ICS.Standard.IsLvalueReference = !isRValRef;
3168 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3169 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003170 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003171 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003172
Sebastian Redld92badf2010-06-30 18:13:39 +00003173 // Nothing more to do: the inaccessibility/ambiguity check for
3174 // derived-to-base conversions is suppressed when we're
3175 // computing the implicit conversion sequence (C++
3176 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003177 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003178 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003179
Sebastian Redld92badf2010-06-30 18:13:39 +00003180 // -- has a class type (i.e., T2 is a class type), where T1 is
3181 // not reference-related to T2, and can be implicitly
3182 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3183 // is reference-compatible with "cv3 T3" 92) (this
3184 // conversion is selected by enumerating the applicable
3185 // conversion functions (13.3.1.6) and choosing the best
3186 // one through overload resolution (13.3)),
3187 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003188 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003189 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003190 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3191 Init, T2, /*AllowRvalues=*/false,
3192 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003193 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003194 }
3195 }
3196
Sebastian Redld92badf2010-06-30 18:13:39 +00003197 // -- Otherwise, the reference shall be an lvalue reference to a
3198 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003199 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003200 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003201 // We actually handle one oddity of C++ [over.ics.ref] at this
3202 // point, which is that, due to p2 (which short-circuits reference
3203 // binding by only attempting a simple conversion for non-direct
3204 // bindings) and p3's strange wording, we allow a const volatile
3205 // reference to bind to an rvalue. Hence the check for the presence
3206 // of "const" rather than checking for "const" being the only
3207 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003208 // This is also the point where rvalue references and lvalue inits no longer
3209 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003210 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003211 return ICS;
3212
Douglas Gregorf143cd52011-01-24 16:14:37 +00003213 // -- If the initializer expression
3214 //
3215 // -- is an xvalue, class prvalue, array prvalue or function
3216 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3217 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3218 (InitCategory.isXValue() ||
3219 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3220 (InitCategory.isLValue() && T2->isFunctionType()))) {
3221 ICS.setStandard();
3222 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003223 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003224 : ObjCConversion? ICK_Compatible_Conversion
3225 : ICK_Identity;
3226 ICS.Standard.Third = ICK_Identity;
3227 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3228 ICS.Standard.setToType(0, T2);
3229 ICS.Standard.setToType(1, T1);
3230 ICS.Standard.setToType(2, T1);
3231 ICS.Standard.ReferenceBinding = true;
3232 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3233 // binding unless we're binding to a class prvalue.
3234 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3235 // allow the use of rvalue references in C++98/03 for the benefit of
3236 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003237 ICS.Standard.DirectBinding =
3238 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003239 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003240 ICS.Standard.IsLvalueReference = !isRValRef;
3241 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003242 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003243 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003244 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003245 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003246 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003247
Douglas Gregorf143cd52011-01-24 16:14:37 +00003248 // -- has a class type (i.e., T2 is a class type), where T1 is not
3249 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003250 // an xvalue, class prvalue, or function lvalue of type
3251 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003252 // "cv3 T3",
3253 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003254 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003255 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003256 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003257 // class subobject).
3258 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003259 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003260 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3261 Init, T2, /*AllowRvalues=*/true,
3262 AllowExplicit)) {
3263 // In the second case, if the reference is an rvalue reference
3264 // and the second standard conversion sequence of the
3265 // user-defined conversion sequence includes an lvalue-to-rvalue
3266 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003267 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003268 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3269 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3270
Douglas Gregor95273c32011-01-21 16:36:05 +00003271 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003272 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003273
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003274 // -- Otherwise, a temporary of type "cv1 T1" is created and
3275 // initialized from the initializer expression using the
3276 // rules for a non-reference copy initialization (8.5). The
3277 // reference is then bound to the temporary. If T1 is
3278 // reference-related to T2, cv1 must be the same
3279 // cv-qualification as, or greater cv-qualification than,
3280 // cv2; otherwise, the program is ill-formed.
3281 if (RefRelationship == Sema::Ref_Related) {
3282 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3283 // we would be reference-compatible or reference-compatible with
3284 // added qualification. But that wasn't the case, so the reference
3285 // initialization fails.
3286 return ICS;
3287 }
3288
3289 // If at least one of the types is a class type, the types are not
3290 // related, and we aren't allowed any user conversions, the
3291 // reference binding fails. This case is important for breaking
3292 // recursion, since TryImplicitConversion below will attempt to
3293 // create a temporary through the use of a copy constructor.
3294 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3295 (T1->isRecordType() || T2->isRecordType()))
3296 return ICS;
3297
Douglas Gregorcba72b12011-01-21 05:18:22 +00003298 // If T1 is reference-related to T2 and the reference is an rvalue
3299 // reference, the initializer expression shall not be an lvalue.
3300 if (RefRelationship >= Sema::Ref_Related &&
3301 isRValRef && Init->Classify(S.Context).isLValue())
3302 return ICS;
3303
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003304 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003305 // When a parameter of reference type is not bound directly to
3306 // an argument expression, the conversion sequence is the one
3307 // required to convert the argument expression to the
3308 // underlying type of the reference according to
3309 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3310 // to copy-initializing a temporary of the underlying type with
3311 // the argument expression. Any difference in top-level
3312 // cv-qualification is subsumed by the initialization itself
3313 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003314 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3315 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003316 /*InOverloadResolution=*/false,
3317 /*CStyle=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003318
3319 // Of course, that's still a reference binding.
3320 if (ICS.isStandard()) {
3321 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003322 ICS.Standard.IsLvalueReference = !isRValRef;
3323 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3324 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003325 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003326 } else if (ICS.isUserDefined()) {
3327 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003328 ICS.Standard.IsLvalueReference = !isRValRef;
3329 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3330 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003331 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003332 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003333
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003334 return ICS;
3335}
3336
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003337/// TryCopyInitialization - Try to copy-initialize a value of type
3338/// ToType from the expression From. Return the implicit conversion
3339/// sequence required to pass this argument, which may be a bad
3340/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003341/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003342/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003343static ImplicitConversionSequence
3344TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003345 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003346 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003347 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003348 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003349 /*FIXME:*/From->getLocStart(),
3350 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003351 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003352
John McCall5c32be02010-08-24 20:38:10 +00003353 return TryImplicitConversion(S, From, ToType,
3354 SuppressUserConversions,
3355 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003356 InOverloadResolution,
3357 /*CStyle=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003358}
3359
Douglas Gregor436424c2008-11-18 23:14:02 +00003360/// TryObjectArgumentInitialization - Try to initialize the object
3361/// parameter of the given member function (@c Method) from the
3362/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003363static ImplicitConversionSequence
3364TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003365 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003366 CXXMethodDecl *Method,
3367 CXXRecordDecl *ActingContext) {
3368 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003369 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3370 // const volatile object.
3371 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3372 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003373 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003374
3375 // Set up the conversion sequence as a "bad" conversion, to allow us
3376 // to exit early.
3377 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003378
3379 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003380 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003381 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003382 FromType = PT->getPointeeType();
3383
Douglas Gregor02824322011-01-26 19:30:28 +00003384 // When we had a pointer, it's implicitly dereferenced, so we
3385 // better have an lvalue.
3386 assert(FromClassification.isLValue());
3387 }
3388
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003389 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003390
Douglas Gregor02824322011-01-26 19:30:28 +00003391 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003392 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003393 // parameter is
3394 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003395 // - "lvalue reference to cv X" for functions declared without a
3396 // ref-qualifier or with the & ref-qualifier
3397 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003398 // ref-qualifier
3399 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003400 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003401 // cv-qualification on the member function declaration.
3402 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003403 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003404 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003405 // (C++ [over.match.funcs]p5). We perform a simplified version of
3406 // reference binding here, that allows class rvalues to bind to
3407 // non-constant references.
3408
Douglas Gregor02824322011-01-26 19:30:28 +00003409 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003410 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003411 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003412 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003413 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003414 ICS.setBad(BadConversionSequence::bad_qualifiers,
3415 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003416 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003417 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003418
3419 // Check that we have either the same type or a derived type. It
3420 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003421 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003422 ImplicitConversionKind SecondKind;
3423 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3424 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003425 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003426 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003427 else {
John McCall65eb8792010-02-25 01:37:24 +00003428 ICS.setBad(BadConversionSequence::unrelated_class,
3429 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003430 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003431 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003432
Douglas Gregor02824322011-01-26 19:30:28 +00003433 // Check the ref-qualifier.
3434 switch (Method->getRefQualifier()) {
3435 case RQ_None:
3436 // Do nothing; we don't care about lvalueness or rvalueness.
3437 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003438
Douglas Gregor02824322011-01-26 19:30:28 +00003439 case RQ_LValue:
3440 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3441 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003442 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003443 ImplicitParamType);
3444 return ICS;
3445 }
3446 break;
3447
3448 case RQ_RValue:
3449 if (!FromClassification.isRValue()) {
3450 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003451 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003452 ImplicitParamType);
3453 return ICS;
3454 }
3455 break;
3456 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003457
Douglas Gregor436424c2008-11-18 23:14:02 +00003458 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003459 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003460 ICS.Standard.setAsIdentityConversion();
3461 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003462 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003463 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003464 ICS.Standard.ReferenceBinding = true;
3465 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003466 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003467 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003468 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3469 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3470 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003471 return ICS;
3472}
3473
3474/// PerformObjectArgumentInitialization - Perform initialization of
3475/// the implicit object parameter for the given Method with the given
3476/// expression.
3477bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003478Sema::PerformObjectArgumentInitialization(Expr *&From,
3479 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003480 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003481 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003482 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003483 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003484 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003485
Douglas Gregor02824322011-01-26 19:30:28 +00003486 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003487 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003488 FromRecordType = PT->getPointeeType();
3489 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003490 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003491 } else {
3492 FromRecordType = From->getType();
3493 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003494 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003495 }
3496
John McCall6e9f8f62009-12-03 04:06:58 +00003497 // Note that we always use the true parent context when performing
3498 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003499 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003500 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3501 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003502 if (ICS.isBad()) {
3503 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3504 Qualifiers FromQs = FromRecordType.getQualifiers();
3505 Qualifiers ToQs = DestType.getQualifiers();
3506 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3507 if (CVR) {
3508 Diag(From->getSourceRange().getBegin(),
3509 diag::err_member_function_call_bad_cvr)
3510 << Method->getDeclName() << FromRecordType << (CVR - 1)
3511 << From->getSourceRange();
3512 Diag(Method->getLocation(), diag::note_previous_decl)
3513 << Method->getDeclName();
3514 return true;
3515 }
3516 }
3517
Douglas Gregor436424c2008-11-18 23:14:02 +00003518 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003519 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003520 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003521 }
Mike Stump11289f42009-09-09 15:08:12 +00003522
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003523 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003524 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003525
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003526 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003527 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003528 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003529 return false;
3530}
3531
Douglas Gregor5fb53972009-01-14 15:45:31 +00003532/// TryContextuallyConvertToBool - Attempt to contextually convert the
3533/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003534static ImplicitConversionSequence
3535TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003536 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003537 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003538 // FIXME: Are these flags correct?
3539 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003540 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003541 /*InOverloadResolution=*/false,
3542 /*CStyle=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003543}
3544
3545/// PerformContextuallyConvertToBool - Perform a contextual conversion
3546/// of the expression From to bool (C++0x [conv]p3).
3547bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003548 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003549 if (!ICS.isBad())
3550 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003551
Fariborz Jahanian76197412009-11-18 18:26:29 +00003552 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003553 return Diag(From->getSourceRange().getBegin(),
3554 diag::err_typecheck_bool_condition)
3555 << From->getType() << From->getSourceRange();
3556 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003557}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003558
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003559/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3560/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003561static ImplicitConversionSequence
3562TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3563 QualType Ty = S.Context.getObjCIdType();
3564 return TryImplicitConversion(S, From, Ty,
3565 // FIXME: Are these flags correct?
3566 /*SuppressUserConversions=*/false,
3567 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003568 /*InOverloadResolution=*/false,
3569 /*CStyle=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003570}
John McCall5c32be02010-08-24 20:38:10 +00003571
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003572/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3573/// of the expression From to 'id'.
3574bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003575 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003576 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003577 if (!ICS.isBad())
3578 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3579 return true;
3580}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003581
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003582/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003583/// enumeration type.
3584///
3585/// This routine will attempt to convert an expression of class type to an
3586/// integral or enumeration type, if that class type only has a single
3587/// conversion to an integral or enumeration type.
3588///
Douglas Gregor4799d032010-06-30 00:20:43 +00003589/// \param Loc The source location of the construct that requires the
3590/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003591///
Douglas Gregor4799d032010-06-30 00:20:43 +00003592/// \param FromE The expression we're converting from.
3593///
3594/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3595/// have integral or enumeration type.
3596///
3597/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3598/// incomplete class type.
3599///
3600/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3601/// explicit conversion function (because no implicit conversion functions
3602/// were available). This is a recovery mode.
3603///
3604/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3605/// showing which conversion was picked.
3606///
3607/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3608/// conversion function that could convert to integral or enumeration type.
3609///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003610/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00003611/// usable conversion function.
3612///
3613/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3614/// function, which may be an extension in this case.
3615///
3616/// \returns The expression, converted to an integral or enumeration type if
3617/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003618ExprResult
John McCallb268a282010-08-23 23:25:46 +00003619Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003620 const PartialDiagnostic &NotIntDiag,
3621 const PartialDiagnostic &IncompleteDiag,
3622 const PartialDiagnostic &ExplicitConvDiag,
3623 const PartialDiagnostic &ExplicitConvNote,
3624 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003625 const PartialDiagnostic &AmbigNote,
3626 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003627 // We can't perform any more checking for type-dependent expressions.
3628 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003629 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003630
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003631 // If the expression already has integral or enumeration type, we're golden.
3632 QualType T = From->getType();
3633 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003634 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003635
3636 // FIXME: Check for missing '()' if T is a function type?
3637
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003638 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003639 // expression of integral or enumeration type.
3640 const RecordType *RecordTy = T->getAs<RecordType>();
3641 if (!RecordTy || !getLangOptions().CPlusPlus) {
3642 Diag(Loc, NotIntDiag)
3643 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003644 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003645 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003646
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003647 // We must have a complete class type.
3648 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003649 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003650
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003651 // Look for a conversion to an integral or enumeration type.
3652 UnresolvedSet<4> ViableConversions;
3653 UnresolvedSet<4> ExplicitConversions;
3654 const UnresolvedSetImpl *Conversions
3655 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003656
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003657 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003658 E = Conversions->end();
3659 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003660 ++I) {
3661 if (CXXConversionDecl *Conversion
3662 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3663 if (Conversion->getConversionType().getNonReferenceType()
3664 ->isIntegralOrEnumerationType()) {
3665 if (Conversion->isExplicit())
3666 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3667 else
3668 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3669 }
3670 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003672 switch (ViableConversions.size()) {
3673 case 0:
3674 if (ExplicitConversions.size() == 1) {
3675 DeclAccessPair Found = ExplicitConversions[0];
3676 CXXConversionDecl *Conversion
3677 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003678
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003679 // The user probably meant to invoke the given explicit
3680 // conversion; use it.
3681 QualType ConvTy
3682 = Conversion->getConversionType().getNonReferenceType();
3683 std::string TypeStr;
3684 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003685
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003686 Diag(Loc, ExplicitConvDiag)
3687 << T << ConvTy
3688 << FixItHint::CreateInsertion(From->getLocStart(),
3689 "static_cast<" + TypeStr + ">(")
3690 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3691 ")");
3692 Diag(Conversion->getLocation(), ExplicitConvNote)
3693 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003694
3695 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003696 // explicit conversion function.
3697 if (isSFINAEContext())
3698 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003699
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003700 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00003701 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3702 if (Result.isInvalid())
3703 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003704
Douglas Gregor668443e2011-01-20 00:18:04 +00003705 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003706 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003707
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003708 // We'll complain below about a non-integral condition type.
3709 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003710
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003711 case 1: {
3712 // Apply this conversion.
3713 DeclAccessPair Found = ViableConversions[0];
3714 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003715
Douglas Gregor4799d032010-06-30 00:20:43 +00003716 CXXConversionDecl *Conversion
3717 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3718 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003719 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00003720 if (ConvDiag.getDiagID()) {
3721 if (isSFINAEContext())
3722 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003723
Douglas Gregor4799d032010-06-30 00:20:43 +00003724 Diag(Loc, ConvDiag)
3725 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3726 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003727
Douglas Gregor668443e2011-01-20 00:18:04 +00003728 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003729 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00003730 if (Result.isInvalid())
3731 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003732
Douglas Gregor668443e2011-01-20 00:18:04 +00003733 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003734 break;
3735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003736
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003737 default:
3738 Diag(Loc, AmbigDiag)
3739 << T << From->getSourceRange();
3740 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3741 CXXConversionDecl *Conv
3742 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3743 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3744 Diag(Conv->getLocation(), AmbigNote)
3745 << ConvTy->isEnumeralType() << ConvTy;
3746 }
John McCallb268a282010-08-23 23:25:46 +00003747 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003748 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749
Douglas Gregor5823da32010-06-29 23:25:20 +00003750 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003751 Diag(Loc, NotIntDiag)
3752 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003753
John McCallb268a282010-08-23 23:25:46 +00003754 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003755}
3756
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003757/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003758/// candidate functions, using the given function call arguments. If
3759/// @p SuppressUserConversions, then don't allow user-defined
3760/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003761///
3762/// \para PartialOverloading true if we are performing "partial" overloading
3763/// based on an incomplete set of function arguments. This feature is used by
3764/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003765void
3766Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003767 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003768 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003769 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003770 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003771 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003772 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003773 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003774 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003775 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003776 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003777
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003778 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003779 if (!isa<CXXConstructorDecl>(Method)) {
3780 // If we get here, it's because we're calling a member function
3781 // that is named without a member access expression (e.g.,
3782 // "this->f") that was either written explicitly or created
3783 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003784 // function, e.g., X::f(). We use an empty type for the implied
3785 // object argument (C++ [over.call.func]p3), and the acting context
3786 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003787 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003788 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00003789 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003790 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003791 return;
3792 }
3793 // We treat a constructor like a non-member function, since its object
3794 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003795 }
3796
Douglas Gregorff7028a2009-11-13 23:59:09 +00003797 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003798 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003799
Douglas Gregor27381f32009-11-23 12:27:39 +00003800 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003801 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003802
Douglas Gregorffe14e32009-11-14 01:20:54 +00003803 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3804 // C++ [class.copy]p3:
3805 // A member function template is never instantiated to perform the copy
3806 // of a class object to an object of its class type.
3807 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003808 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003809 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003810 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3811 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003812 return;
3813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003814
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003815 // Add this candidate
3816 CandidateSet.push_back(OverloadCandidate());
3817 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003818 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003819 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003820 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003821 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003822 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003823 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003824
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003825 unsigned NumArgsInProto = Proto->getNumArgs();
3826
3827 // (C++ 13.3.2p2): A candidate function having fewer than m
3828 // parameters is viable only if it has an ellipsis in its parameter
3829 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003830 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00003831 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003832 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003833 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003834 return;
3835 }
3836
3837 // (C++ 13.3.2p2): A candidate function having more than m parameters
3838 // is viable only if the (m+1)st parameter has a default argument
3839 // (8.3.6). For the purposes of overload resolution, the
3840 // parameter list is truncated on the right, so that there are
3841 // exactly m parameters.
3842 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003843 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003844 // Not enough arguments.
3845 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003846 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003847 return;
3848 }
3849
3850 // Determine the implicit conversion sequences for each of the
3851 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003852 Candidate.Conversions.resize(NumArgs);
3853 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3854 if (ArgIdx < NumArgsInProto) {
3855 // (C++ 13.3.2p3): for F to be a viable function, there shall
3856 // exist for each argument an implicit conversion sequence
3857 // (13.3.3.1) that converts that argument to the corresponding
3858 // parameter of F.
3859 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003860 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003861 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003862 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003863 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003864 if (Candidate.Conversions[ArgIdx].isBad()) {
3865 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003866 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003867 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003868 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003869 } else {
3870 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3871 // argument for which there is no corresponding parameter is
3872 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003873 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003874 }
3875 }
3876}
3877
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003878/// \brief Add all of the function declarations in the given function set to
3879/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003880void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003881 Expr **Args, unsigned NumArgs,
3882 OverloadCandidateSet& CandidateSet,
3883 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003884 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003885 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3886 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003887 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003888 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003889 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00003890 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003891 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003892 CandidateSet, SuppressUserConversions);
3893 else
John McCalla0296f72010-03-19 07:35:19 +00003894 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003895 SuppressUserConversions);
3896 } else {
John McCalla0296f72010-03-19 07:35:19 +00003897 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003898 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3899 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003900 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003901 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003902 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003903 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00003904 Args[0]->Classify(Context),
3905 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003906 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003907 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003908 else
John McCalla0296f72010-03-19 07:35:19 +00003909 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003910 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003911 Args, NumArgs, CandidateSet,
3912 SuppressUserConversions);
3913 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003914 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003915}
3916
John McCallf0f1cf02009-11-17 07:50:12 +00003917/// AddMethodCandidate - Adds a named decl (which is some kind of
3918/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003919void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003920 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00003921 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00003922 Expr **Args, unsigned NumArgs,
3923 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003924 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003925 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003926 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003927
3928 if (isa<UsingShadowDecl>(Decl))
3929 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003930
John McCallf0f1cf02009-11-17 07:50:12 +00003931 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3932 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3933 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003934 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3935 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00003936 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003937 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003938 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003939 } else {
John McCalla0296f72010-03-19 07:35:19 +00003940 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00003941 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003942 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003943 }
3944}
3945
Douglas Gregor436424c2008-11-18 23:14:02 +00003946/// AddMethodCandidate - Adds the given C++ member function to the set
3947/// of candidate functions, using the given function call arguments
3948/// and the object argument (@c Object). For example, in a call
3949/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3950/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3951/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003952/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003953void
John McCalla0296f72010-03-19 07:35:19 +00003954Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003955 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00003956 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00003957 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003958 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003959 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003960 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003961 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003962 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003963 assert(!isa<CXXConstructorDecl>(Method) &&
3964 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003965
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003966 if (!CandidateSet.isNewCandidate(Method))
3967 return;
3968
Douglas Gregor27381f32009-11-23 12:27:39 +00003969 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003970 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003971
Douglas Gregor436424c2008-11-18 23:14:02 +00003972 // Add this candidate
3973 CandidateSet.push_back(OverloadCandidate());
3974 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003975 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003976 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003977 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003978 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003979 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00003980
3981 unsigned NumArgsInProto = Proto->getNumArgs();
3982
3983 // (C++ 13.3.2p2): A candidate function having fewer than m
3984 // parameters is viable only if it has an ellipsis in its parameter
3985 // list (8.3.5).
3986 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3987 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003988 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003989 return;
3990 }
3991
3992 // (C++ 13.3.2p2): A candidate function having more than m parameters
3993 // is viable only if the (m+1)st parameter has a default argument
3994 // (8.3.6). For the purposes of overload resolution, the
3995 // parameter list is truncated on the right, so that there are
3996 // exactly m parameters.
3997 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3998 if (NumArgs < MinRequiredArgs) {
3999 // Not enough arguments.
4000 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004001 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004002 return;
4003 }
4004
4005 Candidate.Viable = true;
4006 Candidate.Conversions.resize(NumArgs + 1);
4007
John McCall6e9f8f62009-12-03 04:06:58 +00004008 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004009 // The implicit object argument is ignored.
4010 Candidate.IgnoreObjectArgument = true;
4011 else {
4012 // Determine the implicit conversion sequence for the object
4013 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004014 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004015 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4016 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004017 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004018 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004019 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004020 return;
4021 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004022 }
4023
4024 // Determine the implicit conversion sequences for each of the
4025 // arguments.
4026 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4027 if (ArgIdx < NumArgsInProto) {
4028 // (C++ 13.3.2p3): for F to be a viable function, there shall
4029 // exist for each argument an implicit conversion sequence
4030 // (13.3.3.1) that converts that argument to the corresponding
4031 // parameter of F.
4032 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004033 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004034 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004035 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00004036 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00004037 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004038 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004039 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004040 break;
4041 }
4042 } else {
4043 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4044 // argument for which there is no corresponding parameter is
4045 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004046 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004047 }
4048 }
4049}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004050
Douglas Gregor97628d62009-08-21 00:16:32 +00004051/// \brief Add a C++ member function template as a candidate to the candidate
4052/// set, using template argument deduction to produce an appropriate member
4053/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004054void
Douglas Gregor97628d62009-08-21 00:16:32 +00004055Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004056 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004057 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00004058 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004059 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004060 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004061 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004062 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004063 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004064 if (!CandidateSet.isNewCandidate(MethodTmpl))
4065 return;
4066
Douglas Gregor97628d62009-08-21 00:16:32 +00004067 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004068 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004069 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004070 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004071 // candidate functions in the usual way.113) A given name can refer to one
4072 // or more function templates and also to a set of overloaded non-template
4073 // functions. In such a case, the candidate functions generated from each
4074 // function template are combined with the set of non-template candidate
4075 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004076 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004077 FunctionDecl *Specialization = 0;
4078 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004079 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004080 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004081 CandidateSet.push_back(OverloadCandidate());
4082 OverloadCandidate &Candidate = CandidateSet.back();
4083 Candidate.FoundDecl = FoundDecl;
4084 Candidate.Function = MethodTmpl->getTemplatedDecl();
4085 Candidate.Viable = false;
4086 Candidate.FailureKind = ovl_fail_bad_deduction;
4087 Candidate.IsSurrogate = false;
4088 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004089 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004090 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004091 Info);
4092 return;
4093 }
Mike Stump11289f42009-09-09 15:08:12 +00004094
Douglas Gregor97628d62009-08-21 00:16:32 +00004095 // Add the function template specialization produced by template argument
4096 // deduction as a candidate.
4097 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004098 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004099 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004100 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004101 ActingContext, ObjectType, ObjectClassification,
4102 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004103}
4104
Douglas Gregor05155d82009-08-21 23:19:43 +00004105/// \brief Add a C++ function template specialization as a candidate
4106/// in the candidate set, using template argument deduction to produce
4107/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004108void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004109Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004110 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00004111 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004112 Expr **Args, unsigned NumArgs,
4113 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004114 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004115 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4116 return;
4117
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004118 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004119 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004120 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004121 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004122 // candidate functions in the usual way.113) A given name can refer to one
4123 // or more function templates and also to a set of overloaded non-template
4124 // functions. In such a case, the candidate functions generated from each
4125 // function template are combined with the set of non-template candidate
4126 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004127 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004128 FunctionDecl *Specialization = 0;
4129 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004130 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004131 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004132 CandidateSet.push_back(OverloadCandidate());
4133 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004134 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004135 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4136 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004137 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004138 Candidate.IsSurrogate = false;
4139 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004140 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004141 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004142 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004143 return;
4144 }
Mike Stump11289f42009-09-09 15:08:12 +00004145
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004146 // Add the function template specialization produced by template argument
4147 // deduction as a candidate.
4148 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004149 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004150 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004151}
Mike Stump11289f42009-09-09 15:08:12 +00004152
Douglas Gregora1f013e2008-11-07 22:36:19 +00004153/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004154/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004155/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004156/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004157/// (which may or may not be the same type as the type that the
4158/// conversion function produces).
4159void
4160Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004161 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004162 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004163 Expr *From, QualType ToType,
4164 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004165 assert(!Conversion->getDescribedFunctionTemplate() &&
4166 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004167 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004168 if (!CandidateSet.isNewCandidate(Conversion))
4169 return;
4170
Douglas Gregor27381f32009-11-23 12:27:39 +00004171 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004172 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004173
Douglas Gregora1f013e2008-11-07 22:36:19 +00004174 // Add this candidate
4175 CandidateSet.push_back(OverloadCandidate());
4176 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004177 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004178 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004179 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004180 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004181 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004182 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004183 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004184 Candidate.Viable = true;
4185 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004186 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004187
Douglas Gregor6affc782010-08-19 15:37:02 +00004188 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004189 // For conversion functions, the function is considered to be a member of
4190 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004191 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004192 //
4193 // Determine the implicit conversion sequence for the implicit
4194 // object parameter.
4195 QualType ImplicitParamType = From->getType();
4196 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4197 ImplicitParamType = FromPtrType->getPointeeType();
4198 CXXRecordDecl *ConversionContext
4199 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004200
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004201 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004202 = TryObjectArgumentInitialization(*this, From->getType(),
4203 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004204 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004205
John McCall0d1da222010-01-12 00:44:57 +00004206 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004207 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004208 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004209 return;
4210 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004211
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004212 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004213 // derived to base as such conversions are given Conversion Rank. They only
4214 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4215 QualType FromCanon
4216 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4217 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4218 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4219 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004220 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004221 return;
4222 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004223
Douglas Gregora1f013e2008-11-07 22:36:19 +00004224 // To determine what the conversion from the result of calling the
4225 // conversion function to the type we're eventually trying to
4226 // convert to (ToType), we need to synthesize a call to the
4227 // conversion function and attempt copy initialization from it. This
4228 // makes sure that we get the right semantics with respect to
4229 // lvalues/rvalues and the type. Fortunately, we can allocate this
4230 // call on the stack and we don't need its arguments to be
4231 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004232 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004233 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004234 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4235 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004236 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004237 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004238
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004239 QualType CallResultType
4240 = Conversion->getConversionType().getNonLValueExprType(Context);
4241 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4242 Candidate.Viable = false;
4243 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4244 return;
4245 }
4246
John McCall7decc9e2010-11-18 06:31:45 +00004247 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4248
Mike Stump11289f42009-09-09 15:08:12 +00004249 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004250 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4251 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00004252 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004253 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004254 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004255 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004256 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00004257 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004258
John McCall0d1da222010-01-12 00:44:57 +00004259 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004260 case ImplicitConversionSequence::StandardConversion:
4261 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004262
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004263 // C++ [over.ics.user]p3:
4264 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004265 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004266 // shall have exact match rank.
4267 if (Conversion->getPrimaryTemplate() &&
4268 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4269 Candidate.Viable = false;
4270 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4271 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004272
Douglas Gregorcba72b12011-01-21 05:18:22 +00004273 // C++0x [dcl.init.ref]p5:
4274 // In the second case, if the reference is an rvalue reference and
4275 // the second standard conversion sequence of the user-defined
4276 // conversion sequence includes an lvalue-to-rvalue conversion, the
4277 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004279 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4280 Candidate.Viable = false;
4281 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4282 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004283 break;
4284
4285 case ImplicitConversionSequence::BadConversion:
4286 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004287 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004288 break;
4289
4290 default:
Mike Stump11289f42009-09-09 15:08:12 +00004291 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004292 "Can only end up with a standard conversion sequence or failure");
4293 }
4294}
4295
Douglas Gregor05155d82009-08-21 23:19:43 +00004296/// \brief Adds a conversion function template specialization
4297/// candidate to the overload set, using template argument deduction
4298/// to deduce the template arguments of the conversion function
4299/// template from the type that we are converting to (C++
4300/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004301void
Douglas Gregor05155d82009-08-21 23:19:43 +00004302Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004303 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004304 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004305 Expr *From, QualType ToType,
4306 OverloadCandidateSet &CandidateSet) {
4307 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4308 "Only conversion function templates permitted here");
4309
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004310 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4311 return;
4312
John McCallbc077cf2010-02-08 23:07:23 +00004313 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004314 CXXConversionDecl *Specialization = 0;
4315 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004316 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004317 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004318 CandidateSet.push_back(OverloadCandidate());
4319 OverloadCandidate &Candidate = CandidateSet.back();
4320 Candidate.FoundDecl = FoundDecl;
4321 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4322 Candidate.Viable = false;
4323 Candidate.FailureKind = ovl_fail_bad_deduction;
4324 Candidate.IsSurrogate = false;
4325 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004326 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004327 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004328 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004329 return;
4330 }
Mike Stump11289f42009-09-09 15:08:12 +00004331
Douglas Gregor05155d82009-08-21 23:19:43 +00004332 // Add the conversion function template specialization produced by
4333 // template argument deduction as a candidate.
4334 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004335 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004336 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004337}
4338
Douglas Gregorab7897a2008-11-19 22:57:39 +00004339/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4340/// converts the given @c Object to a function pointer via the
4341/// conversion function @c Conversion, and then attempts to call it
4342/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4343/// the type of function that we'll eventually be calling.
4344void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004345 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004346 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004347 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004348 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004349 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004350 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004351 if (!CandidateSet.isNewCandidate(Conversion))
4352 return;
4353
Douglas Gregor27381f32009-11-23 12:27:39 +00004354 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004355 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004356
Douglas Gregorab7897a2008-11-19 22:57:39 +00004357 CandidateSet.push_back(OverloadCandidate());
4358 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004359 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004360 Candidate.Function = 0;
4361 Candidate.Surrogate = Conversion;
4362 Candidate.Viable = true;
4363 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004364 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004365 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004366 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004367
4368 // Determine the implicit conversion sequence for the implicit
4369 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004370 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004371 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004372 Object->Classify(Context),
4373 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004374 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004375 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004376 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004377 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004378 return;
4379 }
4380
4381 // The first conversion is actually a user-defined conversion whose
4382 // first conversion is ObjectInit's standard conversion (which is
4383 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004384 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004385 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004386 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004387 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004388 Candidate.Conversions[0].UserDefined.FoundConversionFunction
Douglas Gregor2bbfba02011-01-20 01:32:05 +00004389 = FoundDecl.getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004390 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004391 = Candidate.Conversions[0].UserDefined.Before;
4392 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4393
Mike Stump11289f42009-09-09 15:08:12 +00004394 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004395 unsigned NumArgsInProto = Proto->getNumArgs();
4396
4397 // (C++ 13.3.2p2): A candidate function having fewer than m
4398 // parameters is viable only if it has an ellipsis in its parameter
4399 // list (8.3.5).
4400 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4401 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004402 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004403 return;
4404 }
4405
4406 // Function types don't have any default arguments, so just check if
4407 // we have enough arguments.
4408 if (NumArgs < NumArgsInProto) {
4409 // Not enough arguments.
4410 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004411 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004412 return;
4413 }
4414
4415 // Determine the implicit conversion sequences for each of the
4416 // arguments.
4417 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4418 if (ArgIdx < NumArgsInProto) {
4419 // (C++ 13.3.2p3): for F to be a viable function, there shall
4420 // exist for each argument an implicit conversion sequence
4421 // (13.3.3.1) that converts that argument to the corresponding
4422 // parameter of F.
4423 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004424 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004425 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004426 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004427 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004428 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004429 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004430 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004431 break;
4432 }
4433 } else {
4434 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4435 // argument for which there is no corresponding parameter is
4436 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004437 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004438 }
4439 }
4440}
4441
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004442/// \brief Add overload candidates for overloaded operators that are
4443/// member functions.
4444///
4445/// Add the overloaded operator candidates that are member functions
4446/// for the operator Op that was used in an operator expression such
4447/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4448/// CandidateSet will store the added overload candidates. (C++
4449/// [over.match.oper]).
4450void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4451 SourceLocation OpLoc,
4452 Expr **Args, unsigned NumArgs,
4453 OverloadCandidateSet& CandidateSet,
4454 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004455 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4456
4457 // C++ [over.match.oper]p3:
4458 // For a unary operator @ with an operand of a type whose
4459 // cv-unqualified version is T1, and for a binary operator @ with
4460 // a left operand of a type whose cv-unqualified version is T1 and
4461 // a right operand of a type whose cv-unqualified version is T2,
4462 // three sets of candidate functions, designated member
4463 // candidates, non-member candidates and built-in candidates, are
4464 // constructed as follows:
4465 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004466
4467 // -- If T1 is a class type, the set of member candidates is the
4468 // result of the qualified lookup of T1::operator@
4469 // (13.3.1.1.1); otherwise, the set of member candidates is
4470 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004471 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004472 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004473 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004474 return;
Mike Stump11289f42009-09-09 15:08:12 +00004475
John McCall27b18f82009-11-17 02:14:36 +00004476 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4477 LookupQualifiedName(Operators, T1Rec->getDecl());
4478 Operators.suppressDiagnostics();
4479
Mike Stump11289f42009-09-09 15:08:12 +00004480 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004481 OperEnd = Operators.end();
4482 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004483 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004484 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004485 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00004486 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004487 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004488 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004489}
4490
Douglas Gregora11693b2008-11-12 17:17:38 +00004491/// AddBuiltinCandidate - Add a candidate for a built-in
4492/// operator. ResultTy and ParamTys are the result and parameter types
4493/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004494/// arguments being passed to the candidate. IsAssignmentOperator
4495/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004496/// operator. NumContextualBoolArguments is the number of arguments
4497/// (at the beginning of the argument list) that will be contextually
4498/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004499void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004500 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004501 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004502 bool IsAssignmentOperator,
4503 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004504 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004505 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004506
Douglas Gregora11693b2008-11-12 17:17:38 +00004507 // Add this candidate
4508 CandidateSet.push_back(OverloadCandidate());
4509 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004510 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004511 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004512 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004513 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004514 Candidate.BuiltinTypes.ResultTy = ResultTy;
4515 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4516 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4517
4518 // Determine the implicit conversion sequences for each of the
4519 // arguments.
4520 Candidate.Viable = true;
4521 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004522 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004523 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004524 // C++ [over.match.oper]p4:
4525 // For the built-in assignment operators, conversions of the
4526 // left operand are restricted as follows:
4527 // -- no temporaries are introduced to hold the left operand, and
4528 // -- no user-defined conversions are applied to the left
4529 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004530 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004531 //
4532 // We block these conversions by turning off user-defined
4533 // conversions, since that is the only way that initialization of
4534 // a reference to a non-class type can occur from something that
4535 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004536 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004537 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004538 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004539 Candidate.Conversions[ArgIdx]
4540 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004541 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004542 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004543 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004544 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004545 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004546 }
John McCall0d1da222010-01-12 00:44:57 +00004547 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004548 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004549 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004550 break;
4551 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004552 }
4553}
4554
4555/// BuiltinCandidateTypeSet - A set of types that will be used for the
4556/// candidate operator functions for built-in operators (C++
4557/// [over.built]). The types are separated into pointer types and
4558/// enumeration types.
4559class BuiltinCandidateTypeSet {
4560 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004561 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004562
4563 /// PointerTypes - The set of pointer types that will be used in the
4564 /// built-in candidates.
4565 TypeSet PointerTypes;
4566
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004567 /// MemberPointerTypes - The set of member pointer types that will be
4568 /// used in the built-in candidates.
4569 TypeSet MemberPointerTypes;
4570
Douglas Gregora11693b2008-11-12 17:17:38 +00004571 /// EnumerationTypes - The set of enumeration types that will be
4572 /// used in the built-in candidates.
4573 TypeSet EnumerationTypes;
4574
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004575 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004576 /// candidates.
4577 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004578
4579 /// \brief A flag indicating non-record types are viable candidates
4580 bool HasNonRecordTypes;
4581
4582 /// \brief A flag indicating whether either arithmetic or enumeration types
4583 /// were present in the candidate set.
4584 bool HasArithmeticOrEnumeralTypes;
4585
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004586 /// Sema - The semantic analysis instance where we are building the
4587 /// candidate type set.
4588 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004589
Douglas Gregora11693b2008-11-12 17:17:38 +00004590 /// Context - The AST context in which we will build the type sets.
4591 ASTContext &Context;
4592
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004593 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4594 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004595 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004596
4597public:
4598 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004599 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004600
Mike Stump11289f42009-09-09 15:08:12 +00004601 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004602 : HasNonRecordTypes(false),
4603 HasArithmeticOrEnumeralTypes(false),
4604 SemaRef(SemaRef),
4605 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004606
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004607 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004608 SourceLocation Loc,
4609 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004610 bool AllowExplicitConversions,
4611 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004612
4613 /// pointer_begin - First pointer type found;
4614 iterator pointer_begin() { return PointerTypes.begin(); }
4615
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004616 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004617 iterator pointer_end() { return PointerTypes.end(); }
4618
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004619 /// member_pointer_begin - First member pointer type found;
4620 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4621
4622 /// member_pointer_end - Past the last member pointer type found;
4623 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4624
Douglas Gregora11693b2008-11-12 17:17:38 +00004625 /// enumeration_begin - First enumeration type found;
4626 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4627
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004628 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004629 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004630
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004631 iterator vector_begin() { return VectorTypes.begin(); }
4632 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00004633
4634 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4635 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregora11693b2008-11-12 17:17:38 +00004636};
4637
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004638/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004639/// the set of pointer types along with any more-qualified variants of
4640/// that type. For example, if @p Ty is "int const *", this routine
4641/// will add "int const *", "int const volatile *", "int const
4642/// restrict *", and "int const volatile restrict *" to the set of
4643/// pointer types. Returns true if the add of @p Ty itself succeeded,
4644/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004645///
4646/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004647bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004648BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4649 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004650
Douglas Gregora11693b2008-11-12 17:17:38 +00004651 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004652 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004653 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004654
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004655 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004656 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004657 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004658 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004659 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004660 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004661 buildObjCPtr = true;
4662 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004663 else
4664 assert(false && "type was not a pointer type!");
4665 }
4666 else
4667 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004668
Sebastian Redl4990a632009-11-18 20:39:26 +00004669 // Don't add qualified variants of arrays. For one, they're not allowed
4670 // (the qualifier would sink to the element type), and for another, the
4671 // only overload situation where it matters is subscript or pointer +- int,
4672 // and those shouldn't have qualifier variants anyway.
4673 if (PointeeTy->isArrayType())
4674 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004675 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004676 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004677 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004678 bool hasVolatile = VisibleQuals.hasVolatile();
4679 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004680
John McCall8ccfcb52009-09-24 19:53:00 +00004681 // Iterate through all strict supersets of BaseCVR.
4682 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4683 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004684 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4685 // in the types.
4686 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4687 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004688 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004689 if (!buildObjCPtr)
4690 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4691 else
4692 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004693 }
4694
4695 return true;
4696}
4697
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004698/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4699/// to the set of pointer types along with any more-qualified variants of
4700/// that type. For example, if @p Ty is "int const *", this routine
4701/// will add "int const *", "int const volatile *", "int const
4702/// restrict *", and "int const volatile restrict *" to the set of
4703/// pointer types. Returns true if the add of @p Ty itself succeeded,
4704/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004705///
4706/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004707bool
4708BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4709 QualType Ty) {
4710 // Insert this type.
4711 if (!MemberPointerTypes.insert(Ty))
4712 return false;
4713
John McCall8ccfcb52009-09-24 19:53:00 +00004714 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4715 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004716
John McCall8ccfcb52009-09-24 19:53:00 +00004717 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004718 // Don't add qualified variants of arrays. For one, they're not allowed
4719 // (the qualifier would sink to the element type), and for another, the
4720 // only overload situation where it matters is subscript or pointer +- int,
4721 // and those shouldn't have qualifier variants anyway.
4722 if (PointeeTy->isArrayType())
4723 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004724 const Type *ClassTy = PointerTy->getClass();
4725
4726 // Iterate through all strict supersets of the pointee type's CVR
4727 // qualifiers.
4728 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4729 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4730 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004731
John McCall8ccfcb52009-09-24 19:53:00 +00004732 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00004733 MemberPointerTypes.insert(
4734 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004735 }
4736
4737 return true;
4738}
4739
Douglas Gregora11693b2008-11-12 17:17:38 +00004740/// AddTypesConvertedFrom - Add each of the types to which the type @p
4741/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004742/// primarily interested in pointer types and enumeration types. We also
4743/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004744/// AllowUserConversions is true if we should look at the conversion
4745/// functions of a class type, and AllowExplicitConversions if we
4746/// should also include the explicit conversion functions of a class
4747/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004748void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004749BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004750 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004751 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004752 bool AllowExplicitConversions,
4753 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004754 // Only deal with canonical types.
4755 Ty = Context.getCanonicalType(Ty);
4756
4757 // Look through reference types; they aren't part of the type of an
4758 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004759 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004760 Ty = RefTy->getPointeeType();
4761
John McCall33ddac02011-01-19 10:06:00 +00004762 // If we're dealing with an array type, decay to the pointer.
4763 if (Ty->isArrayType())
4764 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4765
4766 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004767 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004768
Chandler Carruth00a38332010-12-13 01:44:01 +00004769 // Flag if we ever add a non-record type.
4770 const RecordType *TyRec = Ty->getAs<RecordType>();
4771 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4772
Chandler Carruth00a38332010-12-13 01:44:01 +00004773 // Flag if we encounter an arithmetic type.
4774 HasArithmeticOrEnumeralTypes =
4775 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4776
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004777 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4778 PointerTypes.insert(Ty);
4779 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004780 // Insert our type, and its more-qualified variants, into the set
4781 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004782 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004783 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004784 } else if (Ty->isMemberPointerType()) {
4785 // Member pointers are far easier, since the pointee can't be converted.
4786 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4787 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004788 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004789 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00004790 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004791 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004792 // We treat vector types as arithmetic types in many contexts as an
4793 // extension.
4794 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004795 VectorTypes.insert(Ty);
Chandler Carruth00a38332010-12-13 01:44:01 +00004796 } else if (AllowUserConversions && TyRec) {
4797 // No conversion functions in incomplete types.
4798 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4799 return;
Mike Stump11289f42009-09-09 15:08:12 +00004800
Chandler Carruth00a38332010-12-13 01:44:01 +00004801 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4802 const UnresolvedSetImpl *Conversions
4803 = ClassDecl->getVisibleConversionFunctions();
4804 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4805 E = Conversions->end(); I != E; ++I) {
4806 NamedDecl *D = I.getDecl();
4807 if (isa<UsingShadowDecl>(D))
4808 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004809
Chandler Carruth00a38332010-12-13 01:44:01 +00004810 // Skip conversion function templates; they don't tell us anything
4811 // about which builtin types we can convert to.
4812 if (isa<FunctionTemplateDecl>(D))
4813 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00004814
Chandler Carruth00a38332010-12-13 01:44:01 +00004815 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4816 if (AllowExplicitConversions || !Conv->isExplicit()) {
4817 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4818 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004819 }
4820 }
4821 }
4822}
4823
Douglas Gregor84605ae2009-08-24 13:43:27 +00004824/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4825/// the volatile- and non-volatile-qualified assignment operators for the
4826/// given type to the candidate set.
4827static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4828 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004829 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004830 unsigned NumArgs,
4831 OverloadCandidateSet &CandidateSet) {
4832 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004833
Douglas Gregor84605ae2009-08-24 13:43:27 +00004834 // T& operator=(T&, T)
4835 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4836 ParamTypes[1] = T;
4837 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4838 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004839
Douglas Gregor84605ae2009-08-24 13:43:27 +00004840 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4841 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004842 ParamTypes[0]
4843 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004844 ParamTypes[1] = T;
4845 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004846 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004847 }
4848}
Mike Stump11289f42009-09-09 15:08:12 +00004849
Sebastian Redl1054fae2009-10-25 17:03:50 +00004850/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4851/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004852static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4853 Qualifiers VRQuals;
4854 const RecordType *TyRec;
4855 if (const MemberPointerType *RHSMPType =
4856 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004857 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004858 else
4859 TyRec = ArgExpr->getType()->getAs<RecordType>();
4860 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004861 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004862 VRQuals.addVolatile();
4863 VRQuals.addRestrict();
4864 return VRQuals;
4865 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004866
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004867 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004868 if (!ClassDecl->hasDefinition())
4869 return VRQuals;
4870
John McCallad371252010-01-20 00:46:10 +00004871 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004872 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004873
John McCallad371252010-01-20 00:46:10 +00004874 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004875 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004876 NamedDecl *D = I.getDecl();
4877 if (isa<UsingShadowDecl>(D))
4878 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4879 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004880 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4881 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4882 CanTy = ResTypeRef->getPointeeType();
4883 // Need to go down the pointer/mempointer chain and add qualifiers
4884 // as see them.
4885 bool done = false;
4886 while (!done) {
4887 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4888 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004889 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004890 CanTy->getAs<MemberPointerType>())
4891 CanTy = ResTypeMPtr->getPointeeType();
4892 else
4893 done = true;
4894 if (CanTy.isVolatileQualified())
4895 VRQuals.addVolatile();
4896 if (CanTy.isRestrictQualified())
4897 VRQuals.addRestrict();
4898 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4899 return VRQuals;
4900 }
4901 }
4902 }
4903 return VRQuals;
4904}
John McCall52872982010-11-13 05:51:15 +00004905
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004906namespace {
John McCall52872982010-11-13 05:51:15 +00004907
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004908/// \brief Helper class to manage the addition of builtin operator overload
4909/// candidates. It provides shared state and utility methods used throughout
4910/// the process, as well as a helper method to add each group of builtin
4911/// operator overloads from the standard to a candidate set.
4912class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004913 // Common instance state available to all overload candidate addition methods.
4914 Sema &S;
4915 Expr **Args;
4916 unsigned NumArgs;
4917 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00004918 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruthc6586e52010-12-12 10:35:00 +00004919 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4920 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004921
Chandler Carruthc6586e52010-12-12 10:35:00 +00004922 // Define some constants used to index and iterate over the arithemetic types
4923 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00004924 // The "promoted arithmetic types" are the arithmetic
4925 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00004926 static const unsigned FirstIntegralType = 3;
4927 static const unsigned LastIntegralType = 18;
4928 static const unsigned FirstPromotedIntegralType = 3,
4929 LastPromotedIntegralType = 9;
4930 static const unsigned FirstPromotedArithmeticType = 0,
4931 LastPromotedArithmeticType = 9;
4932 static const unsigned NumArithmeticTypes = 18;
4933
Chandler Carruthc6586e52010-12-12 10:35:00 +00004934 /// \brief Get the canonical type for a given arithmetic type index.
4935 CanQualType getArithmeticType(unsigned index) {
4936 assert(index < NumArithmeticTypes);
4937 static CanQualType ASTContext::* const
4938 ArithmeticTypes[NumArithmeticTypes] = {
4939 // Start of promoted types.
4940 &ASTContext::FloatTy,
4941 &ASTContext::DoubleTy,
4942 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00004943
Chandler Carruthc6586e52010-12-12 10:35:00 +00004944 // Start of integral types.
4945 &ASTContext::IntTy,
4946 &ASTContext::LongTy,
4947 &ASTContext::LongLongTy,
4948 &ASTContext::UnsignedIntTy,
4949 &ASTContext::UnsignedLongTy,
4950 &ASTContext::UnsignedLongLongTy,
4951 // End of promoted types.
4952
4953 &ASTContext::BoolTy,
4954 &ASTContext::CharTy,
4955 &ASTContext::WCharTy,
4956 &ASTContext::Char16Ty,
4957 &ASTContext::Char32Ty,
4958 &ASTContext::SignedCharTy,
4959 &ASTContext::ShortTy,
4960 &ASTContext::UnsignedCharTy,
4961 &ASTContext::UnsignedShortTy,
4962 // End of integral types.
4963 // FIXME: What about complex?
4964 };
4965 return S.Context.*ArithmeticTypes[index];
4966 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004967
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004968 /// \brief Gets the canonical type resulting from the usual arithemetic
4969 /// converions for the given arithmetic types.
4970 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
4971 // Accelerator table for performing the usual arithmetic conversions.
4972 // The rules are basically:
4973 // - if either is floating-point, use the wider floating-point
4974 // - if same signedness, use the higher rank
4975 // - if same size, use unsigned of the higher rank
4976 // - use the larger type
4977 // These rules, together with the axiom that higher ranks are
4978 // never smaller, are sufficient to precompute all of these results
4979 // *except* when dealing with signed types of higher rank.
4980 // (we could precompute SLL x UI for all known platforms, but it's
4981 // better not to make any assumptions).
4982 enum PromotedType {
4983 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
4984 };
4985 static PromotedType ConversionsTable[LastPromotedArithmeticType]
4986 [LastPromotedArithmeticType] = {
4987 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4988 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4989 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4990 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4991 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4992 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4993 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4994 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4995 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
4996 };
4997
4998 assert(L < LastPromotedArithmeticType);
4999 assert(R < LastPromotedArithmeticType);
5000 int Idx = ConversionsTable[L][R];
5001
5002 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005003 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005004
5005 // Slow path: we need to compare widths.
5006 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005007 CanQualType LT = getArithmeticType(L),
5008 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005009 unsigned LW = S.Context.getIntWidth(LT),
5010 RW = S.Context.getIntWidth(RT);
5011
5012 // If they're different widths, use the signed type.
5013 if (LW > RW) return LT;
5014 else if (LW < RW) return RT;
5015
5016 // Otherwise, use the unsigned type of the signed type's rank.
5017 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5018 assert(L == SLL || R == SLL);
5019 return S.Context.UnsignedLongLongTy;
5020 }
5021
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005022 /// \brief Helper method to factor out the common pattern of adding overloads
5023 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005024 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5025 bool HasVolatile) {
5026 QualType ParamTypes[2] = {
5027 S.Context.getLValueReferenceType(CandidateTy),
5028 S.Context.IntTy
5029 };
5030
5031 // Non-volatile version.
5032 if (NumArgs == 1)
5033 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5034 else
5035 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5036
5037 // Use a heuristic to reduce number of builtin candidates in the set:
5038 // add volatile version only if there are conversions to a volatile type.
5039 if (HasVolatile) {
5040 ParamTypes[0] =
5041 S.Context.getLValueReferenceType(
5042 S.Context.getVolatileType(CandidateTy));
5043 if (NumArgs == 1)
5044 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5045 else
5046 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5047 }
5048 }
5049
5050public:
5051 BuiltinOperatorOverloadBuilder(
5052 Sema &S, Expr **Args, unsigned NumArgs,
5053 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005054 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005055 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
5056 OverloadCandidateSet &CandidateSet)
5057 : S(S), Args(Args), NumArgs(NumArgs),
5058 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005059 HasArithmeticOrEnumeralCandidateType(
5060 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005061 CandidateTypes(CandidateTypes),
5062 CandidateSet(CandidateSet) {
5063 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005064 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005065 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005066 assert(getArithmeticType(LastPromotedIntegralType - 1)
5067 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005068 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005069 assert(getArithmeticType(FirstPromotedArithmeticType)
5070 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005071 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005072 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5073 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005074 "Invalid last promoted arithmetic type");
5075 }
5076
5077 // C++ [over.built]p3:
5078 //
5079 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5080 // is either volatile or empty, there exist candidate operator
5081 // functions of the form
5082 //
5083 // VQ T& operator++(VQ T&);
5084 // T operator++(VQ T&, int);
5085 //
5086 // C++ [over.built]p4:
5087 //
5088 // For every pair (T, VQ), where T is an arithmetic type other
5089 // than bool, and VQ is either volatile or empty, there exist
5090 // candidate operator functions of the form
5091 //
5092 // VQ T& operator--(VQ T&);
5093 // T operator--(VQ T&, int);
5094 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005095 if (!HasArithmeticOrEnumeralCandidateType)
5096 return;
5097
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005098 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5099 Arith < NumArithmeticTypes; ++Arith) {
5100 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005101 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005102 VisibleTypeConversionsQuals.hasVolatile());
5103 }
5104 }
5105
5106 // C++ [over.built]p5:
5107 //
5108 // For every pair (T, VQ), where T is a cv-qualified or
5109 // cv-unqualified object type, and VQ is either volatile or
5110 // empty, there exist candidate operator functions of the form
5111 //
5112 // T*VQ& operator++(T*VQ&);
5113 // T*VQ& operator--(T*VQ&);
5114 // T* operator++(T*VQ&, int);
5115 // T* operator--(T*VQ&, int);
5116 void addPlusPlusMinusMinusPointerOverloads() {
5117 for (BuiltinCandidateTypeSet::iterator
5118 Ptr = CandidateTypes[0].pointer_begin(),
5119 PtrEnd = CandidateTypes[0].pointer_end();
5120 Ptr != PtrEnd; ++Ptr) {
5121 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005122 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005123 continue;
5124
5125 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5126 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5127 VisibleTypeConversionsQuals.hasVolatile()));
5128 }
5129 }
5130
5131 // C++ [over.built]p6:
5132 // For every cv-qualified or cv-unqualified object type T, there
5133 // exist candidate operator functions of the form
5134 //
5135 // T& operator*(T*);
5136 //
5137 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005138 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005139 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005140 // T& operator*(T*);
5141 void addUnaryStarPointerOverloads() {
5142 for (BuiltinCandidateTypeSet::iterator
5143 Ptr = CandidateTypes[0].pointer_begin(),
5144 PtrEnd = CandidateTypes[0].pointer_end();
5145 Ptr != PtrEnd; ++Ptr) {
5146 QualType ParamTy = *Ptr;
5147 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005148 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5149 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005150
Douglas Gregor02824322011-01-26 19:30:28 +00005151 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5152 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5153 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005154
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005155 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5156 &ParamTy, Args, 1, CandidateSet);
5157 }
5158 }
5159
5160 // C++ [over.built]p9:
5161 // For every promoted arithmetic type T, there exist candidate
5162 // operator functions of the form
5163 //
5164 // T operator+(T);
5165 // T operator-(T);
5166 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005167 if (!HasArithmeticOrEnumeralCandidateType)
5168 return;
5169
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005170 for (unsigned Arith = FirstPromotedArithmeticType;
5171 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005172 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005173 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5174 }
5175
5176 // Extension: We also add these operators for vector types.
5177 for (BuiltinCandidateTypeSet::iterator
5178 Vec = CandidateTypes[0].vector_begin(),
5179 VecEnd = CandidateTypes[0].vector_end();
5180 Vec != VecEnd; ++Vec) {
5181 QualType VecTy = *Vec;
5182 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5183 }
5184 }
5185
5186 // C++ [over.built]p8:
5187 // For every type T, there exist candidate operator functions of
5188 // the form
5189 //
5190 // T* operator+(T*);
5191 void addUnaryPlusPointerOverloads() {
5192 for (BuiltinCandidateTypeSet::iterator
5193 Ptr = CandidateTypes[0].pointer_begin(),
5194 PtrEnd = CandidateTypes[0].pointer_end();
5195 Ptr != PtrEnd; ++Ptr) {
5196 QualType ParamTy = *Ptr;
5197 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5198 }
5199 }
5200
5201 // C++ [over.built]p10:
5202 // For every promoted integral type T, there exist candidate
5203 // operator functions of the form
5204 //
5205 // T operator~(T);
5206 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005207 if (!HasArithmeticOrEnumeralCandidateType)
5208 return;
5209
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005210 for (unsigned Int = FirstPromotedIntegralType;
5211 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005212 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005213 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5214 }
5215
5216 // Extension: We also add this operator for vector types.
5217 for (BuiltinCandidateTypeSet::iterator
5218 Vec = CandidateTypes[0].vector_begin(),
5219 VecEnd = CandidateTypes[0].vector_end();
5220 Vec != VecEnd; ++Vec) {
5221 QualType VecTy = *Vec;
5222 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5223 }
5224 }
5225
5226 // C++ [over.match.oper]p16:
5227 // For every pointer to member type T, there exist candidate operator
5228 // functions of the form
5229 //
5230 // bool operator==(T,T);
5231 // bool operator!=(T,T);
5232 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5233 /// Set of (canonical) types that we've already handled.
5234 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5235
5236 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5237 for (BuiltinCandidateTypeSet::iterator
5238 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5239 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5240 MemPtr != MemPtrEnd;
5241 ++MemPtr) {
5242 // Don't add the same builtin candidate twice.
5243 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5244 continue;
5245
5246 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5247 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5248 CandidateSet);
5249 }
5250 }
5251 }
5252
5253 // C++ [over.built]p15:
5254 //
5255 // For every pointer or enumeration type T, there exist
5256 // candidate operator functions of the form
5257 //
5258 // bool operator<(T, T);
5259 // bool operator>(T, T);
5260 // bool operator<=(T, T);
5261 // bool operator>=(T, T);
5262 // bool operator==(T, T);
5263 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005264 void addRelationalPointerOrEnumeralOverloads() {
5265 // C++ [over.built]p1:
5266 // If there is a user-written candidate with the same name and parameter
5267 // types as a built-in candidate operator function, the built-in operator
5268 // function is hidden and is not included in the set of candidate
5269 // functions.
5270 //
5271 // The text is actually in a note, but if we don't implement it then we end
5272 // up with ambiguities when the user provides an overloaded operator for
5273 // an enumeration type. Note that only enumeration types have this problem,
5274 // so we track which enumeration types we've seen operators for. Also, the
5275 // only other overloaded operator with enumeration argumenst, operator=,
5276 // cannot be overloaded for enumeration types, so this is the only place
5277 // where we must suppress candidates like this.
5278 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5279 UserDefinedBinaryOperators;
5280
5281 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5282 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5283 CandidateTypes[ArgIdx].enumeration_end()) {
5284 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5285 CEnd = CandidateSet.end();
5286 C != CEnd; ++C) {
5287 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5288 continue;
5289
5290 QualType FirstParamType =
5291 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5292 QualType SecondParamType =
5293 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5294
5295 // Skip if either parameter isn't of enumeral type.
5296 if (!FirstParamType->isEnumeralType() ||
5297 !SecondParamType->isEnumeralType())
5298 continue;
5299
5300 // Add this operator to the set of known user-defined operators.
5301 UserDefinedBinaryOperators.insert(
5302 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5303 S.Context.getCanonicalType(SecondParamType)));
5304 }
5305 }
5306 }
5307
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005308 /// Set of (canonical) types that we've already handled.
5309 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5310
5311 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5312 for (BuiltinCandidateTypeSet::iterator
5313 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5314 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5315 Ptr != PtrEnd; ++Ptr) {
5316 // Don't add the same builtin candidate twice.
5317 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5318 continue;
5319
5320 QualType ParamTypes[2] = { *Ptr, *Ptr };
5321 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5322 CandidateSet);
5323 }
5324 for (BuiltinCandidateTypeSet::iterator
5325 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5326 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5327 Enum != EnumEnd; ++Enum) {
5328 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5329
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005330 // Don't add the same builtin candidate twice, or if a user defined
5331 // candidate exists.
5332 if (!AddedTypes.insert(CanonType) ||
5333 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5334 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005335 continue;
5336
5337 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005338 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5339 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005340 }
5341 }
5342 }
5343
5344 // C++ [over.built]p13:
5345 //
5346 // For every cv-qualified or cv-unqualified object type T
5347 // there exist candidate operator functions of the form
5348 //
5349 // T* operator+(T*, ptrdiff_t);
5350 // T& operator[](T*, ptrdiff_t); [BELOW]
5351 // T* operator-(T*, ptrdiff_t);
5352 // T* operator+(ptrdiff_t, T*);
5353 // T& operator[](ptrdiff_t, T*); [BELOW]
5354 //
5355 // C++ [over.built]p14:
5356 //
5357 // For every T, where T is a pointer to object type, there
5358 // exist candidate operator functions of the form
5359 //
5360 // ptrdiff_t operator-(T, T);
5361 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5362 /// Set of (canonical) types that we've already handled.
5363 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5364
5365 for (int Arg = 0; Arg < 2; ++Arg) {
5366 QualType AsymetricParamTypes[2] = {
5367 S.Context.getPointerDiffType(),
5368 S.Context.getPointerDiffType(),
5369 };
5370 for (BuiltinCandidateTypeSet::iterator
5371 Ptr = CandidateTypes[Arg].pointer_begin(),
5372 PtrEnd = CandidateTypes[Arg].pointer_end();
5373 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005374 QualType PointeeTy = (*Ptr)->getPointeeType();
5375 if (!PointeeTy->isObjectType())
5376 continue;
5377
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005378 AsymetricParamTypes[Arg] = *Ptr;
5379 if (Arg == 0 || Op == OO_Plus) {
5380 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5381 // T* operator+(ptrdiff_t, T*);
5382 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5383 CandidateSet);
5384 }
5385 if (Op == OO_Minus) {
5386 // ptrdiff_t operator-(T, T);
5387 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5388 continue;
5389
5390 QualType ParamTypes[2] = { *Ptr, *Ptr };
5391 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5392 Args, 2, CandidateSet);
5393 }
5394 }
5395 }
5396 }
5397
5398 // C++ [over.built]p12:
5399 //
5400 // For every pair of promoted arithmetic types L and R, there
5401 // exist candidate operator functions of the form
5402 //
5403 // LR operator*(L, R);
5404 // LR operator/(L, R);
5405 // LR operator+(L, R);
5406 // LR operator-(L, R);
5407 // bool operator<(L, R);
5408 // bool operator>(L, R);
5409 // bool operator<=(L, R);
5410 // bool operator>=(L, R);
5411 // bool operator==(L, R);
5412 // bool operator!=(L, R);
5413 //
5414 // where LR is the result of the usual arithmetic conversions
5415 // between types L and R.
5416 //
5417 // C++ [over.built]p24:
5418 //
5419 // For every pair of promoted arithmetic types L and R, there exist
5420 // candidate operator functions of the form
5421 //
5422 // LR operator?(bool, L, R);
5423 //
5424 // where LR is the result of the usual arithmetic conversions
5425 // between types L and R.
5426 // Our candidates ignore the first parameter.
5427 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005428 if (!HasArithmeticOrEnumeralCandidateType)
5429 return;
5430
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005431 for (unsigned Left = FirstPromotedArithmeticType;
5432 Left < LastPromotedArithmeticType; ++Left) {
5433 for (unsigned Right = FirstPromotedArithmeticType;
5434 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005435 QualType LandR[2] = { getArithmeticType(Left),
5436 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005437 QualType Result =
5438 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005439 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005440 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5441 }
5442 }
5443
5444 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5445 // conditional operator for vector types.
5446 for (BuiltinCandidateTypeSet::iterator
5447 Vec1 = CandidateTypes[0].vector_begin(),
5448 Vec1End = CandidateTypes[0].vector_end();
5449 Vec1 != Vec1End; ++Vec1) {
5450 for (BuiltinCandidateTypeSet::iterator
5451 Vec2 = CandidateTypes[1].vector_begin(),
5452 Vec2End = CandidateTypes[1].vector_end();
5453 Vec2 != Vec2End; ++Vec2) {
5454 QualType LandR[2] = { *Vec1, *Vec2 };
5455 QualType Result = S.Context.BoolTy;
5456 if (!isComparison) {
5457 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5458 Result = *Vec1;
5459 else
5460 Result = *Vec2;
5461 }
5462
5463 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5464 }
5465 }
5466 }
5467
5468 // C++ [over.built]p17:
5469 //
5470 // For every pair of promoted integral types L and R, there
5471 // exist candidate operator functions of the form
5472 //
5473 // LR operator%(L, R);
5474 // LR operator&(L, R);
5475 // LR operator^(L, R);
5476 // LR operator|(L, R);
5477 // L operator<<(L, R);
5478 // L operator>>(L, R);
5479 //
5480 // where LR is the result of the usual arithmetic conversions
5481 // between types L and R.
5482 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005483 if (!HasArithmeticOrEnumeralCandidateType)
5484 return;
5485
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005486 for (unsigned Left = FirstPromotedIntegralType;
5487 Left < LastPromotedIntegralType; ++Left) {
5488 for (unsigned Right = FirstPromotedIntegralType;
5489 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005490 QualType LandR[2] = { getArithmeticType(Left),
5491 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005492 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5493 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005494 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005495 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5496 }
5497 }
5498 }
5499
5500 // C++ [over.built]p20:
5501 //
5502 // For every pair (T, VQ), where T is an enumeration or
5503 // pointer to member type and VQ is either volatile or
5504 // empty, there exist candidate operator functions of the form
5505 //
5506 // VQ T& operator=(VQ T&, T);
5507 void addAssignmentMemberPointerOrEnumeralOverloads() {
5508 /// Set of (canonical) types that we've already handled.
5509 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5510
5511 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5512 for (BuiltinCandidateTypeSet::iterator
5513 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5514 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5515 Enum != EnumEnd; ++Enum) {
5516 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5517 continue;
5518
5519 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5520 CandidateSet);
5521 }
5522
5523 for (BuiltinCandidateTypeSet::iterator
5524 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5525 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5526 MemPtr != MemPtrEnd; ++MemPtr) {
5527 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5528 continue;
5529
5530 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5531 CandidateSet);
5532 }
5533 }
5534 }
5535
5536 // C++ [over.built]p19:
5537 //
5538 // For every pair (T, VQ), where T is any type and VQ is either
5539 // volatile or empty, there exist candidate operator functions
5540 // of the form
5541 //
5542 // T*VQ& operator=(T*VQ&, T*);
5543 //
5544 // C++ [over.built]p21:
5545 //
5546 // For every pair (T, VQ), where T is a cv-qualified or
5547 // cv-unqualified object type and VQ is either volatile or
5548 // empty, there exist candidate operator functions of the form
5549 //
5550 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5551 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5552 void addAssignmentPointerOverloads(bool isEqualOp) {
5553 /// Set of (canonical) types that we've already handled.
5554 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5555
5556 for (BuiltinCandidateTypeSet::iterator
5557 Ptr = CandidateTypes[0].pointer_begin(),
5558 PtrEnd = CandidateTypes[0].pointer_end();
5559 Ptr != PtrEnd; ++Ptr) {
5560 // If this is operator=, keep track of the builtin candidates we added.
5561 if (isEqualOp)
5562 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005563 else if (!(*Ptr)->getPointeeType()->isObjectType())
5564 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005565
5566 // non-volatile version
5567 QualType ParamTypes[2] = {
5568 S.Context.getLValueReferenceType(*Ptr),
5569 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5570 };
5571 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5572 /*IsAssigmentOperator=*/ isEqualOp);
5573
5574 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5575 VisibleTypeConversionsQuals.hasVolatile()) {
5576 // volatile version
5577 ParamTypes[0] =
5578 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5579 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5580 /*IsAssigmentOperator=*/isEqualOp);
5581 }
5582 }
5583
5584 if (isEqualOp) {
5585 for (BuiltinCandidateTypeSet::iterator
5586 Ptr = CandidateTypes[1].pointer_begin(),
5587 PtrEnd = CandidateTypes[1].pointer_end();
5588 Ptr != PtrEnd; ++Ptr) {
5589 // Make sure we don't add the same candidate twice.
5590 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5591 continue;
5592
Chandler Carruth8e543b32010-12-12 08:17:55 +00005593 QualType ParamTypes[2] = {
5594 S.Context.getLValueReferenceType(*Ptr),
5595 *Ptr,
5596 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005597
5598 // non-volatile version
5599 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5600 /*IsAssigmentOperator=*/true);
5601
5602 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5603 VisibleTypeConversionsQuals.hasVolatile()) {
5604 // volatile version
5605 ParamTypes[0] =
5606 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00005607 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5608 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005609 }
5610 }
5611 }
5612 }
5613
5614 // C++ [over.built]p18:
5615 //
5616 // For every triple (L, VQ, R), where L is an arithmetic type,
5617 // VQ is either volatile or empty, and R is a promoted
5618 // arithmetic type, there exist candidate operator functions of
5619 // the form
5620 //
5621 // VQ L& operator=(VQ L&, R);
5622 // VQ L& operator*=(VQ L&, R);
5623 // VQ L& operator/=(VQ L&, R);
5624 // VQ L& operator+=(VQ L&, R);
5625 // VQ L& operator-=(VQ L&, R);
5626 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005627 if (!HasArithmeticOrEnumeralCandidateType)
5628 return;
5629
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005630 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5631 for (unsigned Right = FirstPromotedArithmeticType;
5632 Right < LastPromotedArithmeticType; ++Right) {
5633 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005634 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005635
5636 // Add this built-in operator as a candidate (VQ is empty).
5637 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005638 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005639 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5640 /*IsAssigmentOperator=*/isEqualOp);
5641
5642 // Add this built-in operator as a candidate (VQ is 'volatile').
5643 if (VisibleTypeConversionsQuals.hasVolatile()) {
5644 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005645 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005646 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005647 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5648 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005649 /*IsAssigmentOperator=*/isEqualOp);
5650 }
5651 }
5652 }
5653
5654 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5655 for (BuiltinCandidateTypeSet::iterator
5656 Vec1 = CandidateTypes[0].vector_begin(),
5657 Vec1End = CandidateTypes[0].vector_end();
5658 Vec1 != Vec1End; ++Vec1) {
5659 for (BuiltinCandidateTypeSet::iterator
5660 Vec2 = CandidateTypes[1].vector_begin(),
5661 Vec2End = CandidateTypes[1].vector_end();
5662 Vec2 != Vec2End; ++Vec2) {
5663 QualType ParamTypes[2];
5664 ParamTypes[1] = *Vec2;
5665 // Add this built-in operator as a candidate (VQ is empty).
5666 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5667 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5668 /*IsAssigmentOperator=*/isEqualOp);
5669
5670 // Add this built-in operator as a candidate (VQ is 'volatile').
5671 if (VisibleTypeConversionsQuals.hasVolatile()) {
5672 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5673 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005674 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5675 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005676 /*IsAssigmentOperator=*/isEqualOp);
5677 }
5678 }
5679 }
5680 }
5681
5682 // C++ [over.built]p22:
5683 //
5684 // For every triple (L, VQ, R), where L is an integral type, VQ
5685 // is either volatile or empty, and R is a promoted integral
5686 // type, there exist candidate operator functions of the form
5687 //
5688 // VQ L& operator%=(VQ L&, R);
5689 // VQ L& operator<<=(VQ L&, R);
5690 // VQ L& operator>>=(VQ L&, R);
5691 // VQ L& operator&=(VQ L&, R);
5692 // VQ L& operator^=(VQ L&, R);
5693 // VQ L& operator|=(VQ L&, R);
5694 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005695 if (!HasArithmeticOrEnumeralCandidateType)
5696 return;
5697
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005698 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5699 for (unsigned Right = FirstPromotedIntegralType;
5700 Right < LastPromotedIntegralType; ++Right) {
5701 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005702 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005703
5704 // Add this built-in operator as a candidate (VQ is empty).
5705 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005706 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005707 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5708 if (VisibleTypeConversionsQuals.hasVolatile()) {
5709 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00005710 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005711 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5712 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5713 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5714 CandidateSet);
5715 }
5716 }
5717 }
5718 }
5719
5720 // C++ [over.operator]p23:
5721 //
5722 // There also exist candidate operator functions of the form
5723 //
5724 // bool operator!(bool);
5725 // bool operator&&(bool, bool);
5726 // bool operator||(bool, bool);
5727 void addExclaimOverload() {
5728 QualType ParamTy = S.Context.BoolTy;
5729 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5730 /*IsAssignmentOperator=*/false,
5731 /*NumContextualBoolArguments=*/1);
5732 }
5733 void addAmpAmpOrPipePipeOverload() {
5734 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5735 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5736 /*IsAssignmentOperator=*/false,
5737 /*NumContextualBoolArguments=*/2);
5738 }
5739
5740 // C++ [over.built]p13:
5741 //
5742 // For every cv-qualified or cv-unqualified object type T there
5743 // exist candidate operator functions of the form
5744 //
5745 // T* operator+(T*, ptrdiff_t); [ABOVE]
5746 // T& operator[](T*, ptrdiff_t);
5747 // T* operator-(T*, ptrdiff_t); [ABOVE]
5748 // T* operator+(ptrdiff_t, T*); [ABOVE]
5749 // T& operator[](ptrdiff_t, T*);
5750 void addSubscriptOverloads() {
5751 for (BuiltinCandidateTypeSet::iterator
5752 Ptr = CandidateTypes[0].pointer_begin(),
5753 PtrEnd = CandidateTypes[0].pointer_end();
5754 Ptr != PtrEnd; ++Ptr) {
5755 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5756 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005757 if (!PointeeType->isObjectType())
5758 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005759
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005760 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5761
5762 // T& operator[](T*, ptrdiff_t)
5763 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5764 }
5765
5766 for (BuiltinCandidateTypeSet::iterator
5767 Ptr = CandidateTypes[1].pointer_begin(),
5768 PtrEnd = CandidateTypes[1].pointer_end();
5769 Ptr != PtrEnd; ++Ptr) {
5770 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5771 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005772 if (!PointeeType->isObjectType())
5773 continue;
5774
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005775 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5776
5777 // T& operator[](ptrdiff_t, T*)
5778 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5779 }
5780 }
5781
5782 // C++ [over.built]p11:
5783 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5784 // C1 is the same type as C2 or is a derived class of C2, T is an object
5785 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5786 // there exist candidate operator functions of the form
5787 //
5788 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5789 //
5790 // where CV12 is the union of CV1 and CV2.
5791 void addArrowStarOverloads() {
5792 for (BuiltinCandidateTypeSet::iterator
5793 Ptr = CandidateTypes[0].pointer_begin(),
5794 PtrEnd = CandidateTypes[0].pointer_end();
5795 Ptr != PtrEnd; ++Ptr) {
5796 QualType C1Ty = (*Ptr);
5797 QualType C1;
5798 QualifierCollector Q1;
5799 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5800 if (!isa<RecordType>(C1))
5801 continue;
5802 // heuristic to reduce number of builtin candidates in the set.
5803 // Add volatile/restrict version only if there are conversions to a
5804 // volatile/restrict type.
5805 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5806 continue;
5807 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5808 continue;
5809 for (BuiltinCandidateTypeSet::iterator
5810 MemPtr = CandidateTypes[1].member_pointer_begin(),
5811 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5812 MemPtr != MemPtrEnd; ++MemPtr) {
5813 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5814 QualType C2 = QualType(mptr->getClass(), 0);
5815 C2 = C2.getUnqualifiedType();
5816 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5817 break;
5818 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5819 // build CV12 T&
5820 QualType T = mptr->getPointeeType();
5821 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5822 T.isVolatileQualified())
5823 continue;
5824 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5825 T.isRestrictQualified())
5826 continue;
5827 T = Q1.apply(S.Context, T);
5828 QualType ResultTy = S.Context.getLValueReferenceType(T);
5829 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5830 }
5831 }
5832 }
5833
5834 // Note that we don't consider the first argument, since it has been
5835 // contextually converted to bool long ago. The candidates below are
5836 // therefore added as binary.
5837 //
5838 // C++ [over.built]p25:
5839 // For every type T, where T is a pointer, pointer-to-member, or scoped
5840 // enumeration type, there exist candidate operator functions of the form
5841 //
5842 // T operator?(bool, T, T);
5843 //
5844 void addConditionalOperatorOverloads() {
5845 /// Set of (canonical) types that we've already handled.
5846 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5847
5848 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5849 for (BuiltinCandidateTypeSet::iterator
5850 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5851 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5852 Ptr != PtrEnd; ++Ptr) {
5853 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5854 continue;
5855
5856 QualType ParamTypes[2] = { *Ptr, *Ptr };
5857 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5858 }
5859
5860 for (BuiltinCandidateTypeSet::iterator
5861 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5862 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5863 MemPtr != MemPtrEnd; ++MemPtr) {
5864 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5865 continue;
5866
5867 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5868 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5869 }
5870
5871 if (S.getLangOptions().CPlusPlus0x) {
5872 for (BuiltinCandidateTypeSet::iterator
5873 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5874 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5875 Enum != EnumEnd; ++Enum) {
5876 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5877 continue;
5878
5879 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5880 continue;
5881
5882 QualType ParamTypes[2] = { *Enum, *Enum };
5883 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5884 }
5885 }
5886 }
5887 }
5888};
5889
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005890} // end anonymous namespace
5891
5892/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5893/// operator overloads to the candidate set (C++ [over.built]), based
5894/// on the operator @p Op and the arguments given. For example, if the
5895/// operator is a binary '+', this routine might add "int
5896/// operator+(int, int)" to cover integer addition.
5897void
5898Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5899 SourceLocation OpLoc,
5900 Expr **Args, unsigned NumArgs,
5901 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005902 // Find all of the types that the arguments can convert to, but only
5903 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00005904 // that make use of these types. Also record whether we encounter non-record
5905 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005906 Qualifiers VisibleTypeConversionsQuals;
5907 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005908 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5909 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00005910
5911 bool HasNonRecordCandidateType = false;
5912 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005913 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5914 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5915 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5916 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5917 OpLoc,
5918 true,
5919 (Op == OO_Exclaim ||
5920 Op == OO_AmpAmp ||
5921 Op == OO_PipePipe),
5922 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00005923 HasNonRecordCandidateType = HasNonRecordCandidateType ||
5924 CandidateTypes[ArgIdx].hasNonRecordTypes();
5925 HasArithmeticOrEnumeralCandidateType =
5926 HasArithmeticOrEnumeralCandidateType ||
5927 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005928 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005929
Chandler Carruth00a38332010-12-13 01:44:01 +00005930 // Exit early when no non-record types have been added to the candidate set
5931 // for any of the arguments to the operator.
5932 if (!HasNonRecordCandidateType)
5933 return;
5934
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005935 // Setup an object to manage the common state for building overloads.
5936 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
5937 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005938 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005939 CandidateTypes, CandidateSet);
5940
5941 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00005942 switch (Op) {
5943 case OO_None:
5944 case NUM_OVERLOADED_OPERATORS:
5945 assert(false && "Expected an overloaded operator");
5946 break;
5947
Chandler Carruth5184de02010-12-12 08:51:33 +00005948 case OO_New:
5949 case OO_Delete:
5950 case OO_Array_New:
5951 case OO_Array_Delete:
5952 case OO_Call:
5953 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
5954 break;
5955
5956 case OO_Comma:
5957 case OO_Arrow:
5958 // C++ [over.match.oper]p3:
5959 // -- For the operator ',', the unary operator '&', or the
5960 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00005961 break;
5962
5963 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00005964 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005965 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00005966 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00005967
5968 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00005969 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005970 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00005971 } else {
5972 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
5973 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5974 }
Douglas Gregord08452f2008-11-19 15:42:04 +00005975 break;
5976
Chandler Carruth5184de02010-12-12 08:51:33 +00005977 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00005978 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00005979 OpBuilder.addUnaryStarPointerOverloads();
5980 else
5981 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5982 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005983
Chandler Carruth5184de02010-12-12 08:51:33 +00005984 case OO_Slash:
5985 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00005986 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005987
5988 case OO_PlusPlus:
5989 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005990 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
5991 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00005992 break;
5993
Douglas Gregor84605ae2009-08-24 13:43:27 +00005994 case OO_EqualEqual:
5995 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005996 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00005997 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00005998
Douglas Gregora11693b2008-11-12 17:17:38 +00005999 case OO_Less:
6000 case OO_Greater:
6001 case OO_LessEqual:
6002 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006003 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006004 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6005 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006006
Douglas Gregora11693b2008-11-12 17:17:38 +00006007 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006008 case OO_Caret:
6009 case OO_Pipe:
6010 case OO_LessLess:
6011 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006012 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006013 break;
6014
Chandler Carruth5184de02010-12-12 08:51:33 +00006015 case OO_Amp: // '&' is either unary or binary
6016 if (NumArgs == 1)
6017 // C++ [over.match.oper]p3:
6018 // -- For the operator ',', the unary operator '&', or the
6019 // operator '->', the built-in candidates set is empty.
6020 break;
6021
6022 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6023 break;
6024
6025 case OO_Tilde:
6026 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6027 break;
6028
Douglas Gregora11693b2008-11-12 17:17:38 +00006029 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006030 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006031 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006032
6033 case OO_PlusEqual:
6034 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006035 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006036 // Fall through.
6037
6038 case OO_StarEqual:
6039 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006040 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006041 break;
6042
6043 case OO_PercentEqual:
6044 case OO_LessLessEqual:
6045 case OO_GreaterGreaterEqual:
6046 case OO_AmpEqual:
6047 case OO_CaretEqual:
6048 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006049 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006050 break;
6051
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006052 case OO_Exclaim:
6053 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006054 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006055
Douglas Gregora11693b2008-11-12 17:17:38 +00006056 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006057 case OO_PipePipe:
6058 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006059 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006060
6061 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006062 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006063 break;
6064
6065 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006066 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006067 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006068
6069 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006070 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006071 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6072 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006073 }
6074}
6075
Douglas Gregore254f902009-02-04 00:32:51 +00006076/// \brief Add function candidates found via argument-dependent lookup
6077/// to the set of overloading candidates.
6078///
6079/// This routine performs argument-dependent name lookup based on the
6080/// given function name (which may also be an operator name) and adds
6081/// all of the overload candidates found by ADL to the overload
6082/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006083void
Douglas Gregore254f902009-02-04 00:32:51 +00006084Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006085 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006086 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00006087 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006088 OverloadCandidateSet& CandidateSet,
6089 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00006090 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006091
John McCall91f61fc2010-01-26 06:04:06 +00006092 // FIXME: This approach for uniquing ADL results (and removing
6093 // redundant candidates from the set) relies on pointer-equality,
6094 // which means we need to key off the canonical decl. However,
6095 // always going back to the canonical decl might not get us the
6096 // right set of default arguments. What default arguments are
6097 // we supposed to consider on ADL candidates, anyway?
6098
Douglas Gregorcabea402009-09-22 15:41:20 +00006099 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00006100 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00006101
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006102 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006103 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6104 CandEnd = CandidateSet.end();
6105 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006106 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006107 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006108 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006109 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006110 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006111
6112 // For each of the ADL candidates we found, add it to the overload
6113 // set.
John McCall8fe68082010-01-26 07:16:45 +00006114 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006115 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006116 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006117 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006118 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006119
John McCalla0296f72010-03-19 07:35:19 +00006120 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006121 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006122 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006123 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006124 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006125 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006126 }
Douglas Gregore254f902009-02-04 00:32:51 +00006127}
6128
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006129/// isBetterOverloadCandidate - Determines whether the first overload
6130/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006131bool
John McCall5c32be02010-08-24 20:38:10 +00006132isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006133 const OverloadCandidate &Cand1,
6134 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006135 SourceLocation Loc,
6136 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006137 // Define viable functions to be better candidates than non-viable
6138 // functions.
6139 if (!Cand2.Viable)
6140 return Cand1.Viable;
6141 else if (!Cand1.Viable)
6142 return false;
6143
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006144 // C++ [over.match.best]p1:
6145 //
6146 // -- if F is a static member function, ICS1(F) is defined such
6147 // that ICS1(F) is neither better nor worse than ICS1(G) for
6148 // any function G, and, symmetrically, ICS1(G) is neither
6149 // better nor worse than ICS1(F).
6150 unsigned StartArg = 0;
6151 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6152 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006153
Douglas Gregord3cb3562009-07-07 23:38:56 +00006154 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006155 // A viable function F1 is defined to be a better function than another
6156 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006157 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006158 unsigned NumArgs = Cand1.Conversions.size();
6159 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6160 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006161 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006162 switch (CompareImplicitConversionSequences(S,
6163 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006164 Cand2.Conversions[ArgIdx])) {
6165 case ImplicitConversionSequence::Better:
6166 // Cand1 has a better conversion sequence.
6167 HasBetterConversion = true;
6168 break;
6169
6170 case ImplicitConversionSequence::Worse:
6171 // Cand1 can't be better than Cand2.
6172 return false;
6173
6174 case ImplicitConversionSequence::Indistinguishable:
6175 // Do nothing.
6176 break;
6177 }
6178 }
6179
Mike Stump11289f42009-09-09 15:08:12 +00006180 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006181 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006182 if (HasBetterConversion)
6183 return true;
6184
Mike Stump11289f42009-09-09 15:08:12 +00006185 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006186 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006187 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006188 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6189 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006190
6191 // -- F1 and F2 are function template specializations, and the function
6192 // template for F1 is more specialized than the template for F2
6193 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006194 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006195 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006196 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006197 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006198 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6199 Cand2.Function->getPrimaryTemplate(),
6200 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006201 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006202 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006203 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006204 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006205 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006206
Douglas Gregora1f013e2008-11-07 22:36:19 +00006207 // -- the context is an initialization by user-defined conversion
6208 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6209 // from the return type of F1 to the destination type (i.e.,
6210 // the type of the entity being initialized) is a better
6211 // conversion sequence than the standard conversion sequence
6212 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006213 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006214 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006215 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006216 switch (CompareStandardConversionSequences(S,
6217 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006218 Cand2.FinalConversion)) {
6219 case ImplicitConversionSequence::Better:
6220 // Cand1 has a better conversion sequence.
6221 return true;
6222
6223 case ImplicitConversionSequence::Worse:
6224 // Cand1 can't be better than Cand2.
6225 return false;
6226
6227 case ImplicitConversionSequence::Indistinguishable:
6228 // Do nothing
6229 break;
6230 }
6231 }
6232
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006233 return false;
6234}
6235
Mike Stump11289f42009-09-09 15:08:12 +00006236/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006237/// within an overload candidate set.
6238///
6239/// \param CandidateSet the set of candidate functions.
6240///
6241/// \param Loc the location of the function name (or operator symbol) for
6242/// which overload resolution occurs.
6243///
Mike Stump11289f42009-09-09 15:08:12 +00006244/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006245/// function, Best points to the candidate function found.
6246///
6247/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006248OverloadingResult
6249OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006250 iterator &Best,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006251 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006252 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006253 Best = end();
6254 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6255 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006256 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006257 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006258 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006259 }
6260
6261 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006262 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006263 return OR_No_Viable_Function;
6264
6265 // Make sure that this function is better than every other viable
6266 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006267 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006268 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006269 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006270 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006271 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006272 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006273 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006274 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006275 }
Mike Stump11289f42009-09-09 15:08:12 +00006276
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006277 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006278 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006279 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006280 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006281 return OR_Deleted;
6282
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006283 // C++ [basic.def.odr]p2:
6284 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00006285 // when referred to from a potentially-evaluated expression. [Note: this
6286 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006287 // (clause 13), user-defined conversions (12.3.2), allocation function for
6288 // placement new (5.3.4), as well as non-default initialization (8.5).
6289 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00006290 S.MarkDeclarationReferenced(Loc, Best->Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006291
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006292 return OR_Success;
6293}
6294
John McCall53262c92010-01-12 02:15:36 +00006295namespace {
6296
6297enum OverloadCandidateKind {
6298 oc_function,
6299 oc_method,
6300 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006301 oc_function_template,
6302 oc_method_template,
6303 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006304 oc_implicit_default_constructor,
6305 oc_implicit_copy_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006306 oc_implicit_copy_assignment,
6307 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006308};
6309
John McCalle1ac8d12010-01-13 00:25:19 +00006310OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6311 FunctionDecl *Fn,
6312 std::string &Description) {
6313 bool isTemplate = false;
6314
6315 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6316 isTemplate = true;
6317 Description = S.getTemplateArgumentBindingsText(
6318 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6319 }
John McCallfd0b2f82010-01-06 09:43:14 +00006320
6321 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006322 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006323 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006324
Sebastian Redl08905022011-02-05 19:23:19 +00006325 if (Ctor->getInheritedConstructor())
6326 return oc_implicit_inherited_constructor;
6327
John McCall53262c92010-01-12 02:15:36 +00006328 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6329 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006330 }
6331
6332 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6333 // This actually gets spelled 'candidate function' for now, but
6334 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006335 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006336 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006337
Douglas Gregorec3bec02010-09-27 22:37:28 +00006338 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006339 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006340 return oc_implicit_copy_assignment;
6341 }
6342
John McCalle1ac8d12010-01-13 00:25:19 +00006343 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006344}
6345
Sebastian Redl08905022011-02-05 19:23:19 +00006346void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6347 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6348 if (!Ctor) return;
6349
6350 Ctor = Ctor->getInheritedConstructor();
6351 if (!Ctor) return;
6352
6353 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6354}
6355
John McCall53262c92010-01-12 02:15:36 +00006356} // end anonymous namespace
6357
6358// Notes the location of an overload candidate.
6359void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006360 std::string FnDesc;
6361 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6362 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6363 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00006364 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00006365}
6366
Douglas Gregorb491ed32011-02-19 21:32:49 +00006367//Notes the location of all overload candidates designated through
6368// OverloadedExpr
6369void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6370 assert(OverloadedExpr->getType() == Context.OverloadTy);
6371
6372 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6373 OverloadExpr *OvlExpr = Ovl.Expression;
6374
6375 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6376 IEnd = OvlExpr->decls_end();
6377 I != IEnd; ++I) {
6378 if (FunctionTemplateDecl *FunTmpl =
6379 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6380 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6381 } else if (FunctionDecl *Fun
6382 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6383 NoteOverloadCandidate(Fun);
6384 }
6385 }
6386}
6387
John McCall0d1da222010-01-12 00:44:57 +00006388/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6389/// "lead" diagnostic; it will be given two arguments, the source and
6390/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006391void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6392 Sema &S,
6393 SourceLocation CaretLoc,
6394 const PartialDiagnostic &PDiag) const {
6395 S.Diag(CaretLoc, PDiag)
6396 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006397 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006398 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6399 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006400 }
John McCall12f97bc2010-01-08 04:41:39 +00006401}
6402
John McCall0d1da222010-01-12 00:44:57 +00006403namespace {
6404
John McCall6a61b522010-01-13 09:16:55 +00006405void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6406 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6407 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006408 assert(Cand->Function && "for now, candidate must be a function");
6409 FunctionDecl *Fn = Cand->Function;
6410
6411 // There's a conversion slot for the object argument if this is a
6412 // non-constructor method. Note that 'I' corresponds the
6413 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006414 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006415 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006416 if (I == 0)
6417 isObjectArgument = true;
6418 else
6419 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006420 }
6421
John McCalle1ac8d12010-01-13 00:25:19 +00006422 std::string FnDesc;
6423 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6424
John McCall6a61b522010-01-13 09:16:55 +00006425 Expr *FromExpr = Conv.Bad.FromExpr;
6426 QualType FromTy = Conv.Bad.getFromType();
6427 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006428
John McCallfb7ad0f2010-02-02 02:42:52 +00006429 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006430 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006431 Expr *E = FromExpr->IgnoreParens();
6432 if (isa<UnaryOperator>(E))
6433 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006434 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006435
6436 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6437 << (unsigned) FnKind << FnDesc
6438 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6439 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006440 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00006441 return;
6442 }
6443
John McCall6d174642010-01-23 08:10:49 +00006444 // Do some hand-waving analysis to see if the non-viability is due
6445 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006446 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6447 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6448 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6449 CToTy = RT->getPointeeType();
6450 else {
6451 // TODO: detect and diagnose the full richness of const mismatches.
6452 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6453 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6454 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6455 }
6456
6457 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6458 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6459 // It is dumb that we have to do this here.
6460 while (isa<ArrayType>(CFromTy))
6461 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6462 while (isa<ArrayType>(CToTy))
6463 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6464
6465 Qualifiers FromQs = CFromTy.getQualifiers();
6466 Qualifiers ToQs = CToTy.getQualifiers();
6467
6468 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6469 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6470 << (unsigned) FnKind << FnDesc
6471 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6472 << FromTy
6473 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6474 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006475 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006476 return;
6477 }
6478
6479 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6480 assert(CVR && "unexpected qualifiers mismatch");
6481
6482 if (isObjectArgument) {
6483 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6484 << (unsigned) FnKind << FnDesc
6485 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6486 << FromTy << (CVR - 1);
6487 } else {
6488 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6489 << (unsigned) FnKind << FnDesc
6490 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6491 << FromTy << (CVR - 1) << I+1;
6492 }
Sebastian Redl08905022011-02-05 19:23:19 +00006493 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006494 return;
6495 }
6496
John McCall6d174642010-01-23 08:10:49 +00006497 // Diagnose references or pointers to incomplete types differently,
6498 // since it's far from impossible that the incompleteness triggered
6499 // the failure.
6500 QualType TempFromTy = FromTy.getNonReferenceType();
6501 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6502 TempFromTy = PTy->getPointeeType();
6503 if (TempFromTy->isIncompleteType()) {
6504 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6505 << (unsigned) FnKind << FnDesc
6506 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6507 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006508 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00006509 return;
6510 }
6511
Douglas Gregor56f2e342010-06-30 23:01:39 +00006512 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006513 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006514 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6515 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6516 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6517 FromPtrTy->getPointeeType()) &&
6518 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6519 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006520 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00006521 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006522 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006523 }
6524 } else if (const ObjCObjectPointerType *FromPtrTy
6525 = FromTy->getAs<ObjCObjectPointerType>()) {
6526 if (const ObjCObjectPointerType *ToPtrTy
6527 = ToTy->getAs<ObjCObjectPointerType>())
6528 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6529 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6530 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6531 FromPtrTy->getPointeeType()) &&
6532 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006533 BaseToDerivedConversion = 2;
6534 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6535 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6536 !FromTy->isIncompleteType() &&
6537 !ToRefTy->getPointeeType()->isIncompleteType() &&
6538 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6539 BaseToDerivedConversion = 3;
6540 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006541
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006542 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006543 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006544 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006545 << (unsigned) FnKind << FnDesc
6546 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006547 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006548 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006549 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00006550 return;
6551 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006552
John McCall47000992010-01-14 03:28:57 +00006553 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006554 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6555 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006556 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006557 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006558 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00006559}
6560
6561void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6562 unsigned NumFormalArgs) {
6563 // TODO: treat calls to a missing default constructor as a special case
6564
6565 FunctionDecl *Fn = Cand->Function;
6566 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6567
6568 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006569
John McCall6a61b522010-01-13 09:16:55 +00006570 // at least / at most / exactly
6571 unsigned mode, modeCount;
6572 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006573 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6574 (Cand->FailureKind == ovl_fail_bad_deduction &&
6575 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006576 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00006577 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00006578 mode = 0; // "at least"
6579 else
6580 mode = 2; // "exactly"
6581 modeCount = MinParams;
6582 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006583 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6584 (Cand->FailureKind == ovl_fail_bad_deduction &&
6585 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006586 if (MinParams != FnTy->getNumArgs())
6587 mode = 1; // "at most"
6588 else
6589 mode = 2; // "exactly"
6590 modeCount = FnTy->getNumArgs();
6591 }
6592
6593 std::string Description;
6594 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6595
6596 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006597 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00006598 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00006599 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006600}
6601
John McCall8b9ed552010-02-01 18:53:26 +00006602/// Diagnose a failed template-argument deduction.
6603void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6604 Expr **Args, unsigned NumArgs) {
6605 FunctionDecl *Fn = Cand->Function; // pattern
6606
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006607 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006608 NamedDecl *ParamD;
6609 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6610 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6611 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006612 switch (Cand->DeductionFailure.Result) {
6613 case Sema::TDK_Success:
6614 llvm_unreachable("TDK_success while diagnosing bad deduction");
6615
6616 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006617 assert(ParamD && "no parameter found for incomplete deduction result");
6618 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6619 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00006620 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00006621 return;
6622 }
6623
John McCall42d7d192010-08-05 09:05:08 +00006624 case Sema::TDK_Underqualified: {
6625 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6626 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6627
6628 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6629
6630 // Param will have been canonicalized, but it should just be a
6631 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00006632 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00006633 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00006634 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00006635 assert(S.Context.hasSameType(Param, NonCanonParam));
6636
6637 // Arg has also been canonicalized, but there's nothing we can do
6638 // about that. It also doesn't matter as much, because it won't
6639 // have any template parameters in it (because deduction isn't
6640 // done on dependent types).
6641 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6642
6643 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6644 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00006645 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00006646 return;
6647 }
6648
6649 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00006650 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006651 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006652 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006653 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006654 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006655 which = 1;
6656 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006657 which = 2;
6658 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006659
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006660 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006661 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006662 << *Cand->DeductionFailure.getFirstArg()
6663 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00006664 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006665 return;
6666 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006667
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006668 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006669 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006670 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006671 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006672 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6673 << ParamD->getDeclName();
6674 else {
6675 int index = 0;
6676 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6677 index = TTP->getIndex();
6678 else if (NonTypeTemplateParmDecl *NTTP
6679 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6680 index = NTTP->getIndex();
6681 else
6682 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006683 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006684 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6685 << (index + 1);
6686 }
Sebastian Redl08905022011-02-05 19:23:19 +00006687 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006688 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006689
Douglas Gregor02eb4832010-05-08 18:13:28 +00006690 case Sema::TDK_TooManyArguments:
6691 case Sema::TDK_TooFewArguments:
6692 DiagnoseArityMismatch(S, Cand, NumArgs);
6693 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006694
6695 case Sema::TDK_InstantiationDepth:
6696 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00006697 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00006698 return;
6699
6700 case Sema::TDK_SubstitutionFailure: {
6701 std::string ArgString;
6702 if (TemplateArgumentList *Args
6703 = Cand->DeductionFailure.getTemplateArgumentList())
6704 ArgString = S.getTemplateArgumentBindingsText(
6705 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6706 *Args);
6707 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6708 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00006709 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00006710 return;
6711 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006712
John McCall8b9ed552010-02-01 18:53:26 +00006713 // TODO: diagnose these individually, then kill off
6714 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006715 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006716 case Sema::TDK_FailedOverloadResolution:
6717 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00006718 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00006719 return;
6720 }
6721}
6722
6723/// Generates a 'note' diagnostic for an overload candidate. We've
6724/// already generated a primary error at the call site.
6725///
6726/// It really does need to be a single diagnostic with its caret
6727/// pointed at the candidate declaration. Yes, this creates some
6728/// major challenges of technical writing. Yes, this makes pointing
6729/// out problems with specific arguments quite awkward. It's still
6730/// better than generating twenty screens of text for every failed
6731/// overload.
6732///
6733/// It would be great to be able to express per-candidate problems
6734/// more richly for those diagnostic clients that cared, but we'd
6735/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006736void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6737 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006738 FunctionDecl *Fn = Cand->Function;
6739
John McCall12f97bc2010-01-08 04:41:39 +00006740 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00006741 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006742 std::string FnDesc;
6743 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006744
6745 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006746 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00006747 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00006748 return;
John McCall12f97bc2010-01-08 04:41:39 +00006749 }
6750
John McCalle1ac8d12010-01-13 00:25:19 +00006751 // We don't really have anything else to say about viable candidates.
6752 if (Cand->Viable) {
6753 S.NoteOverloadCandidate(Fn);
6754 return;
6755 }
John McCall0d1da222010-01-12 00:44:57 +00006756
John McCall6a61b522010-01-13 09:16:55 +00006757 switch (Cand->FailureKind) {
6758 case ovl_fail_too_many_arguments:
6759 case ovl_fail_too_few_arguments:
6760 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006761
John McCall6a61b522010-01-13 09:16:55 +00006762 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006763 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6764
John McCallfe796dd2010-01-23 05:17:32 +00006765 case ovl_fail_trivial_conversion:
6766 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006767 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006768 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006769
John McCall65eb8792010-02-25 01:37:24 +00006770 case ovl_fail_bad_conversion: {
6771 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6772 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006773 if (Cand->Conversions[I].isBad())
6774 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006775
John McCall6a61b522010-01-13 09:16:55 +00006776 // FIXME: this currently happens when we're called from SemaInit
6777 // when user-conversion overload fails. Figure out how to handle
6778 // those conditions and diagnose them well.
6779 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006780 }
John McCall65eb8792010-02-25 01:37:24 +00006781 }
John McCalld3224162010-01-08 00:58:21 +00006782}
6783
6784void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6785 // Desugar the type of the surrogate down to a function type,
6786 // retaining as many typedefs as possible while still showing
6787 // the function type (and, therefore, its parameter types).
6788 QualType FnType = Cand->Surrogate->getConversionType();
6789 bool isLValueReference = false;
6790 bool isRValueReference = false;
6791 bool isPointer = false;
6792 if (const LValueReferenceType *FnTypeRef =
6793 FnType->getAs<LValueReferenceType>()) {
6794 FnType = FnTypeRef->getPointeeType();
6795 isLValueReference = true;
6796 } else if (const RValueReferenceType *FnTypeRef =
6797 FnType->getAs<RValueReferenceType>()) {
6798 FnType = FnTypeRef->getPointeeType();
6799 isRValueReference = true;
6800 }
6801 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6802 FnType = FnTypePtr->getPointeeType();
6803 isPointer = true;
6804 }
6805 // Desugar down to a function type.
6806 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6807 // Reconstruct the pointer/reference as appropriate.
6808 if (isPointer) FnType = S.Context.getPointerType(FnType);
6809 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6810 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6811
6812 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6813 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00006814 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00006815}
6816
6817void NoteBuiltinOperatorCandidate(Sema &S,
6818 const char *Opc,
6819 SourceLocation OpLoc,
6820 OverloadCandidate *Cand) {
6821 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6822 std::string TypeStr("operator");
6823 TypeStr += Opc;
6824 TypeStr += "(";
6825 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6826 if (Cand->Conversions.size() == 1) {
6827 TypeStr += ")";
6828 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6829 } else {
6830 TypeStr += ", ";
6831 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6832 TypeStr += ")";
6833 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6834 }
6835}
6836
6837void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6838 OverloadCandidate *Cand) {
6839 unsigned NoOperands = Cand->Conversions.size();
6840 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6841 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006842 if (ICS.isBad()) break; // all meaningless after first invalid
6843 if (!ICS.isAmbiguous()) continue;
6844
John McCall5c32be02010-08-24 20:38:10 +00006845 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006846 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006847 }
6848}
6849
John McCall3712d9e2010-01-15 23:32:50 +00006850SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6851 if (Cand->Function)
6852 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006853 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006854 return Cand->Surrogate->getLocation();
6855 return SourceLocation();
6856}
6857
John McCallad2587a2010-01-12 00:48:53 +00006858struct CompareOverloadCandidatesForDisplay {
6859 Sema &S;
6860 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006861
6862 bool operator()(const OverloadCandidate *L,
6863 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006864 // Fast-path this check.
6865 if (L == R) return false;
6866
John McCall12f97bc2010-01-08 04:41:39 +00006867 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006868 if (L->Viable) {
6869 if (!R->Viable) return true;
6870
6871 // TODO: introduce a tri-valued comparison for overload
6872 // candidates. Would be more worthwhile if we had a sort
6873 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006874 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6875 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006876 } else if (R->Viable)
6877 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006878
John McCall3712d9e2010-01-15 23:32:50 +00006879 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006880
John McCall3712d9e2010-01-15 23:32:50 +00006881 // Criteria by which we can sort non-viable candidates:
6882 if (!L->Viable) {
6883 // 1. Arity mismatches come after other candidates.
6884 if (L->FailureKind == ovl_fail_too_many_arguments ||
6885 L->FailureKind == ovl_fail_too_few_arguments)
6886 return false;
6887 if (R->FailureKind == ovl_fail_too_many_arguments ||
6888 R->FailureKind == ovl_fail_too_few_arguments)
6889 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006890
John McCallfe796dd2010-01-23 05:17:32 +00006891 // 2. Bad conversions come first and are ordered by the number
6892 // of bad conversions and quality of good conversions.
6893 if (L->FailureKind == ovl_fail_bad_conversion) {
6894 if (R->FailureKind != ovl_fail_bad_conversion)
6895 return true;
6896
6897 // If there's any ordering between the defined conversions...
6898 // FIXME: this might not be transitive.
6899 assert(L->Conversions.size() == R->Conversions.size());
6900
6901 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006902 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6903 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006904 switch (CompareImplicitConversionSequences(S,
6905 L->Conversions[I],
6906 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006907 case ImplicitConversionSequence::Better:
6908 leftBetter++;
6909 break;
6910
6911 case ImplicitConversionSequence::Worse:
6912 leftBetter--;
6913 break;
6914
6915 case ImplicitConversionSequence::Indistinguishable:
6916 break;
6917 }
6918 }
6919 if (leftBetter > 0) return true;
6920 if (leftBetter < 0) return false;
6921
6922 } else if (R->FailureKind == ovl_fail_bad_conversion)
6923 return false;
6924
John McCall3712d9e2010-01-15 23:32:50 +00006925 // TODO: others?
6926 }
6927
6928 // Sort everything else by location.
6929 SourceLocation LLoc = GetLocationForCandidate(L);
6930 SourceLocation RLoc = GetLocationForCandidate(R);
6931
6932 // Put candidates without locations (e.g. builtins) at the end.
6933 if (LLoc.isInvalid()) return false;
6934 if (RLoc.isInvalid()) return true;
6935
6936 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006937 }
6938};
6939
John McCallfe796dd2010-01-23 05:17:32 +00006940/// CompleteNonViableCandidate - Normally, overload resolution only
6941/// computes up to the first
6942void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6943 Expr **Args, unsigned NumArgs) {
6944 assert(!Cand->Viable);
6945
6946 // Don't do anything on failures other than bad conversion.
6947 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6948
6949 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006950 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006951 unsigned ConvCount = Cand->Conversions.size();
6952 while (true) {
6953 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6954 ConvIdx++;
6955 if (Cand->Conversions[ConvIdx - 1].isBad())
6956 break;
6957 }
6958
6959 if (ConvIdx == ConvCount)
6960 return;
6961
John McCall65eb8792010-02-25 01:37:24 +00006962 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6963 "remaining conversion is initialized?");
6964
Douglas Gregoradc7a702010-04-16 17:45:54 +00006965 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006966 // operation somehow.
6967 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006968
6969 const FunctionProtoType* Proto;
6970 unsigned ArgIdx = ConvIdx;
6971
6972 if (Cand->IsSurrogate) {
6973 QualType ConvType
6974 = Cand->Surrogate->getConversionType().getNonReferenceType();
6975 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6976 ConvType = ConvPtrType->getPointeeType();
6977 Proto = ConvType->getAs<FunctionProtoType>();
6978 ArgIdx--;
6979 } else if (Cand->Function) {
6980 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6981 if (isa<CXXMethodDecl>(Cand->Function) &&
6982 !isa<CXXConstructorDecl>(Cand->Function))
6983 ArgIdx--;
6984 } else {
6985 // Builtin binary operator with a bad first conversion.
6986 assert(ConvCount <= 3);
6987 for (; ConvIdx != ConvCount; ++ConvIdx)
6988 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006989 = TryCopyInitialization(S, Args[ConvIdx],
6990 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006991 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006992 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006993 return;
6994 }
6995
6996 // Fill in the rest of the conversions.
6997 unsigned NumArgsInProto = Proto->getNumArgs();
6998 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6999 if (ArgIdx < NumArgsInProto)
7000 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007001 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007002 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007003 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00007004 else
7005 Cand->Conversions[ConvIdx].setEllipsis();
7006 }
7007}
7008
John McCalld3224162010-01-08 00:58:21 +00007009} // end anonymous namespace
7010
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007011/// PrintOverloadCandidates - When overload resolution fails, prints
7012/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007013/// set.
John McCall5c32be02010-08-24 20:38:10 +00007014void OverloadCandidateSet::NoteCandidates(Sema &S,
7015 OverloadCandidateDisplayKind OCD,
7016 Expr **Args, unsigned NumArgs,
7017 const char *Opc,
7018 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007019 // Sort the candidates by viability and position. Sorting directly would
7020 // be prohibitive, so we make a set of pointers and sort those.
7021 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007022 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7023 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007024 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007025 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007026 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007027 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007028 if (Cand->Function || Cand->IsSurrogate)
7029 Cands.push_back(Cand);
7030 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7031 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007032 }
7033 }
7034
John McCallad2587a2010-01-12 00:48:53 +00007035 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007036 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007037
John McCall0d1da222010-01-12 00:44:57 +00007038 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007039
John McCall12f97bc2010-01-08 04:41:39 +00007040 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00007041 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007042 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007043 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7044 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007045
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007046 // Set an arbitrary limit on the number of candidate functions we'll spam
7047 // the user with. FIXME: This limit should depend on details of the
7048 // candidate list.
7049 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7050 break;
7051 }
7052 ++CandsShown;
7053
John McCalld3224162010-01-08 00:58:21 +00007054 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007055 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007056 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007057 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007058 else {
7059 assert(Cand->Viable &&
7060 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007061 // Generally we only see ambiguities including viable builtin
7062 // operators if overload resolution got screwed up by an
7063 // ambiguous user-defined conversion.
7064 //
7065 // FIXME: It's quite possible for different conversions to see
7066 // different ambiguities, though.
7067 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007068 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007069 ReportedAmbiguousConversions = true;
7070 }
John McCalld3224162010-01-08 00:58:21 +00007071
John McCall0d1da222010-01-12 00:44:57 +00007072 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007073 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007074 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007075 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007076
7077 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007078 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007079}
7080
Douglas Gregorb491ed32011-02-19 21:32:49 +00007081// [PossiblyAFunctionType] --> [Return]
7082// NonFunctionType --> NonFunctionType
7083// R (A) --> R(A)
7084// R (*)(A) --> R (A)
7085// R (&)(A) --> R (A)
7086// R (S::*)(A) --> R (A)
7087QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7088 QualType Ret = PossiblyAFunctionType;
7089 if (const PointerType *ToTypePtr =
7090 PossiblyAFunctionType->getAs<PointerType>())
7091 Ret = ToTypePtr->getPointeeType();
7092 else if (const ReferenceType *ToTypeRef =
7093 PossiblyAFunctionType->getAs<ReferenceType>())
7094 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007095 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007096 PossiblyAFunctionType->getAs<MemberPointerType>())
7097 Ret = MemTypePtr->getPointeeType();
7098 Ret =
7099 Context.getCanonicalType(Ret).getUnqualifiedType();
7100 return Ret;
7101}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007102
Douglas Gregorb491ed32011-02-19 21:32:49 +00007103// A helper class to help with address of function resolution
7104// - allows us to avoid passing around all those ugly parameters
7105class AddressOfFunctionResolver
7106{
7107 Sema& S;
7108 Expr* SourceExpr;
7109 const QualType& TargetType;
7110 QualType TargetFunctionType; // Extracted function type from target type
7111
7112 bool Complain;
7113 //DeclAccessPair& ResultFunctionAccessPair;
7114 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007115
Douglas Gregorb491ed32011-02-19 21:32:49 +00007116 bool TargetTypeIsNonStaticMemberFunction;
7117 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007118
Douglas Gregorb491ed32011-02-19 21:32:49 +00007119 OverloadExpr::FindResult OvlExprInfo;
7120 OverloadExpr *OvlExpr;
7121 TemplateArgumentListInfo OvlExplicitTemplateArgs;
John McCalla0296f72010-03-19 07:35:19 +00007122 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007123
Douglas Gregorb491ed32011-02-19 21:32:49 +00007124public:
7125 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7126 const QualType& TargetType, bool Complain)
7127 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7128 Complain(Complain), Context(S.getASTContext()),
7129 TargetTypeIsNonStaticMemberFunction(
7130 !!TargetType->getAs<MemberPointerType>()),
7131 FoundNonTemplateFunction(false),
7132 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7133 OvlExpr(OvlExprInfo.Expression)
7134 {
7135 ExtractUnqualifiedFunctionTypeFromTargetType();
7136
7137 if (!TargetFunctionType->isFunctionType()) {
7138 if (OvlExpr->hasExplicitTemplateArgs()) {
7139 DeclAccessPair dap;
7140 if( FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
7141 OvlExpr, false, &dap) ) {
7142 Matches.push_back(std::make_pair(dap,Fn));
7143 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007144 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007145 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007146 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007147
7148 if (OvlExpr->hasExplicitTemplateArgs())
7149 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007150
Douglas Gregorb491ed32011-02-19 21:32:49 +00007151 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7152 // C++ [over.over]p4:
7153 // If more than one function is selected, [...]
7154 if (Matches.size() > 1) {
7155 if (FoundNonTemplateFunction)
7156 EliminateAllTemplateMatches();
7157 else
7158 EliminateAllExceptMostSpecializedTemplate();
7159 }
7160 }
7161 }
7162
7163private:
7164 bool isTargetTypeAFunction() const {
7165 return TargetFunctionType->isFunctionType();
7166 }
7167
7168 // [ToType] [Return]
7169
7170 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7171 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7172 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7173 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7174 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7175 }
7176
7177 // return true if any matching specializations were found
7178 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7179 const DeclAccessPair& CurAccessFunPair) {
7180 if (CXXMethodDecl *Method
7181 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7182 // Skip non-static function templates when converting to pointer, and
7183 // static when converting to member pointer.
7184 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7185 return false;
7186 }
7187 else if (TargetTypeIsNonStaticMemberFunction)
7188 return false;
7189
7190 // C++ [over.over]p2:
7191 // If the name is a function template, template argument deduction is
7192 // done (14.8.2.2), and if the argument deduction succeeds, the
7193 // resulting template argument list is used to generate a single
7194 // function template specialization, which is added to the set of
7195 // overloaded functions considered.
7196 FunctionDecl *Specialization = 0;
7197 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7198 if (Sema::TemplateDeductionResult Result
7199 = S.DeduceTemplateArguments(FunctionTemplate,
7200 &OvlExplicitTemplateArgs,
7201 TargetFunctionType, Specialization,
7202 Info)) {
7203 // FIXME: make a note of the failed deduction for diagnostics.
7204 (void)Result;
7205 return false;
7206 }
7207
7208 // Template argument deduction ensures that we have an exact match.
7209 // This function template specicalization works.
7210 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7211 assert(TargetFunctionType
7212 == Context.getCanonicalType(Specialization->getType()));
7213 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7214 return true;
7215 }
7216
7217 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7218 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007219 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007220 // Skip non-static functions when converting to pointer, and static
7221 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007222 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7223 return false;
7224 }
7225 else if (TargetTypeIsNonStaticMemberFunction)
7226 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007227
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007228 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007229 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007230 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7231 FunDecl->getType()) ||
7232 IsNoReturnConversion(Context, FunDecl->getType(), TargetFunctionType,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007233 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007234 Matches.push_back(std::make_pair(CurAccessFunPair,
7235 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007236 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007237 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007238 }
Mike Stump11289f42009-09-09 15:08:12 +00007239 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007240
7241 return false;
7242 }
7243
7244 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7245 bool Ret = false;
7246
7247 // If the overload expression doesn't have the form of a pointer to
7248 // member, don't try to convert it to a pointer-to-member type.
7249 if (IsInvalidFormOfPointerToMemberFunction())
7250 return false;
7251
7252 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7253 E = OvlExpr->decls_end();
7254 I != E; ++I) {
7255 // Look through any using declarations to find the underlying function.
7256 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7257
7258 // C++ [over.over]p3:
7259 // Non-member functions and static member functions match
7260 // targets of type "pointer-to-function" or "reference-to-function."
7261 // Nonstatic member functions match targets of
7262 // type "pointer-to-member-function."
7263 // Note that according to DR 247, the containing class does not matter.
7264 if (FunctionTemplateDecl *FunctionTemplate
7265 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7266 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7267 Ret = true;
7268 }
7269 // If we have explicit template arguments supplied, skip non-templates.
7270 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7271 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7272 Ret = true;
7273 }
7274 assert(Ret || Matches.empty());
7275 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007276 }
7277
Douglas Gregorb491ed32011-02-19 21:32:49 +00007278 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00007279 // [...] and any given function template specialization F1 is
7280 // eliminated if the set contains a second function template
7281 // specialization whose function template is more specialized
7282 // than the function template of F1 according to the partial
7283 // ordering rules of 14.5.5.2.
7284
7285 // The algorithm specified above is quadratic. We instead use a
7286 // two-pass algorithm (similar to the one used to identify the
7287 // best viable function in an overload set) that identifies the
7288 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007289
7290 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7291 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7292 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007293
John McCall58cc69d2010-01-27 01:50:18 +00007294 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007295 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7296 TPOC_Other, 0, SourceExpr->getLocStart(),
7297 S.PDiag(),
7298 S.PDiag(diag::err_addr_ovl_ambiguous)
7299 << Matches[0].second->getDeclName(),
7300 S.PDiag(diag::note_ovl_candidate)
7301 << (unsigned) oc_function_template,
7302 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007303
Douglas Gregorb491ed32011-02-19 21:32:49 +00007304 if (Result != MatchesCopy.end()) {
7305 // Make it the first and only element
7306 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7307 Matches[0].second = cast<FunctionDecl>(*Result);
7308 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00007309 }
7310 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007311
Douglas Gregorb491ed32011-02-19 21:32:49 +00007312 void EliminateAllTemplateMatches() {
7313 // [...] any function template specializations in the set are
7314 // eliminated if the set also contains a non-template function, [...]
7315 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7316 if (Matches[I].second->getPrimaryTemplate() == 0)
7317 ++I;
7318 else {
7319 Matches[I] = Matches[--N];
7320 Matches.set_size(N);
7321 }
7322 }
7323 }
7324
7325public:
7326 void ComplainNoMatchesFound() const {
7327 assert(Matches.empty());
7328 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7329 << OvlExpr->getName() << TargetFunctionType
7330 << OvlExpr->getSourceRange();
7331 S.NoteAllOverloadCandidates(OvlExpr);
7332 }
7333
7334 bool IsInvalidFormOfPointerToMemberFunction() const {
7335 return TargetTypeIsNonStaticMemberFunction &&
7336 !OvlExprInfo.HasFormOfMemberPointer;
7337 }
7338
7339 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7340 // TODO: Should we condition this on whether any functions might
7341 // have matched, or is it more appropriate to do that in callers?
7342 // TODO: a fixit wouldn't hurt.
7343 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7344 << TargetType << OvlExpr->getSourceRange();
7345 }
7346
7347 void ComplainOfInvalidConversion() const {
7348 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7349 << OvlExpr->getName() << TargetType;
7350 }
7351
7352 void ComplainMultipleMatchesFound() const {
7353 assert(Matches.size() > 1);
7354 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7355 << OvlExpr->getName()
7356 << OvlExpr->getSourceRange();
7357 S.NoteAllOverloadCandidates(OvlExpr);
7358 }
7359
7360 int getNumMatches() const { return Matches.size(); }
7361
7362 FunctionDecl* getMatchingFunctionDecl() const {
7363 if (Matches.size() != 1) return 0;
7364 return Matches[0].second;
7365 }
7366
7367 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7368 if (Matches.size() != 1) return 0;
7369 return &Matches[0].first;
7370 }
7371};
7372
7373/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7374/// an overloaded function (C++ [over.over]), where @p From is an
7375/// expression with overloaded function type and @p ToType is the type
7376/// we're trying to resolve to. For example:
7377///
7378/// @code
7379/// int f(double);
7380/// int f(int);
7381///
7382/// int (*pfd)(double) = f; // selects f(double)
7383/// @endcode
7384///
7385/// This routine returns the resulting FunctionDecl if it could be
7386/// resolved, and NULL otherwise. When @p Complain is true, this
7387/// routine will emit diagnostics if there is an error.
7388FunctionDecl *
7389Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7390 bool Complain,
7391 DeclAccessPair &FoundResult) {
7392
7393 assert(AddressOfExpr->getType() == Context.OverloadTy);
7394
7395 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7396 int NumMatches = Resolver.getNumMatches();
7397 FunctionDecl* Fn = 0;
7398 if ( NumMatches == 0 && Complain) {
7399 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7400 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7401 else
7402 Resolver.ComplainNoMatchesFound();
7403 }
7404 else if (NumMatches > 1 && Complain)
7405 Resolver.ComplainMultipleMatchesFound();
7406 else if (NumMatches == 1) {
7407 Fn = Resolver.getMatchingFunctionDecl();
7408 assert(Fn);
7409 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7410 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007411 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00007412 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007413 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007414
7415 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007416}
7417
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007418/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007419/// resolve that overloaded function expression down to a single function.
7420///
7421/// This routine can only resolve template-ids that refer to a single function
7422/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007423/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007424/// as described in C++0x [temp.arg.explicit]p3.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007425FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From,
7426 bool Complain,
7427 DeclAccessPair* FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007428 // C++ [over.over]p1:
7429 // [...] [Note: any redundant set of parentheses surrounding the
7430 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007431 // C++ [over.over]p1:
7432 // [...] The overloaded function name can be preceded by the &
7433 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00007434 if (From->getType() != Context.OverloadTy)
7435 return 0;
7436
John McCall8d08b9b2010-08-27 09:08:28 +00007437 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007438
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007439 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00007440 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007441 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007442
7443 TemplateArgumentListInfo ExplicitTemplateArgs;
7444 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007445
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007446 // Look through all of the overloaded functions, searching for one
7447 // whose type matches exactly.
7448 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00007449 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7450 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007451 // C++0x [temp.arg.explicit]p3:
7452 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007453 // where deduction is not done, if a template argument list is
7454 // specified and it, along with any default template arguments,
7455 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007456 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00007457 FunctionTemplateDecl *FunctionTemplate
7458 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007459
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007460 // C++ [over.over]p2:
7461 // If the name is a function template, template argument deduction is
7462 // done (14.8.2.2), and if the argument deduction succeeds, the
7463 // resulting template argument list is used to generate a single
7464 // function template specialization, which is added to the set of
7465 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007466 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00007467 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007468 if (TemplateDeductionResult Result
7469 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7470 Specialization, Info)) {
7471 // FIXME: make a note of the failed deduction for diagnostics.
7472 (void)Result;
7473 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007474 }
7475
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007476 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007477 if (Matched) {
7478 if (FoundResult)
7479 *FoundResult = DeclAccessPair();
7480
7481 if (Complain) {
7482 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
7483 << OvlExpr->getName();
7484 NoteAllOverloadCandidates(OvlExpr);
7485 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007486 return 0;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007487 }
7488
7489 if ((Matched = Specialization) && FoundResult)
7490 *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007491 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007492
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007493 return Matched;
7494}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007495
Douglas Gregorcabea402009-09-22 15:41:20 +00007496/// \brief Add a single candidate to the overload set.
7497static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00007498 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00007499 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007500 Expr **Args, unsigned NumArgs,
7501 OverloadCandidateSet &CandidateSet,
7502 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00007503 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00007504 if (isa<UsingShadowDecl>(Callee))
7505 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7506
Douglas Gregorcabea402009-09-22 15:41:20 +00007507 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00007508 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00007509 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007510 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007511 return;
John McCalld14a8642009-11-21 08:51:07 +00007512 }
7513
7514 if (FunctionTemplateDecl *FuncTemplate
7515 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00007516 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7517 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007518 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00007519 return;
7520 }
7521
7522 assert(false && "unhandled case in overloaded call candidate");
7523
7524 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00007525}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007526
Douglas Gregorcabea402009-09-22 15:41:20 +00007527/// \brief Add the overload candidates named by callee and/or found by argument
7528/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00007529void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00007530 Expr **Args, unsigned NumArgs,
7531 OverloadCandidateSet &CandidateSet,
7532 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00007533
7534#ifndef NDEBUG
7535 // Verify that ArgumentDependentLookup is consistent with the rules
7536 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00007537 //
Douglas Gregorcabea402009-09-22 15:41:20 +00007538 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7539 // and let Y be the lookup set produced by argument dependent
7540 // lookup (defined as follows). If X contains
7541 //
7542 // -- a declaration of a class member, or
7543 //
7544 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00007545 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00007546 //
7547 // -- a declaration that is neither a function or a function
7548 // template
7549 //
7550 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00007551
John McCall57500772009-12-16 12:17:52 +00007552 if (ULE->requiresADL()) {
7553 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7554 E = ULE->decls_end(); I != E; ++I) {
7555 assert(!(*I)->getDeclContext()->isRecord());
7556 assert(isa<UsingShadowDecl>(*I) ||
7557 !(*I)->getDeclContext()->isFunctionOrMethod());
7558 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00007559 }
7560 }
7561#endif
7562
John McCall57500772009-12-16 12:17:52 +00007563 // It would be nice to avoid this copy.
7564 TemplateArgumentListInfo TABuffer;
7565 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7566 if (ULE->hasExplicitTemplateArgs()) {
7567 ULE->copyTemplateArgumentsInto(TABuffer);
7568 ExplicitTemplateArgs = &TABuffer;
7569 }
7570
7571 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7572 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00007573 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007574 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00007575 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00007576
John McCall57500772009-12-16 12:17:52 +00007577 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00007578 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7579 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007580 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007581 CandidateSet,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007582 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007583}
John McCalld681c392009-12-16 08:11:27 +00007584
7585/// Attempts to recover from a call where no functions were found.
7586///
7587/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00007588static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007589BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00007590 UnresolvedLookupExpr *ULE,
7591 SourceLocation LParenLoc,
7592 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007593 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00007594
7595 CXXScopeSpec SS;
Douglas Gregor2ab3fee2011-02-24 00:49:34 +00007596 if (ULE->getQualifier())
Douglas Gregor869ad452011-02-24 17:54:50 +00007597 SS.MakeTrivial(SemaRef.Context,
7598 ULE->getQualifier(), ULE->getQualifierRange());
John McCalld681c392009-12-16 08:11:27 +00007599
John McCall57500772009-12-16 12:17:52 +00007600 TemplateArgumentListInfo TABuffer;
7601 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7602 if (ULE->hasExplicitTemplateArgs()) {
7603 ULE->copyTemplateArgumentsInto(TABuffer);
7604 ExplicitTemplateArgs = &TABuffer;
7605 }
7606
John McCalld681c392009-12-16 08:11:27 +00007607 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7608 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00007609 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00007610 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00007611
John McCall57500772009-12-16 12:17:52 +00007612 assert(!R.empty() && "lookup results empty despite recovery");
7613
7614 // Build an implicit member call if appropriate. Just drop the
7615 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00007616 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00007617 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00007618 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7619 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00007620 else if (ExplicitTemplateArgs)
7621 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7622 else
7623 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7624
7625 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007626 return ExprError();
John McCall57500772009-12-16 12:17:52 +00007627
7628 // This shouldn't cause an infinite loop because we're giving it
7629 // an expression with non-empty lookup results, which should never
7630 // end up here.
John McCallb268a282010-08-23 23:25:46 +00007631 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007632 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007633}
Douglas Gregor4038cf42010-06-08 17:35:15 +00007634
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007635/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00007636/// (which eventually refers to the declaration Func) and the call
7637/// arguments Args/NumArgs, attempt to resolve the function call down
7638/// to a specific function. If overload resolution succeeds, returns
7639/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00007640/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007641/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00007642ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007643Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00007644 SourceLocation LParenLoc,
7645 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00007646 SourceLocation RParenLoc,
7647 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00007648#ifndef NDEBUG
7649 if (ULE->requiresADL()) {
7650 // To do ADL, we must have found an unqualified name.
7651 assert(!ULE->getQualifier() && "qualified name with ADL");
7652
7653 // We don't perform ADL for implicit declarations of builtins.
7654 // Verify that this was correctly set up.
7655 FunctionDecl *F;
7656 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7657 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7658 F->getBuiltinID() && F->isImplicit())
7659 assert(0 && "performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007660
John McCall57500772009-12-16 12:17:52 +00007661 // We don't perform ADL in C.
7662 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7663 }
7664#endif
7665
John McCallbc077cf2010-02-08 23:07:23 +00007666 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007667
John McCall57500772009-12-16 12:17:52 +00007668 // Add the functions denoted by the callee to the set of candidate
7669 // functions, including those from argument-dependent lookup.
7670 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007671
7672 // If we found nothing, try to recover.
7673 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7674 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007675 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007676 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007677 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007678
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007679 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007680 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007681 case OR_Success: {
7682 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00007683 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007684 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7685 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007686 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00007687 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
7688 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00007689 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007690
7691 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007692 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007693 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007694 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007695 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007696 break;
7697
7698 case OR_Ambiguous:
7699 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007700 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007701 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007702 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007703
7704 case OR_Deleted:
7705 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7706 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00007707 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00007708 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007709 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007710 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007711 }
7712
Douglas Gregorb412e172010-07-25 18:17:45 +00007713 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007714 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007715}
7716
John McCall4c4c1df2010-01-26 03:27:55 +00007717static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007718 return Functions.size() > 1 ||
7719 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7720}
7721
Douglas Gregor084d8552009-03-13 23:49:33 +00007722/// \brief Create a unary operation that may resolve to an overloaded
7723/// operator.
7724///
7725/// \param OpLoc The location of the operator itself (e.g., '*').
7726///
7727/// \param OpcIn The UnaryOperator::Opcode that describes this
7728/// operator.
7729///
7730/// \param Functions The set of non-member functions that will be
7731/// considered by overload resolution. The caller needs to build this
7732/// set based on the context using, e.g.,
7733/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7734/// set should not contain any member functions; those will be added
7735/// by CreateOverloadedUnaryOp().
7736///
7737/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007738ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007739Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7740 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007741 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007742 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007743
7744 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7745 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7746 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007747 // TODO: provide better source location info.
7748 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007749
John McCalle26a8722010-12-04 08:14:53 +00007750 if (Input->getObjectKind() == OK_ObjCProperty)
7751 ConvertPropertyForRValue(Input);
7752
Douglas Gregor084d8552009-03-13 23:49:33 +00007753 Expr *Args[2] = { Input, 0 };
7754 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007755
Douglas Gregor084d8552009-03-13 23:49:33 +00007756 // For post-increment and post-decrement, add the implicit '0' as
7757 // the second argument, so that we know this is a post-increment or
7758 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007759 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007760 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007761 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7762 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007763 NumArgs = 2;
7764 }
7765
7766 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007767 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007768 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007769 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00007770 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007771 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00007772 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007773
John McCall58cc69d2010-01-27 01:50:18 +00007774 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007775 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007776 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007777 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007778 /*ADL*/ true, IsOverloaded(Fns),
7779 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007780 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7781 &Args[0], NumArgs,
7782 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007783 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00007784 OpLoc));
7785 }
7786
7787 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007788 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007789
7790 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007791 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007792
7793 // Add operator candidates that are member functions.
7794 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7795
John McCall4c4c1df2010-01-26 03:27:55 +00007796 // Add candidates from ADL.
7797 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007798 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007799 /*ExplicitTemplateArgs*/ 0,
7800 CandidateSet);
7801
Douglas Gregor084d8552009-03-13 23:49:33 +00007802 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007803 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007804
7805 // Perform overload resolution.
7806 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007807 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007808 case OR_Success: {
7809 // We found a built-in operator or an overloaded operator.
7810 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007811
Douglas Gregor084d8552009-03-13 23:49:33 +00007812 if (FnDecl) {
7813 // We matched an overloaded operator. Build a call to that
7814 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007815
Douglas Gregor084d8552009-03-13 23:49:33 +00007816 // Convert the arguments.
7817 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007818 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007819
John McCall16df1e52010-03-30 21:47:33 +00007820 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7821 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007822 return ExprError();
7823 } else {
7824 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007825 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007826 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007827 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007828 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007829 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007830 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007831 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007832 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007833 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007834 }
7835
John McCall4fa0d5f2010-05-06 18:15:07 +00007836 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7837
John McCall7decc9e2010-11-18 06:31:45 +00007838 // Determine the result type.
7839 QualType ResultTy = FnDecl->getResultType();
7840 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7841 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00007842
Douglas Gregor084d8552009-03-13 23:49:33 +00007843 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007844 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007845
Eli Friedman030eee42009-11-18 03:58:17 +00007846 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007847 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007848 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007849 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007850
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007851 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007852 FnDecl))
7853 return ExprError();
7854
John McCallb268a282010-08-23 23:25:46 +00007855 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007856 } else {
7857 // We matched a built-in operator. Convert the arguments, then
7858 // break out so that we will build the appropriate built-in
7859 // operator node.
7860 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007861 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007862 return ExprError();
7863
7864 break;
7865 }
7866 }
7867
7868 case OR_No_Viable_Function:
7869 // No viable function; fall through to handling this as a
7870 // built-in operator, which will produce an error message for us.
7871 break;
7872
7873 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007874 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregor084d8552009-03-13 23:49:33 +00007875 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007876 << Input->getType()
Douglas Gregor084d8552009-03-13 23:49:33 +00007877 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007878 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7879 Args, NumArgs,
7880 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007881 return ExprError();
7882
7883 case OR_Deleted:
7884 Diag(OpLoc, diag::err_ovl_deleted_oper)
7885 << Best->Function->isDeleted()
7886 << UnaryOperator::getOpcodeStr(Opc)
7887 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007888 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007889 return ExprError();
7890 }
7891
7892 // Either we found no viable overloaded operator or we matched a
7893 // built-in operator. In either case, fall through to trying to
7894 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007895 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007896}
7897
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007898/// \brief Create a binary operation that may resolve to an overloaded
7899/// operator.
7900///
7901/// \param OpLoc The location of the operator itself (e.g., '+').
7902///
7903/// \param OpcIn The BinaryOperator::Opcode that describes this
7904/// operator.
7905///
7906/// \param Functions The set of non-member functions that will be
7907/// considered by overload resolution. The caller needs to build this
7908/// set based on the context using, e.g.,
7909/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7910/// set should not contain any member functions; those will be added
7911/// by CreateOverloadedBinOp().
7912///
7913/// \param LHS Left-hand argument.
7914/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00007915ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007916Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007917 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00007918 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007919 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007920 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00007921 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007922
7923 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7924 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7925 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7926
7927 // If either side is type-dependent, create an appropriate dependent
7928 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00007929 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00007930 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007931 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00007932 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00007933 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00007934 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00007935 Context.DependentTy,
7936 VK_RValue, OK_Ordinary,
7937 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007938
Douglas Gregor5287f092009-11-05 00:51:44 +00007939 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7940 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007941 VK_LValue,
7942 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00007943 Context.DependentTy,
7944 Context.DependentTy,
7945 OpLoc));
7946 }
John McCall4c4c1df2010-01-26 03:27:55 +00007947
7948 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00007949 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007950 // TODO: provide better source location info in DNLoc component.
7951 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00007952 UnresolvedLookupExpr *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007953 = UnresolvedLookupExpr::Create(Context, NamingClass, 0, SourceRange(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00007954 OpNameInfo, /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007955 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007956 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00007957 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007958 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007959 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007960 OpLoc));
7961 }
7962
John McCalle26a8722010-12-04 08:14:53 +00007963 // Always do property rvalue conversions on the RHS.
7964 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7965 ConvertPropertyForRValue(Args[1]);
7966
7967 // The LHS is more complicated.
7968 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
7969
7970 // There's a tension for assignment operators between primitive
7971 // property assignment and the overloaded operators.
7972 if (BinaryOperator::isAssignmentOp(Opc)) {
7973 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7974
7975 // Is the property "logically" settable?
7976 bool Settable = (PRE->isExplicitProperty() ||
7977 PRE->getImplicitPropertySetter());
7978
7979 // To avoid gratuitously inventing semantics, use the primitive
7980 // unless it isn't. Thoughts in case we ever really care:
7981 // - If the property isn't logically settable, we have to
7982 // load and hope.
7983 // - If the property is settable and this is simple assignment,
7984 // we really should use the primitive.
7985 // - If the property is settable, then we could try overloading
7986 // on a generic lvalue of the appropriate type; if it works
7987 // out to a builtin candidate, we would do that same operation
7988 // on the property, and otherwise just error.
7989 if (Settable)
7990 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7991 }
7992
7993 ConvertPropertyForRValue(Args[0]);
7994 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007995
Sebastian Redl6a96bf72009-11-18 23:10:33 +00007996 // If this is the assignment operator, we only perform overload resolution
7997 // if the left-hand side is a class or enumeration type. This is actually
7998 // a hack. The standard requires that we do overload resolution between the
7999 // various built-in candidates, but as DR507 points out, this can lead to
8000 // problems. So we do it this way, which pretty much follows what GCC does.
8001 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00008002 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00008003 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008004
John McCalle26a8722010-12-04 08:14:53 +00008005 // If this is the .* operator, which is not overloadable, just
8006 // create a built-in binary operator.
8007 if (Opc == BO_PtrMemD)
8008 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8009
Douglas Gregor084d8552009-03-13 23:49:33 +00008010 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008011 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008012
8013 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008014 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008015
8016 // Add operator candidates that are member functions.
8017 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8018
John McCall4c4c1df2010-01-26 03:27:55 +00008019 // Add candidates from ADL.
8020 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8021 Args, 2,
8022 /*ExplicitTemplateArgs*/ 0,
8023 CandidateSet);
8024
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008025 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008026 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008027
8028 // Perform overload resolution.
8029 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008030 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00008031 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008032 // We found a built-in operator or an overloaded operator.
8033 FunctionDecl *FnDecl = Best->Function;
8034
8035 if (FnDecl) {
8036 // We matched an overloaded operator. Build a call to that
8037 // operator.
8038
8039 // Convert the arguments.
8040 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00008041 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00008042 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008043
Chandler Carruth8e543b32010-12-12 08:17:55 +00008044 ExprResult Arg1 =
8045 PerformCopyInitialization(
8046 InitializedEntity::InitializeParameter(Context,
8047 FnDecl->getParamDecl(0)),
8048 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008049 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008050 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008051
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008052 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008053 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008054 return ExprError();
8055
8056 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008057 } else {
8058 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00008059 ExprResult Arg0 = PerformCopyInitialization(
8060 InitializedEntity::InitializeParameter(Context,
8061 FnDecl->getParamDecl(0)),
8062 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008063 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008064 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008065
Chandler Carruth8e543b32010-12-12 08:17:55 +00008066 ExprResult Arg1 =
8067 PerformCopyInitialization(
8068 InitializedEntity::InitializeParameter(Context,
8069 FnDecl->getParamDecl(1)),
8070 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008071 if (Arg1.isInvalid())
8072 return ExprError();
8073 Args[0] = LHS = Arg0.takeAs<Expr>();
8074 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008075 }
8076
John McCall4fa0d5f2010-05-06 18:15:07 +00008077 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8078
John McCall7decc9e2010-11-18 06:31:45 +00008079 // Determine the result type.
8080 QualType ResultTy = FnDecl->getResultType();
8081 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8082 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008083
8084 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00008085 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008086
John McCallb268a282010-08-23 23:25:46 +00008087 CXXOperatorCallExpr *TheCall =
8088 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008089 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008090
8091 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008092 FnDecl))
8093 return ExprError();
8094
John McCallb268a282010-08-23 23:25:46 +00008095 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008096 } else {
8097 // We matched a built-in operator. Convert the arguments, then
8098 // break out so that we will build the appropriate built-in
8099 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00008100 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008101 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00008102 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008103 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008104 return ExprError();
8105
8106 break;
8107 }
8108 }
8109
Douglas Gregor66950a32009-09-30 21:46:01 +00008110 case OR_No_Viable_Function: {
8111 // C++ [over.match.oper]p9:
8112 // If the operator is the operator , [...] and there are no
8113 // viable functions, then the operator is assumed to be the
8114 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00008115 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00008116 break;
8117
Chandler Carruth8e543b32010-12-12 08:17:55 +00008118 // For class as left operand for assignment or compound assigment
8119 // operator do not fall through to handling in built-in, but report that
8120 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00008121 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008122 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00008123 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00008124 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8125 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00008126 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00008127 } else {
8128 // No viable function; try to create a built-in operation, which will
8129 // produce an error. Then, show the non-viable candidates.
8130 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00008131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008132 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00008133 "C++ binary operator overloading is missing candidates!");
8134 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00008135 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8136 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00008137 return move(Result);
8138 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008139
8140 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008141 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008142 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00008143 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00008144 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008145 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8146 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008147 return ExprError();
8148
8149 case OR_Deleted:
8150 Diag(OpLoc, diag::err_ovl_deleted_oper)
8151 << Best->Function->isDeleted()
8152 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00008153 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008154 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008155 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00008156 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008157
Douglas Gregor66950a32009-09-30 21:46:01 +00008158 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00008159 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008160}
8161
John McCalldadc5752010-08-24 06:29:42 +00008162ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00008163Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8164 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00008165 Expr *Base, Expr *Idx) {
8166 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00008167 DeclarationName OpName =
8168 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8169
8170 // If either side is type-dependent, create an appropriate dependent
8171 // expression.
8172 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8173
John McCall58cc69d2010-01-27 01:50:18 +00008174 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008175 // CHECKME: no 'operator' keyword?
8176 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8177 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00008178 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008179 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008180 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008181 /*ADL*/ true, /*Overloaded*/ false,
8182 UnresolvedSetIterator(),
8183 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00008184 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00008185
Sebastian Redladba46e2009-10-29 20:17:01 +00008186 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8187 Args, 2,
8188 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008189 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00008190 RLoc));
8191 }
8192
John McCalle26a8722010-12-04 08:14:53 +00008193 if (Args[0]->getObjectKind() == OK_ObjCProperty)
8194 ConvertPropertyForRValue(Args[0]);
8195 if (Args[1]->getObjectKind() == OK_ObjCProperty)
8196 ConvertPropertyForRValue(Args[1]);
8197
Sebastian Redladba46e2009-10-29 20:17:01 +00008198 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008199 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008200
8201 // Subscript can only be overloaded as a member function.
8202
8203 // Add operator candidates that are member functions.
8204 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8205
8206 // Add builtin operator candidates.
8207 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8208
8209 // Perform overload resolution.
8210 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008211 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00008212 case OR_Success: {
8213 // We found a built-in operator or an overloaded operator.
8214 FunctionDecl *FnDecl = Best->Function;
8215
8216 if (FnDecl) {
8217 // We matched an overloaded operator. Build a call to that
8218 // operator.
8219
John McCalla0296f72010-03-19 07:35:19 +00008220 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008221 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00008222
Sebastian Redladba46e2009-10-29 20:17:01 +00008223 // Convert the arguments.
8224 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008225 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008226 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00008227 return ExprError();
8228
Anders Carlssona68e51e2010-01-29 18:37:50 +00008229 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008230 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00008231 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008232 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00008233 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008234 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00008235 Owned(Args[1]));
8236 if (InputInit.isInvalid())
8237 return ExprError();
8238
8239 Args[1] = InputInit.takeAs<Expr>();
8240
Sebastian Redladba46e2009-10-29 20:17:01 +00008241 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00008242 QualType ResultTy = FnDecl->getResultType();
8243 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8244 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00008245
8246 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00008247 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008248
John McCallb268a282010-08-23 23:25:46 +00008249 CXXOperatorCallExpr *TheCall =
8250 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
8251 FnExpr, Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00008252 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008253
John McCallb268a282010-08-23 23:25:46 +00008254 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00008255 FnDecl))
8256 return ExprError();
8257
John McCallb268a282010-08-23 23:25:46 +00008258 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00008259 } else {
8260 // We matched a built-in operator. Convert the arguments, then
8261 // break out so that we will build the appropriate built-in
8262 // operator node.
8263 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008264 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00008265 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008266 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00008267 return ExprError();
8268
8269 break;
8270 }
8271 }
8272
8273 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00008274 if (CandidateSet.empty())
8275 Diag(LLoc, diag::err_ovl_no_oper)
8276 << Args[0]->getType() << /*subscript*/ 0
8277 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8278 else
8279 Diag(LLoc, diag::err_ovl_no_viable_subscript)
8280 << Args[0]->getType()
8281 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008282 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8283 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00008284 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00008285 }
8286
8287 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008288 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008289 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00008290 << Args[0]->getType() << Args[1]->getType()
8291 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008292 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8293 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008294 return ExprError();
8295
8296 case OR_Deleted:
8297 Diag(LLoc, diag::err_ovl_deleted_oper)
8298 << Best->Function->isDeleted() << "[]"
8299 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008300 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8301 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008302 return ExprError();
8303 }
8304
8305 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00008306 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008307}
8308
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008309/// BuildCallToMemberFunction - Build a call to a member
8310/// function. MemExpr is the expression that refers to the member
8311/// function (and includes the object parameter), Args/NumArgs are the
8312/// arguments to the function call (not including the object
8313/// parameter). The caller needs to validate that the member
8314/// expression refers to a member function or an overloaded member
8315/// function.
John McCalldadc5752010-08-24 06:29:42 +00008316ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008317Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8318 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008319 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008320 // Dig out the member expression. This holds both the object
8321 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00008322 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008323
John McCall10eae182009-11-30 22:42:35 +00008324 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008325 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00008326 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008327 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00008328 if (isa<MemberExpr>(NakedMemExpr)) {
8329 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00008330 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00008331 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008332 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00008333 } else {
8334 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008335 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008336
John McCall6e9f8f62009-12-03 04:06:58 +00008337 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00008338 Expr::Classification ObjectClassification
8339 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
8340 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00008341
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008342 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00008343 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00008344
John McCall2d74de92009-12-01 22:10:20 +00008345 // FIXME: avoid copy.
8346 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8347 if (UnresExpr->hasExplicitTemplateArgs()) {
8348 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8349 TemplateArgs = &TemplateArgsBuffer;
8350 }
8351
John McCall10eae182009-11-30 22:42:35 +00008352 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
8353 E = UnresExpr->decls_end(); I != E; ++I) {
8354
John McCall6e9f8f62009-12-03 04:06:58 +00008355 NamedDecl *Func = *I;
8356 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
8357 if (isa<UsingShadowDecl>(Func))
8358 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
8359
Douglas Gregor02824322011-01-26 19:30:28 +00008360
Francois Pichet64225792011-01-18 05:04:39 +00008361 // Microsoft supports direct constructor calls.
8362 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
8363 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
8364 CandidateSet);
8365 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00008366 // If explicit template arguments were provided, we can't call a
8367 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00008368 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00008369 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008370
John McCalla0296f72010-03-19 07:35:19 +00008371 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008372 ObjectClassification,
8373 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00008374 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008375 } else {
John McCall10eae182009-11-30 22:42:35 +00008376 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00008377 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008378 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00008379 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008380 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008381 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008382 }
Mike Stump11289f42009-09-09 15:08:12 +00008383
John McCall10eae182009-11-30 22:42:35 +00008384 DeclarationName DeclName = UnresExpr->getMemberName();
8385
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008386 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008387 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00008388 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008389 case OR_Success:
8390 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008391 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00008392 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008393 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008394 break;
8395
8396 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00008397 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008398 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008399 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008400 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008401 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008402 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008403
8404 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00008405 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008406 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008407 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008408 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008409 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008410
8411 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00008412 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00008413 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00008414 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008415 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008416 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008417 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008418 }
8419
John McCall16df1e52010-03-30 21:47:33 +00008420 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00008421
John McCall2d74de92009-12-01 22:10:20 +00008422 // If overload resolution picked a static member, build a
8423 // non-member call based on that function.
8424 if (Method->isStatic()) {
8425 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8426 Args, NumArgs, RParenLoc);
8427 }
8428
John McCall10eae182009-11-30 22:42:35 +00008429 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008430 }
8431
John McCall7decc9e2010-11-18 06:31:45 +00008432 QualType ResultType = Method->getResultType();
8433 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8434 ResultType = ResultType.getNonLValueExprType(Context);
8435
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008436 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008437 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00008438 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008439 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008440
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008441 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008442 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00008443 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00008444 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008445
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008446 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00008447 // We only need to do this if there was actually an overload; otherwise
8448 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00008449 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00008450 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00008451 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
8452 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00008453 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008454 MemExpr->setBase(ObjectArg);
8455
8456 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00008457 const FunctionProtoType *Proto =
8458 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00008459 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008460 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00008461 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008462
John McCallb268a282010-08-23 23:25:46 +00008463 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00008464 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00008465
John McCallb268a282010-08-23 23:25:46 +00008466 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008467}
8468
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008469/// BuildCallToObjectOfClassType - Build a call to an object of class
8470/// type (C++ [over.call.object]), which can end up invoking an
8471/// overloaded function call operator (@c operator()) or performing a
8472/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00008473ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008474Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00008475 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008476 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008477 SourceLocation RParenLoc) {
John McCalle26a8722010-12-04 08:14:53 +00008478 if (Object->getObjectKind() == OK_ObjCProperty)
8479 ConvertPropertyForRValue(Object);
8480
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008481 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008482 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00008483
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008484 // C++ [over.call.object]p1:
8485 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00008486 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008487 // candidate functions includes at least the function call
8488 // operators of T. The function call operators of T are obtained by
8489 // ordinary lookup of the name operator() in the context of
8490 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00008491 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00008492 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008493
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008494 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00008495 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008496 << Object->getSourceRange()))
8497 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008498
John McCall27b18f82009-11-17 02:14:36 +00008499 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8500 LookupQualifiedName(R, Record->getDecl());
8501 R.suppressDiagnostics();
8502
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008503 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00008504 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008505 AddMethodCandidate(Oper.getPair(), Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00008506 Object->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00008507 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00008508 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008509
Douglas Gregorab7897a2008-11-19 22:57:39 +00008510 // C++ [over.call.object]p2:
8511 // In addition, for each conversion function declared in T of the
8512 // form
8513 //
8514 // operator conversion-type-id () cv-qualifier;
8515 //
8516 // where cv-qualifier is the same cv-qualification as, or a
8517 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00008518 // denotes the type "pointer to function of (P1,...,Pn) returning
8519 // R", or the type "reference to pointer to function of
8520 // (P1,...,Pn) returning R", or the type "reference to function
8521 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00008522 // is also considered as a candidate function. Similarly,
8523 // surrogate call functions are added to the set of candidate
8524 // functions for each conversion function declared in an
8525 // accessible base class provided the function is not hidden
8526 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00008527 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00008528 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00008529 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00008530 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00008531 NamedDecl *D = *I;
8532 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8533 if (isa<UsingShadowDecl>(D))
8534 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008535
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008536 // Skip over templated conversion functions; they aren't
8537 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00008538 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008539 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00008540
John McCall6e9f8f62009-12-03 04:06:58 +00008541 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00008542
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008543 // Strip the reference type (if any) and then the pointer type (if
8544 // any) to get down to what might be a function type.
8545 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8546 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8547 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00008548
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008549 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00008550 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00008551 Object, Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008552 }
Mike Stump11289f42009-09-09 15:08:12 +00008553
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008554 // Perform overload resolution.
8555 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008556 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
8557 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008558 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00008559 // Overload resolution succeeded; we'll build the appropriate call
8560 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008561 break;
8562
8563 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00008564 if (CandidateSet.empty())
8565 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8566 << Object->getType() << /*call*/ 1
8567 << Object->getSourceRange();
8568 else
8569 Diag(Object->getSourceRange().getBegin(),
8570 diag::err_ovl_no_viable_object_call)
8571 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008572 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008573 break;
8574
8575 case OR_Ambiguous:
8576 Diag(Object->getSourceRange().getBegin(),
8577 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008578 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008579 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008580 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008581
8582 case OR_Deleted:
8583 Diag(Object->getSourceRange().getBegin(),
8584 diag::err_ovl_deleted_object_call)
8585 << Best->Function->isDeleted()
8586 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008587 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008588 break;
Mike Stump11289f42009-09-09 15:08:12 +00008589 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008590
Douglas Gregorb412e172010-07-25 18:17:45 +00008591 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008592 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008593
Douglas Gregorab7897a2008-11-19 22:57:39 +00008594 if (Best->Function == 0) {
8595 // Since there is no function declaration, this is one of the
8596 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00008597 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00008598 = cast<CXXConversionDecl>(
8599 Best->Conversions[0].UserDefined.ConversionFunction);
8600
John McCalla0296f72010-03-19 07:35:19 +00008601 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008602 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008603
Douglas Gregorab7897a2008-11-19 22:57:39 +00008604 // We selected one of the surrogate functions that converts the
8605 // object parameter to a function pointer. Perform the conversion
8606 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008607
Fariborz Jahanian774cf792009-09-28 18:35:46 +00008608 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00008609 // and then call it.
Douglas Gregor668443e2011-01-20 00:18:04 +00008610 ExprResult Call = BuildCXXMemberCallExpr(Object, Best->FoundDecl, Conv);
8611 if (Call.isInvalid())
8612 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008613
Douglas Gregor668443e2011-01-20 00:18:04 +00008614 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008615 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008616 }
8617
John McCalla0296f72010-03-19 07:35:19 +00008618 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008619 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008620
Douglas Gregorab7897a2008-11-19 22:57:39 +00008621 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8622 // that calls this method, using Object for the implicit object
8623 // parameter and passing along the remaining arguments.
8624 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008625 const FunctionProtoType *Proto =
8626 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008627
8628 unsigned NumArgsInProto = Proto->getNumArgs();
8629 unsigned NumArgsToCheck = NumArgs;
8630
8631 // Build the full argument list for the method call (the
8632 // implicit object parameter is placed at the beginning of the
8633 // list).
8634 Expr **MethodArgs;
8635 if (NumArgs < NumArgsInProto) {
8636 NumArgsToCheck = NumArgsInProto;
8637 MethodArgs = new Expr*[NumArgsInProto + 1];
8638 } else {
8639 MethodArgs = new Expr*[NumArgs + 1];
8640 }
8641 MethodArgs[0] = Object;
8642 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8643 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00008644
John McCall7decc9e2010-11-18 06:31:45 +00008645 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008646
8647 // Once we've built TheCall, all of the expressions are properly
8648 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00008649 QualType ResultTy = Method->getResultType();
8650 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8651 ResultTy = ResultTy.getNonLValueExprType(Context);
8652
John McCallb268a282010-08-23 23:25:46 +00008653 CXXOperatorCallExpr *TheCall =
8654 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
8655 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00008656 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008657 delete [] MethodArgs;
8658
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008659 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00008660 Method))
8661 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008662
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008663 // We may have default arguments. If so, we need to allocate more
8664 // slots in the call for them.
8665 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00008666 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008667 else if (NumArgs > NumArgsInProto)
8668 NumArgsToCheck = NumArgsInProto;
8669
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008670 bool IsError = false;
8671
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008672 // Initialize the implicit object parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008673 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008674 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008675 TheCall->setArg(0, Object);
8676
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008677
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008678 // Check the argument types.
8679 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008680 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008681 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008682 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00008683
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008684 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008685
John McCalldadc5752010-08-24 06:29:42 +00008686 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008687 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008688 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008689 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00008690 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008691
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008692 IsError |= InputInit.isInvalid();
8693 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008694 } else {
John McCalldadc5752010-08-24 06:29:42 +00008695 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008696 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8697 if (DefArg.isInvalid()) {
8698 IsError = true;
8699 break;
8700 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008701
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008702 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008703 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008704
8705 TheCall->setArg(i + 1, Arg);
8706 }
8707
8708 // If this is a variadic call, handle args passed through "...".
8709 if (Proto->isVariadic()) {
8710 // Promote the arguments (C99 6.5.2.2p7).
8711 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8712 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00008713 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008714 TheCall->setArg(i + 1, Arg);
8715 }
8716 }
8717
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008718 if (IsError) return true;
8719
John McCallb268a282010-08-23 23:25:46 +00008720 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00008721 return true;
8722
John McCalle172be52010-08-24 06:09:16 +00008723 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008724}
8725
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008726/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00008727/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008728/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00008729ExprResult
John McCallb268a282010-08-23 23:25:46 +00008730Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008731 assert(Base->getType()->isRecordType() &&
8732 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00008733
John McCalle26a8722010-12-04 08:14:53 +00008734 if (Base->getObjectKind() == OK_ObjCProperty)
8735 ConvertPropertyForRValue(Base);
8736
John McCallbc077cf2010-02-08 23:07:23 +00008737 SourceLocation Loc = Base->getExprLoc();
8738
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008739 // C++ [over.ref]p1:
8740 //
8741 // [...] An expression x->m is interpreted as (x.operator->())->m
8742 // for a class object x of type T if T::operator->() exists and if
8743 // the operator is selected as the best match function by the
8744 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00008745 DeclarationName OpName =
8746 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00008747 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008748 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00008749
John McCallbc077cf2010-02-08 23:07:23 +00008750 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00008751 PDiag(diag::err_typecheck_incomplete_tag)
8752 << Base->getSourceRange()))
8753 return ExprError();
8754
John McCall27b18f82009-11-17 02:14:36 +00008755 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8756 LookupQualifiedName(R, BaseRecord->getDecl());
8757 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00008758
8759 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00008760 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00008761 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
8762 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00008763 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008764
8765 // Perform overload resolution.
8766 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008767 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008768 case OR_Success:
8769 // Overload resolution succeeded; we'll build the call below.
8770 break;
8771
8772 case OR_No_Viable_Function:
8773 if (CandidateSet.empty())
8774 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008775 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008776 else
8777 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008778 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008779 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008780 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008781
8782 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008783 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8784 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008785 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008786 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008787
8788 case OR_Deleted:
8789 Diag(OpLoc, diag::err_ovl_deleted_oper)
8790 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00008791 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008792 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008793 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008794 }
8795
John McCalla0296f72010-03-19 07:35:19 +00008796 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008797 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00008798
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008799 // Convert the object parameter.
8800 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008801 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8802 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00008803 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00008804
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008805 // Build the operator call.
John McCall7decc9e2010-11-18 06:31:45 +00008806 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008807
John McCall7decc9e2010-11-18 06:31:45 +00008808 QualType ResultTy = Method->getResultType();
8809 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8810 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00008811 CXXOperatorCallExpr *TheCall =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008812 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008813 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008814
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008815 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008816 Method))
8817 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008818 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008819}
8820
Douglas Gregorcd695e52008-11-10 20:40:00 +00008821/// FixOverloadedFunctionReference - E is an expression that refers to
8822/// a C++ overloaded function (possibly with some parentheses and
8823/// perhaps a '&' around it). We have resolved the overloaded function
8824/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008825/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00008826Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00008827 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00008828 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008829 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8830 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008831 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008832 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008833
Douglas Gregor51c538b2009-11-20 19:42:02 +00008834 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008835 }
8836
Douglas Gregor51c538b2009-11-20 19:42:02 +00008837 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008838 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8839 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008840 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008841 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00008842 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00008843 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00008844 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008845 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008846
8847 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +00008848 ICE->getCastKind(),
8849 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00008850 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008851 }
8852
Douglas Gregor51c538b2009-11-20 19:42:02 +00008853 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00008854 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008855 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008856 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8857 if (Method->isStatic()) {
8858 // Do nothing: static member functions aren't any different
8859 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008860 } else {
John McCalle66edc12009-11-24 19:00:30 +00008861 // Fix the sub expression, which really has to be an
8862 // UnresolvedLookupExpr holding an overloaded member function
8863 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008864 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8865 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008866 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008867 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008868
John McCalld14a8642009-11-21 08:51:07 +00008869 assert(isa<DeclRefExpr>(SubExpr)
8870 && "fixed to something other than a decl ref");
8871 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8872 && "fixed to a member ref with no nested name qualifier");
8873
8874 // We have taken the address of a pointer to member
8875 // function. Perform the computation here so that we get the
8876 // appropriate pointer to member type.
8877 QualType ClassType
8878 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8879 QualType MemPtrType
8880 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8881
John McCall7decc9e2010-11-18 06:31:45 +00008882 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8883 VK_RValue, OK_Ordinary,
8884 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008885 }
8886 }
John McCall16df1e52010-03-30 21:47:33 +00008887 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8888 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008889 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008890 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008891
John McCalle3027922010-08-25 11:45:40 +00008892 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008893 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00008894 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008895 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008896 }
John McCalld14a8642009-11-21 08:51:07 +00008897
8898 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00008899 // FIXME: avoid copy.
8900 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00008901 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00008902 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8903 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00008904 }
8905
John McCalld14a8642009-11-21 08:51:07 +00008906 return DeclRefExpr::Create(Context,
8907 ULE->getQualifier(),
8908 ULE->getQualifierRange(),
8909 Fn,
8910 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00008911 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008912 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008913 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00008914 }
8915
John McCall10eae182009-11-30 22:42:35 +00008916 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00008917 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00008918 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8919 if (MemExpr->hasExplicitTemplateArgs()) {
8920 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8921 TemplateArgs = &TemplateArgsBuffer;
8922 }
John McCall6b51f282009-11-23 01:53:49 +00008923
John McCall2d74de92009-12-01 22:10:20 +00008924 Expr *Base;
8925
John McCall7decc9e2010-11-18 06:31:45 +00008926 // If we're filling in a static method where we used to have an
8927 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00008928 if (MemExpr->isImplicitAccess()) {
8929 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8930 return DeclRefExpr::Create(Context,
8931 MemExpr->getQualifier(),
8932 MemExpr->getQualifierRange(),
8933 Fn,
8934 MemExpr->getMemberLoc(),
8935 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008936 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008937 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00008938 } else {
8939 SourceLocation Loc = MemExpr->getMemberLoc();
8940 if (MemExpr->getQualifier())
8941 Loc = MemExpr->getQualifierRange().getBegin();
8942 Base = new (Context) CXXThisExpr(Loc,
8943 MemExpr->getBaseType(),
8944 /*isImplicit=*/true);
8945 }
John McCall2d74de92009-12-01 22:10:20 +00008946 } else
John McCallc3007a22010-10-26 07:05:15 +00008947 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00008948
8949 return MemberExpr::Create(Context, Base,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008950 MemExpr->isArrow(),
8951 MemExpr->getQualifier(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008952 MemExpr->getQualifierRange(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008953 Fn,
John McCall16df1e52010-03-30 21:47:33 +00008954 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008955 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00008956 TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008957 Fn->getType(),
8958 cast<CXXMethodDecl>(Fn)->isStatic()
8959 ? VK_LValue : VK_RValue,
8960 OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008961 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008962
John McCallc3007a22010-10-26 07:05:15 +00008963 llvm_unreachable("Invalid reference to overloaded function");
8964 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008965}
8966
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008967ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +00008968 DeclAccessPair Found,
8969 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00008970 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008971}
8972
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008973} // end namespace clang