blob: 00cdca3bcf3ef6b4f2fb9d7b6a175addf1e17db1 [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();
1039 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
1040 if (!Method->isStatic()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001041 const Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +00001042 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1043 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +00001044 }
1045 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001046
Douglas Gregor980fb162010-04-29 18:24:40 +00001047 // If the "from" expression takes the address of the overloaded
1048 // function, update the type of the resulting expression accordingly.
1049 if (FromType->getAs<FunctionType>())
1050 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +00001051 if (UnOp->getOpcode() == UO_AddrOf)
John McCall5c32be02010-08-24 20:38:10 +00001052 FromType = S.Context.getPointerType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001053
Douglas Gregor980fb162010-04-29 18:24:40 +00001054 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00001055 assert(S.Context.hasSameType(FromType,
1056 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001057 } else {
1058 return false;
1059 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001060 }
Mike Stump11289f42009-09-09 15:08:12 +00001061 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062 // An lvalue (3.10) of a non-function, non-array type T can be
1063 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001064 bool argIsLValue = From->isLValue();
1065 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001066 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001067 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001068 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001069
1070 // If T is a non-class type, the type of the rvalue is the
1071 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001072 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1073 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001074 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001075 } else if (FromType->isArrayType()) {
1076 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001077 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001078
1079 // An lvalue or rvalue of type "array of N T" or "array of unknown
1080 // bound of T" can be converted to an rvalue of type "pointer to
1081 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001082 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001083
John McCall5c32be02010-08-24 20:38:10 +00001084 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001085 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001086 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001087
1088 // For the purpose of ranking in overload resolution
1089 // (13.3.3.1.1), this conversion is considered an
1090 // array-to-pointer conversion followed by a qualification
1091 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001092 SCS.Second = ICK_Identity;
1093 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001094 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001095 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001096 }
John McCall086a4642010-11-24 05:12:34 +00001097 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001098 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001099 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001100
1101 // An lvalue of function type T can be converted to an rvalue of
1102 // type "pointer to T." The result is a pointer to the
1103 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001104 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001105 } else {
1106 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001107 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001108 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001109 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001110
1111 // The second conversion can be an integral promotion, floating
1112 // point promotion, integral conversion, floating point conversion,
1113 // floating-integral conversion, pointer conversion,
1114 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001115 // For overloading in C, this can also be a "compatible-type"
1116 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001117 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001118 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001119 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001120 // The unqualified versions of the types are the same: there's no
1121 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001122 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001123 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001124 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001125 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001126 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001127 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001128 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001129 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001130 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001131 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001132 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001133 SCS.Second = ICK_Complex_Promotion;
1134 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001135 } else if (ToType->isBooleanType() &&
1136 (FromType->isArithmeticType() ||
1137 FromType->isAnyPointerType() ||
1138 FromType->isBlockPointerType() ||
1139 FromType->isMemberPointerType() ||
1140 FromType->isNullPtrType())) {
1141 // Boolean conversions (C++ 4.12).
1142 SCS.Second = ICK_Boolean_Conversion;
1143 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001144 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001145 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001146 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001147 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001148 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001149 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001150 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001151 SCS.Second = ICK_Complex_Conversion;
1152 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001153 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1154 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001155 // Complex-real conversions (C99 6.3.1.7)
1156 SCS.Second = ICK_Complex_Real;
1157 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001158 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001159 // Floating point conversions (C++ 4.8).
1160 SCS.Second = ICK_Floating_Conversion;
1161 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001162 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001163 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001164 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001165 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001166 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001167 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001168 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001169 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1170 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001171 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001172 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001173 SCS.IncompatibleObjC = IncompatibleObjC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001174 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001175 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001176 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001177 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001178 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001179 SCS.Second = SecondICK;
1180 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001181 } else if (!S.getLangOptions().CPlusPlus &&
1182 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001183 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001184 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001185 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001186 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001187 // Treat a conversion that strips "noreturn" as an identity conversion.
1188 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001189 } else {
1190 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001191 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001192 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001193 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001194
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001195 QualType CanonFrom;
1196 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001197 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor58281352011-01-27 00:58:17 +00001198 if (S.IsQualificationConversion(FromType, ToType, CStyle)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001199 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001200 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001201 CanonFrom = S.Context.getCanonicalType(FromType);
1202 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001203 } else {
1204 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001205 SCS.Third = ICK_Identity;
1206
Mike Stump11289f42009-09-09 15:08:12 +00001207 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001208 // [...] Any difference in top-level cv-qualification is
1209 // subsumed by the initialization itself and does not constitute
1210 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001211 CanonFrom = S.Context.getCanonicalType(FromType);
1212 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001213 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001214 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001215 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1216 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001217 FromType = ToType;
1218 CanonFrom = CanonTo;
1219 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001220 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001221 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001222
1223 // If we have not converted the argument type to the parameter type,
1224 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001225 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001226 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001227
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001228 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001229}
1230
1231/// IsIntegralPromotion - Determines whether the conversion from the
1232/// expression From (whose potentially-adjusted type is FromType) to
1233/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1234/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001235bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001236 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001237 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001238 if (!To) {
1239 return false;
1240 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001241
1242 // An rvalue of type char, signed char, unsigned char, short int, or
1243 // unsigned short int can be converted to an rvalue of type int if
1244 // int can represent all the values of the source type; otherwise,
1245 // the source rvalue can be converted to an rvalue of type unsigned
1246 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001247 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1248 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001249 if (// We can promote any signed, promotable integer type to an int
1250 (FromType->isSignedIntegerType() ||
1251 // We can promote any unsigned integer type whose size is
1252 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001253 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001254 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001255 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001256 }
1257
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001258 return To->getKind() == BuiltinType::UInt;
1259 }
1260
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001261 // C++0x [conv.prom]p3:
1262 // A prvalue of an unscoped enumeration type whose underlying type is not
1263 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1264 // following types that can represent all the values of the enumeration
1265 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1266 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001267 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001268 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001269 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001270 // with lowest integer conversion rank (4.13) greater than the rank of long
1271 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001272 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001273 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1274 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1275 // provided for a scoped enumeration.
1276 if (FromEnumType->getDecl()->isScoped())
1277 return false;
1278
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001279 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001280 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001281 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001282 return Context.hasSameUnqualifiedType(ToType,
1283 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001284 }
John McCall56774992009-12-09 09:09:27 +00001285
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001286 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001287 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1288 // to an rvalue a prvalue of the first of the following types that can
1289 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001290 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001291 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001292 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001293 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001294 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001295 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001296 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001297 // Determine whether the type we're converting from is signed or
1298 // unsigned.
1299 bool FromIsSigned;
1300 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001301
John McCall56774992009-12-09 09:09:27 +00001302 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1303 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001304
1305 // The types we'll try to promote to, in the appropriate
1306 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001307 QualType PromoteTypes[6] = {
1308 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001309 Context.LongTy, Context.UnsignedLongTy ,
1310 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001311 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001312 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001313 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1314 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001315 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001316 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1317 // We found the type that we can promote to. If this is the
1318 // type we wanted, we have a promotion. Otherwise, no
1319 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001320 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001321 }
1322 }
1323 }
1324
1325 // An rvalue for an integral bit-field (9.6) can be converted to an
1326 // rvalue of type int if int can represent all the values of the
1327 // bit-field; otherwise, it can be converted to unsigned int if
1328 // unsigned int can represent all the values of the bit-field. If
1329 // the bit-field is larger yet, no integral promotion applies to
1330 // it. If the bit-field has an enumerated type, it is treated as any
1331 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001332 // FIXME: We should delay checking of bit-fields until we actually perform the
1333 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001334 using llvm::APSInt;
1335 if (From)
1336 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001337 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001338 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001339 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1340 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1341 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001342
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001343 // Are we promoting to an int from a bitfield that fits in an int?
1344 if (BitWidth < ToSize ||
1345 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1346 return To->getKind() == BuiltinType::Int;
1347 }
Mike Stump11289f42009-09-09 15:08:12 +00001348
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001349 // Are we promoting to an unsigned int from an unsigned bitfield
1350 // that fits into an unsigned int?
1351 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1352 return To->getKind() == BuiltinType::UInt;
1353 }
Mike Stump11289f42009-09-09 15:08:12 +00001354
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001355 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001356 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001357 }
Mike Stump11289f42009-09-09 15:08:12 +00001358
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001359 // An rvalue of type bool can be converted to an rvalue of type int,
1360 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001361 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001362 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001363 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001364
1365 return false;
1366}
1367
1368/// IsFloatingPointPromotion - Determines whether the conversion from
1369/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1370/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001371bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001372 /// An rvalue of type float can be converted to an rvalue of type
1373 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001374 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1375 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001376 if (FromBuiltin->getKind() == BuiltinType::Float &&
1377 ToBuiltin->getKind() == BuiltinType::Double)
1378 return true;
1379
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001380 // C99 6.3.1.5p1:
1381 // When a float is promoted to double or long double, or a
1382 // double is promoted to long double [...].
1383 if (!getLangOptions().CPlusPlus &&
1384 (FromBuiltin->getKind() == BuiltinType::Float ||
1385 FromBuiltin->getKind() == BuiltinType::Double) &&
1386 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1387 return true;
1388 }
1389
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001390 return false;
1391}
1392
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001393/// \brief Determine if a conversion is a complex promotion.
1394///
1395/// A complex promotion is defined as a complex -> complex conversion
1396/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001397/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001398bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001399 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001400 if (!FromComplex)
1401 return false;
1402
John McCall9dd450b2009-09-21 23:43:11 +00001403 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001404 if (!ToComplex)
1405 return false;
1406
1407 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001408 ToComplex->getElementType()) ||
1409 IsIntegralPromotion(0, FromComplex->getElementType(),
1410 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001411}
1412
Douglas Gregor237f96c2008-11-26 23:31:11 +00001413/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1414/// the pointer type FromPtr to a pointer to type ToPointee, with the
1415/// same type qualifiers as FromPtr has on its pointee type. ToType,
1416/// if non-empty, will be a pointer to ToType that may or may not have
1417/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001418static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001419BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001420 QualType ToPointee, QualType ToType,
1421 ASTContext &Context) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001422 assert((FromPtr->getTypeClass() == Type::Pointer ||
1423 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1424 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001425
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001426 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1427 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1428 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001429
1430 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001431 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001432 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001433 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001434
1435 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001436 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001437 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001438 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001439 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001440
1441 // Build a pointer to ToPointee. It has the right qualifiers
1442 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001443 if (isa<ObjCObjectPointerType>(ToType))
1444 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001445 return Context.getPointerType(ToPointee);
1446 }
1447
1448 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001449 QualType QualifiedCanonToPointee
1450 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001451
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001452 if (isa<ObjCObjectPointerType>(ToType))
1453 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1454 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001455}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001456
Mike Stump11289f42009-09-09 15:08:12 +00001457static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001458 bool InOverloadResolution,
1459 ASTContext &Context) {
1460 // Handle value-dependent integral null pointer constants correctly.
1461 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1462 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001463 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001464 return !InOverloadResolution;
1465
Douglas Gregor56751b52009-09-25 04:25:58 +00001466 return Expr->isNullPointerConstant(Context,
1467 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1468 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001469}
Mike Stump11289f42009-09-09 15:08:12 +00001470
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001471/// IsPointerConversion - Determines whether the conversion of the
1472/// expression From, which has the (possibly adjusted) type FromType,
1473/// can be converted to the type ToType via a pointer conversion (C++
1474/// 4.10). If so, returns true and places the converted type (that
1475/// might differ from ToType in its cv-qualifiers at some level) into
1476/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001477///
Douglas Gregora29dc052008-11-27 01:19:21 +00001478/// This routine also supports conversions to and from block pointers
1479/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1480/// pointers to interfaces. FIXME: Once we've determined the
1481/// appropriate overloading rules for Objective-C, we may want to
1482/// split the Objective-C checks into a different routine; however,
1483/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001484/// conversions, so for now they live here. IncompatibleObjC will be
1485/// set if the conversion is an allowed Objective-C conversion that
1486/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001487bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001488 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001489 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001490 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001491 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001492 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1493 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001494 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001495
Mike Stump11289f42009-09-09 15:08:12 +00001496 // Conversion from a null pointer constant to any Objective-C pointer type.
1497 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001498 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001499 ConvertedType = ToType;
1500 return true;
1501 }
1502
Douglas Gregor231d1c62008-11-27 00:15:41 +00001503 // Blocks: Block pointers can be converted to void*.
1504 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001505 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001506 ConvertedType = ToType;
1507 return true;
1508 }
1509 // Blocks: A null pointer constant can be converted to a block
1510 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001511 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001512 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001513 ConvertedType = ToType;
1514 return true;
1515 }
1516
Sebastian Redl576fd422009-05-10 18:38:11 +00001517 // If the left-hand-side is nullptr_t, the right side can be a null
1518 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001519 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001520 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001521 ConvertedType = ToType;
1522 return true;
1523 }
1524
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001525 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001526 if (!ToTypePtr)
1527 return false;
1528
1529 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001530 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001531 ConvertedType = ToType;
1532 return true;
1533 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001534
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001535 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001536 // , including objective-c pointers.
1537 QualType ToPointeeType = ToTypePtr->getPointeeType();
1538 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001539 ConvertedType = BuildSimilarlyQualifiedPointerType(
1540 FromType->getAs<ObjCObjectPointerType>(),
1541 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001542 ToType, Context);
1543 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001544 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001545 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001546 if (!FromTypePtr)
1547 return false;
1548
1549 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001550
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001551 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001552 // pointer conversion, so don't do all of the work below.
1553 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1554 return false;
1555
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001556 // An rvalue of type "pointer to cv T," where T is an object type,
1557 // can be converted to an rvalue of type "pointer to cv void" (C++
1558 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001559 if (FromPointeeType->isIncompleteOrObjectType() &&
1560 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001561 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001562 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001563 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001564 return true;
1565 }
1566
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001567 // When we're overloading in C, we allow a special kind of pointer
1568 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001569 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001570 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001571 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001572 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001573 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001574 return true;
1575 }
1576
Douglas Gregor5c407d92008-10-23 00:40:37 +00001577 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001578 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001579 // An rvalue of type "pointer to cv D," where D is a class type,
1580 // can be converted to an rvalue of type "pointer to cv B," where
1581 // B is a base class (clause 10) of D. If B is an inaccessible
1582 // (clause 11) or ambiguous (10.2) base class of D, a program that
1583 // necessitates this conversion is ill-formed. The result of the
1584 // conversion is a pointer to the base class sub-object of the
1585 // derived class object. The null pointer value is converted to
1586 // the null pointer value of the destination type.
1587 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001588 // Note that we do not check for ambiguity or inaccessibility
1589 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001590 if (getLangOptions().CPlusPlus &&
1591 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001592 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001593 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001594 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001595 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001596 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001597 ToType, Context);
1598 return true;
1599 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001600
Douglas Gregora119f102008-12-19 19:13:09 +00001601 return false;
1602}
1603
1604/// isObjCPointerConversion - Determines whether this is an
1605/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1606/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001607bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001608 QualType& ConvertedType,
1609 bool &IncompatibleObjC) {
1610 if (!getLangOptions().ObjC1)
1611 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001612
Steve Naroff7cae42b2009-07-10 23:34:53 +00001613 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001614 const ObjCObjectPointerType* ToObjCPtr =
1615 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001616 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001617 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001618
Steve Naroff7cae42b2009-07-10 23:34:53 +00001619 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001620 // If the pointee types are the same (ignoring qualifications),
1621 // then this is not a pointer conversion.
1622 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1623 FromObjCPtr->getPointeeType()))
1624 return false;
1625
Steve Naroff1329fa02009-07-15 18:40:39 +00001626 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001627 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001628 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001629 ConvertedType = ToType;
1630 return true;
1631 }
1632 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001633 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001634 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001635 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001636 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001637 ConvertedType = ToType;
1638 return true;
1639 }
1640 // Objective C++: We're able to convert from a pointer to an
1641 // interface to a pointer to a different interface.
1642 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001643 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1644 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1645 if (getLangOptions().CPlusPlus && LHS && RHS &&
1646 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1647 FromObjCPtr->getPointeeType()))
1648 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001649 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001650 ToObjCPtr->getPointeeType(),
1651 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001652 return true;
1653 }
1654
1655 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1656 // Okay: this is some kind of implicit downcast of Objective-C
1657 // interfaces, which is permitted. However, we're going to
1658 // complain about it.
1659 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001660 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001661 ToObjCPtr->getPointeeType(),
1662 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001663 return true;
1664 }
Mike Stump11289f42009-09-09 15:08:12 +00001665 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001666 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001667 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001668 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001669 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001670 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001671 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001672 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001673 // to a block pointer type.
1674 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1675 ConvertedType = ToType;
1676 return true;
1677 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001678 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001679 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001680 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001681 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001682 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001683 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001684 ConvertedType = ToType;
1685 return true;
1686 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001687 else
Douglas Gregora119f102008-12-19 19:13:09 +00001688 return false;
1689
Douglas Gregor033f56d2008-12-23 00:53:59 +00001690 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001691 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001692 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001693 else if (const BlockPointerType *FromBlockPtr =
1694 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001695 FromPointeeType = FromBlockPtr->getPointeeType();
1696 else
Douglas Gregora119f102008-12-19 19:13:09 +00001697 return false;
1698
Douglas Gregora119f102008-12-19 19:13:09 +00001699 // If we have pointers to pointers, recursively check whether this
1700 // is an Objective-C conversion.
1701 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1702 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1703 IncompatibleObjC)) {
1704 // We always complain about this conversion.
1705 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001706 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregora119f102008-12-19 19:13:09 +00001707 return true;
1708 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001709 // Allow conversion of pointee being objective-c pointer to another one;
1710 // as in I* to id.
1711 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1712 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1713 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1714 IncompatibleObjC)) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001715 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001716 return true;
1717 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001718
Douglas Gregor033f56d2008-12-23 00:53:59 +00001719 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001720 // differences in the argument and result types are in Objective-C
1721 // pointer conversions. If so, we permit the conversion (but
1722 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001723 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001724 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001725 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001726 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001727 if (FromFunctionType && ToFunctionType) {
1728 // If the function types are exactly the same, this isn't an
1729 // Objective-C pointer conversion.
1730 if (Context.getCanonicalType(FromPointeeType)
1731 == Context.getCanonicalType(ToPointeeType))
1732 return false;
1733
1734 // Perform the quick checks that will tell us whether these
1735 // function types are obviously different.
1736 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1737 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1738 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1739 return false;
1740
1741 bool HasObjCConversion = false;
1742 if (Context.getCanonicalType(FromFunctionType->getResultType())
1743 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1744 // Okay, the types match exactly. Nothing to do.
1745 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1746 ToFunctionType->getResultType(),
1747 ConvertedType, IncompatibleObjC)) {
1748 // Okay, we have an Objective-C pointer conversion.
1749 HasObjCConversion = true;
1750 } else {
1751 // Function types are too different. Abort.
1752 return false;
1753 }
Mike Stump11289f42009-09-09 15:08:12 +00001754
Douglas Gregora119f102008-12-19 19:13:09 +00001755 // Check argument types.
1756 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1757 ArgIdx != NumArgs; ++ArgIdx) {
1758 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1759 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1760 if (Context.getCanonicalType(FromArgType)
1761 == Context.getCanonicalType(ToArgType)) {
1762 // Okay, the types match exactly. Nothing to do.
1763 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1764 ConvertedType, IncompatibleObjC)) {
1765 // Okay, we have an Objective-C pointer conversion.
1766 HasObjCConversion = true;
1767 } else {
1768 // Argument types are too different. Abort.
1769 return false;
1770 }
1771 }
1772
1773 if (HasObjCConversion) {
1774 // We had an Objective-C conversion. Allow this pointer
1775 // conversion, but complain about it.
1776 ConvertedType = ToType;
1777 IncompatibleObjC = true;
1778 return true;
1779 }
1780 }
1781
Sebastian Redl72b597d2009-01-25 19:43:20 +00001782 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001783}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001784
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001785/// FunctionArgTypesAreEqual - This routine checks two function proto types
1786/// for equlity of their argument types. Caller has already checked that
1787/// they have same number of arguments. This routine assumes that Objective-C
1788/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001789bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00001790 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001791 if (!getLangOptions().ObjC1)
1792 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1793 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001794
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001795 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1796 N = NewType->arg_type_begin(),
1797 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1798 QualType ToType = (*O);
1799 QualType FromType = (*N);
1800 if (ToType != FromType) {
1801 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1802 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001803 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1804 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1805 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1806 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001807 continue;
1808 }
John McCall8b07ec22010-05-15 11:32:37 +00001809 else if (const ObjCObjectPointerType *PTTo =
1810 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001811 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00001812 FromType->getAs<ObjCObjectPointerType>())
1813 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1814 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001815 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001816 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001817 }
1818 }
1819 return true;
1820}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001821
Douglas Gregor39c16d42008-10-24 04:54:22 +00001822/// CheckPointerConversion - Check the pointer conversion from the
1823/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001824/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001825/// conversions for which IsPointerConversion has already returned
1826/// true. It returns true and produces a diagnostic if there was an
1827/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001828bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001829 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001830 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001831 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001832 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001833 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001834
John McCall8cb679e2010-11-15 09:13:47 +00001835 Kind = CK_BitCast;
1836
Douglas Gregor4038cf42010-06-08 17:35:15 +00001837 if (CXXBoolLiteralExpr* LitBool
1838 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001839 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregor4038cf42010-06-08 17:35:15 +00001840 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1841 << ToType;
1842
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001843 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1844 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001845 QualType FromPointeeType = FromPtrType->getPointeeType(),
1846 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001847
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001848 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1849 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001850 // We must have a derived-to-base conversion. Check an
1851 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001852 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1853 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001854 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001855 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001856 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001857
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001858 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00001859 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001860 }
1861 }
Mike Stump11289f42009-09-09 15:08:12 +00001862 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00001863 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001864 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001865 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001866 // Objective-C++ conversions are always okay.
1867 // FIXME: We should have a different class of conversions for the
1868 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001869 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001870 return false;
John McCall8cb679e2010-11-15 09:13:47 +00001871 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001872 }
John McCall8cb679e2010-11-15 09:13:47 +00001873
1874 // We shouldn't fall into this case unless it's valid for other
1875 // reasons.
1876 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1877 Kind = CK_NullToPointer;
1878
Douglas Gregor39c16d42008-10-24 04:54:22 +00001879 return false;
1880}
1881
Sebastian Redl72b597d2009-01-25 19:43:20 +00001882/// IsMemberPointerConversion - Determines whether the conversion of the
1883/// expression From, which has the (possibly adjusted) type FromType, can be
1884/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1885/// If so, returns true and places the converted type (that might differ from
1886/// ToType in its cv-qualifiers at some level) into ConvertedType.
1887bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001888 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001889 bool InOverloadResolution,
1890 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001891 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001892 if (!ToTypePtr)
1893 return false;
1894
1895 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001896 if (From->isNullPointerConstant(Context,
1897 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1898 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001899 ConvertedType = ToType;
1900 return true;
1901 }
1902
1903 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001904 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001905 if (!FromTypePtr)
1906 return false;
1907
1908 // A pointer to member of B can be converted to a pointer to member of D,
1909 // where D is derived from B (C++ 4.11p2).
1910 QualType FromClass(FromTypePtr->getClass(), 0);
1911 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001912
Douglas Gregor7f6ae692010-12-21 21:40:41 +00001913 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
1914 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
1915 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001916 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1917 ToClass.getTypePtr());
1918 return true;
1919 }
1920
1921 return false;
1922}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001923
Sebastian Redl72b597d2009-01-25 19:43:20 +00001924/// CheckMemberPointerConversion - Check the member pointer conversion from the
1925/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001926/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001927/// for which IsMemberPointerConversion has already returned true. It returns
1928/// true and produces a diagnostic if there was an error, or returns false
1929/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001930bool Sema::CheckMemberPointerConversion(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) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001934 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001935 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001936 if (!FromPtrType) {
1937 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001938 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00001939 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001940 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00001941 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001942 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001943 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001944
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001945 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001946 assert(ToPtrType && "No member pointer cast has a target type "
1947 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001948
Sebastian Redled8f2002009-01-28 18:33:18 +00001949 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1950 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001951
Sebastian Redled8f2002009-01-28 18:33:18 +00001952 // FIXME: What about dependent types?
1953 assert(FromClass->isRecordType() && "Pointer into non-class.");
1954 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001955
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001956 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001957 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001958 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1959 assert(DerivationOkay &&
1960 "Should not have been called if derivation isn't OK.");
1961 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001962
Sebastian Redled8f2002009-01-28 18:33:18 +00001963 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1964 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001965 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1966 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1967 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1968 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001969 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001970
Douglas Gregor89ee6822009-02-28 01:32:25 +00001971 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001972 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1973 << FromClass << ToClass << QualType(VBase, 0)
1974 << From->getSourceRange();
1975 return true;
1976 }
1977
John McCall5b0829a2010-02-10 09:31:12 +00001978 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001979 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1980 Paths.front(),
1981 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001982
Anders Carlssond7923c62009-08-22 23:33:40 +00001983 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001984 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001985 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001986 return false;
1987}
1988
Douglas Gregor9a657932008-10-21 23:43:52 +00001989/// IsQualificationConversion - Determines whether the conversion from
1990/// an rvalue of type FromType to ToType is a qualification conversion
1991/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001992bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001993Sema::IsQualificationConversion(QualType FromType, QualType ToType,
Douglas Gregor58281352011-01-27 00:58:17 +00001994 bool CStyle) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001995 FromType = Context.getCanonicalType(FromType);
1996 ToType = Context.getCanonicalType(ToType);
1997
1998 // If FromType and ToType are the same type, this is not a
1999 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002000 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002001 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002002
Douglas Gregor9a657932008-10-21 23:43:52 +00002003 // (C++ 4.4p4):
2004 // A conversion can add cv-qualifiers at levels other than the first
2005 // in multi-level pointers, subject to the following rules: [...]
2006 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002007 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002008 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002009 // Within each iteration of the loop, we check the qualifiers to
2010 // determine if this still looks like a qualification
2011 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002012 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002013 // until there are no more pointers or pointers-to-members left to
2014 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002015 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002016
2017 // -- for every j > 0, if const is in cv 1,j then const is in cv
2018 // 2,j, and similarly for volatile.
Douglas Gregor58281352011-01-27 00:58:17 +00002019 if (!CStyle && !ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00002020 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002021
Douglas Gregor9a657932008-10-21 23:43:52 +00002022 // -- if the cv 1,j and cv 2,j are different, then const is in
2023 // every cv for 0 < k < j.
Douglas Gregor58281352011-01-27 00:58:17 +00002024 if (!CStyle && FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002025 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002026 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002027
Douglas Gregor9a657932008-10-21 23:43:52 +00002028 // Keep track of whether all prior cv-qualifiers in the "to" type
2029 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002030 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00002031 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002032 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002033
2034 // We are left with FromType and ToType being the pointee types
2035 // after unwrapping the original FromType and ToType the same number
2036 // of types. If we unwrapped any pointers, and if FromType and
2037 // ToType have the same unqualified type (since we checked
2038 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002039 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002040}
2041
Douglas Gregor576e98c2009-01-30 23:27:23 +00002042/// Determines whether there is a user-defined conversion sequence
2043/// (C++ [over.ics.user]) that converts expression From to the type
2044/// ToType. If such a conversion exists, User will contain the
2045/// user-defined conversion sequence that performs such a conversion
2046/// and this routine will return true. Otherwise, this routine returns
2047/// false and User is unspecified.
2048///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002049/// \param AllowExplicit true if the conversion should consider C++0x
2050/// "explicit" conversion functions as well as non-explicit conversion
2051/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002052static OverloadingResult
2053IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2054 UserDefinedConversionSequence& User,
2055 OverloadCandidateSet& CandidateSet,
2056 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002057 // Whether we will only visit constructors.
2058 bool ConstructorsOnly = false;
2059
2060 // If the type we are conversion to is a class type, enumerate its
2061 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002062 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002063 // C++ [over.match.ctor]p1:
2064 // When objects of class type are direct-initialized (8.5), or
2065 // copy-initialized from an expression of the same or a
2066 // derived class type (8.5), overload resolution selects the
2067 // constructor. [...] For copy-initialization, the candidate
2068 // functions are all the converting constructors (12.3.1) of
2069 // that class. The argument list is the expression-list within
2070 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002071 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002072 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002073 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002074 ConstructorsOnly = true;
2075
John McCall5c32be02010-08-24 20:38:10 +00002076 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002077 // We're not going to find any constructors.
2078 } else if (CXXRecordDecl *ToRecordDecl
2079 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002080 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002081 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002082 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002083 NamedDecl *D = *Con;
2084 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2085
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002086 // Find the constructor (which may be a template).
2087 CXXConstructorDecl *Constructor = 0;
2088 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002089 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002090 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002091 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002092 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2093 else
John McCalla0296f72010-03-19 07:35:19 +00002094 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002095
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002096 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002097 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002098 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002099 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2100 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002101 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002102 /*SuppressUserConversions=*/
2103 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002104 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002105 // Allow one user-defined conversion when user specifies a
2106 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002107 S.AddOverloadCandidate(Constructor, FoundDecl,
2108 &From, 1, CandidateSet,
2109 /*SuppressUserConversions=*/
2110 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002111 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002112 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002113 }
2114 }
2115
Douglas Gregor5ab11652010-04-17 22:01:05 +00002116 // Enumerate conversion functions, if we're allowed to.
2117 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002118 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2119 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002120 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002121 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002122 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002123 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002124 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2125 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002126 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002127 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002128 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002129 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002130 DeclAccessPair FoundDecl = I.getPair();
2131 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002132 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2133 if (isa<UsingShadowDecl>(D))
2134 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2135
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002136 CXXConversionDecl *Conv;
2137 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002138 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2139 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002140 else
John McCallda4458e2010-03-31 01:36:47 +00002141 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002142
2143 if (AllowExplicit || !Conv->isExplicit()) {
2144 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002145 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2146 ActingContext, From, ToType,
2147 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002148 else
John McCall5c32be02010-08-24 20:38:10 +00002149 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2150 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002151 }
2152 }
2153 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002154 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002155
2156 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002157 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002158 case OR_Success:
2159 // Record the standard conversion we used and the conversion function.
2160 if (CXXConstructorDecl *Constructor
2161 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2162 // C++ [over.ics.user]p1:
2163 // If the user-defined conversion is specified by a
2164 // constructor (12.3.1), the initial standard conversion
2165 // sequence converts the source type to the type required by
2166 // the argument of the constructor.
2167 //
2168 QualType ThisType = Constructor->getThisType(S.Context);
2169 if (Best->Conversions[0].isEllipsis())
2170 User.EllipsisConversion = true;
2171 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002172 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002173 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002174 }
John McCall5c32be02010-08-24 20:38:10 +00002175 User.ConversionFunction = Constructor;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002176 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002177 User.After.setAsIdentityConversion();
2178 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2179 User.After.setAllToTypes(ToType);
2180 return OR_Success;
2181 } else if (CXXConversionDecl *Conversion
2182 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2183 // C++ [over.ics.user]p1:
2184 //
2185 // [...] If the user-defined conversion is specified by a
2186 // conversion function (12.3.2), the initial standard
2187 // conversion sequence converts the source type to the
2188 // implicit object parameter of the conversion function.
2189 User.Before = Best->Conversions[0].Standard;
2190 User.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002191 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002192 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002193
John McCall5c32be02010-08-24 20:38:10 +00002194 // C++ [over.ics.user]p2:
2195 // The second standard conversion sequence converts the
2196 // result of the user-defined conversion to the target type
2197 // for the sequence. Since an implicit conversion sequence
2198 // is an initialization, the special rules for
2199 // initialization by user-defined conversion apply when
2200 // selecting the best user-defined conversion for a
2201 // user-defined conversion sequence (see 13.3.3 and
2202 // 13.3.3.1).
2203 User.After = Best->FinalConversion;
2204 return OR_Success;
2205 } else {
2206 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002207 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002208 }
2209
John McCall5c32be02010-08-24 20:38:10 +00002210 case OR_No_Viable_Function:
2211 return OR_No_Viable_Function;
2212 case OR_Deleted:
2213 // No conversion here! We're done.
2214 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002215
John McCall5c32be02010-08-24 20:38:10 +00002216 case OR_Ambiguous:
2217 return OR_Ambiguous;
2218 }
2219
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002220 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002221}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002222
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002223bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002224Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002225 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002226 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002227 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002228 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002229 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002230 if (OvResult == OR_Ambiguous)
2231 Diag(From->getSourceRange().getBegin(),
2232 diag::err_typecheck_ambiguous_condition)
2233 << From->getType() << ToType << From->getSourceRange();
2234 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2235 Diag(From->getSourceRange().getBegin(),
2236 diag::err_typecheck_nonviable_condition)
2237 << From->getType() << ToType << From->getSourceRange();
2238 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002239 return false;
John McCall5c32be02010-08-24 20:38:10 +00002240 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002241 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002242}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002243
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002244/// CompareImplicitConversionSequences - Compare two implicit
2245/// conversion sequences to determine whether one is better than the
2246/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002247static ImplicitConversionSequence::CompareKind
2248CompareImplicitConversionSequences(Sema &S,
2249 const ImplicitConversionSequence& ICS1,
2250 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002251{
2252 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2253 // conversion sequences (as defined in 13.3.3.1)
2254 // -- a standard conversion sequence (13.3.3.1.1) is a better
2255 // conversion sequence than a user-defined conversion sequence or
2256 // an ellipsis conversion sequence, and
2257 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2258 // conversion sequence than an ellipsis conversion sequence
2259 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002260 //
John McCall0d1da222010-01-12 00:44:57 +00002261 // C++0x [over.best.ics]p10:
2262 // For the purpose of ranking implicit conversion sequences as
2263 // described in 13.3.3.2, the ambiguous conversion sequence is
2264 // treated as a user-defined sequence that is indistinguishable
2265 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002266 if (ICS1.getKindRank() < ICS2.getKindRank())
2267 return ImplicitConversionSequence::Better;
2268 else if (ICS2.getKindRank() < ICS1.getKindRank())
2269 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002270
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002271 // The following checks require both conversion sequences to be of
2272 // the same kind.
2273 if (ICS1.getKind() != ICS2.getKind())
2274 return ImplicitConversionSequence::Indistinguishable;
2275
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002276 // Two implicit conversion sequences of the same form are
2277 // indistinguishable conversion sequences unless one of the
2278 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002279 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002280 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002281 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002282 // User-defined conversion sequence U1 is a better conversion
2283 // sequence than another user-defined conversion sequence U2 if
2284 // they contain the same user-defined conversion function or
2285 // constructor and if the second standard conversion sequence of
2286 // U1 is better than the second standard conversion sequence of
2287 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002288 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002289 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002290 return CompareStandardConversionSequences(S,
2291 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002292 ICS2.UserDefined.After);
2293 }
2294
2295 return ImplicitConversionSequence::Indistinguishable;
2296}
2297
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002298static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2299 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2300 Qualifiers Quals;
2301 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002302 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002303 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002304
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002305 return Context.hasSameUnqualifiedType(T1, T2);
2306}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002307
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002308// Per 13.3.3.2p3, compare the given standard conversion sequences to
2309// determine if one is a proper subset of the other.
2310static ImplicitConversionSequence::CompareKind
2311compareStandardConversionSubsets(ASTContext &Context,
2312 const StandardConversionSequence& SCS1,
2313 const StandardConversionSequence& SCS2) {
2314 ImplicitConversionSequence::CompareKind Result
2315 = ImplicitConversionSequence::Indistinguishable;
2316
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002317 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002318 // any non-identity conversion sequence
2319 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2320 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2321 return ImplicitConversionSequence::Better;
2322 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2323 return ImplicitConversionSequence::Worse;
2324 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002325
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002326 if (SCS1.Second != SCS2.Second) {
2327 if (SCS1.Second == ICK_Identity)
2328 Result = ImplicitConversionSequence::Better;
2329 else if (SCS2.Second == ICK_Identity)
2330 Result = ImplicitConversionSequence::Worse;
2331 else
2332 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002333 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002334 return ImplicitConversionSequence::Indistinguishable;
2335
2336 if (SCS1.Third == SCS2.Third) {
2337 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2338 : ImplicitConversionSequence::Indistinguishable;
2339 }
2340
2341 if (SCS1.Third == ICK_Identity)
2342 return Result == ImplicitConversionSequence::Worse
2343 ? ImplicitConversionSequence::Indistinguishable
2344 : ImplicitConversionSequence::Better;
2345
2346 if (SCS2.Third == ICK_Identity)
2347 return Result == ImplicitConversionSequence::Better
2348 ? ImplicitConversionSequence::Indistinguishable
2349 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002350
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002351 return ImplicitConversionSequence::Indistinguishable;
2352}
2353
Douglas Gregore696ebb2011-01-26 14:52:12 +00002354/// \brief Determine whether one of the given reference bindings is better
2355/// than the other based on what kind of bindings they are.
2356static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2357 const StandardConversionSequence &SCS2) {
2358 // C++0x [over.ics.rank]p3b4:
2359 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2360 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002361 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002362 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002363 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002364 // reference*.
2365 //
2366 // FIXME: Rvalue references. We're going rogue with the above edits,
2367 // because the semantics in the current C++0x working paper (N3225 at the
2368 // time of this writing) break the standard definition of std::forward
2369 // and std::reference_wrapper when dealing with references to functions.
2370 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002371 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2372 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2373 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002374
Douglas Gregore696ebb2011-01-26 14:52:12 +00002375 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2376 SCS2.IsLvalueReference) ||
2377 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2378 !SCS2.IsLvalueReference);
2379}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002380
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002381/// CompareStandardConversionSequences - Compare two standard
2382/// conversion sequences to determine whether one is better than the
2383/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002384static ImplicitConversionSequence::CompareKind
2385CompareStandardConversionSequences(Sema &S,
2386 const StandardConversionSequence& SCS1,
2387 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002388{
2389 // Standard conversion sequence S1 is a better conversion sequence
2390 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2391
2392 // -- S1 is a proper subsequence of S2 (comparing the conversion
2393 // sequences in the canonical form defined by 13.3.3.1.1,
2394 // excluding any Lvalue Transformation; the identity conversion
2395 // sequence is considered to be a subsequence of any
2396 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002397 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002398 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002399 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002400
2401 // -- the rank of S1 is better than the rank of S2 (by the rules
2402 // defined below), or, if not that,
2403 ImplicitConversionRank Rank1 = SCS1.getRank();
2404 ImplicitConversionRank Rank2 = SCS2.getRank();
2405 if (Rank1 < Rank2)
2406 return ImplicitConversionSequence::Better;
2407 else if (Rank2 < Rank1)
2408 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002409
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002410 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2411 // are indistinguishable unless one of the following rules
2412 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002413
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002414 // A conversion that is not a conversion of a pointer, or
2415 // pointer to member, to bool is better than another conversion
2416 // that is such a conversion.
2417 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2418 return SCS2.isPointerConversionToBool()
2419 ? ImplicitConversionSequence::Better
2420 : ImplicitConversionSequence::Worse;
2421
Douglas Gregor5c407d92008-10-23 00:40:37 +00002422 // C++ [over.ics.rank]p4b2:
2423 //
2424 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002425 // conversion of B* to A* is better than conversion of B* to
2426 // void*, and conversion of A* to void* is better than conversion
2427 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002428 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002429 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002430 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002431 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002432 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2433 // Exactly one of the conversion sequences is a conversion to
2434 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002435 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2436 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002437 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2438 // Neither conversion sequence converts to a void pointer; compare
2439 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002440 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002441 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002442 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002443 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2444 // Both conversion sequences are conversions to void
2445 // pointers. Compare the source types to determine if there's an
2446 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002447 QualType FromType1 = SCS1.getFromType();
2448 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002449
2450 // Adjust the types we're converting from via the array-to-pointer
2451 // conversion, if we need to.
2452 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002453 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002454 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002455 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002456
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002457 QualType FromPointee1
2458 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2459 QualType FromPointee2
2460 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002461
John McCall5c32be02010-08-24 20:38:10 +00002462 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002463 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002464 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002465 return ImplicitConversionSequence::Worse;
2466
2467 // Objective-C++: If one interface is more specific than the
2468 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002469 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2470 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002471 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002472 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002473 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002474 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002475 return ImplicitConversionSequence::Worse;
2476 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002477 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002478
2479 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2480 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002481 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002482 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002483 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002484
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002485 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002486 // Check for a better reference binding based on the kind of bindings.
2487 if (isBetterReferenceBindingKind(SCS1, SCS2))
2488 return ImplicitConversionSequence::Better;
2489 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2490 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002491
Sebastian Redlb28b4072009-03-22 23:49:27 +00002492 // C++ [over.ics.rank]p3b4:
2493 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2494 // which the references refer are the same type except for
2495 // top-level cv-qualifiers, and the type to which the reference
2496 // initialized by S2 refers is more cv-qualified than the type
2497 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002498 QualType T1 = SCS1.getToType(2);
2499 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002500 T1 = S.Context.getCanonicalType(T1);
2501 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002502 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002503 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2504 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002505 if (UnqualT1 == UnqualT2) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00002506 // If the type is an array type, promote the element qualifiers to the
2507 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002508 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002509 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002510 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002511 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002512 if (T2.isMoreQualifiedThan(T1))
2513 return ImplicitConversionSequence::Better;
2514 else if (T1.isMoreQualifiedThan(T2))
2515 return ImplicitConversionSequence::Worse;
2516 }
2517 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002518
2519 return ImplicitConversionSequence::Indistinguishable;
2520}
2521
2522/// CompareQualificationConversions - Compares two standard conversion
2523/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002524/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2525ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002526CompareQualificationConversions(Sema &S,
2527 const StandardConversionSequence& SCS1,
2528 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002529 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002530 // -- S1 and S2 differ only in their qualification conversion and
2531 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2532 // cv-qualification signature of type T1 is a proper subset of
2533 // the cv-qualification signature of type T2, and S1 is not the
2534 // deprecated string literal array-to-pointer conversion (4.2).
2535 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2536 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2537 return ImplicitConversionSequence::Indistinguishable;
2538
2539 // FIXME: the example in the standard doesn't use a qualification
2540 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002541 QualType T1 = SCS1.getToType(2);
2542 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002543 T1 = S.Context.getCanonicalType(T1);
2544 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002545 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002546 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2547 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002548
2549 // If the types are the same, we won't learn anything by unwrapped
2550 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002551 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002552 return ImplicitConversionSequence::Indistinguishable;
2553
Chandler Carruth607f38e2009-12-29 07:16:59 +00002554 // If the type is an array type, promote the element qualifiers to the type
2555 // for comparison.
2556 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002557 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002558 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002559 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002560
Mike Stump11289f42009-09-09 15:08:12 +00002561 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002562 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002563 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002564 // Within each iteration of the loop, we check the qualifiers to
2565 // determine if this still looks like a qualification
2566 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002567 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002568 // until there are no more pointers or pointers-to-members left
2569 // to unwrap. This essentially mimics what
2570 // IsQualificationConversion does, but here we're checking for a
2571 // strict subset of qualifiers.
2572 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2573 // The qualifiers are the same, so this doesn't tell us anything
2574 // about how the sequences rank.
2575 ;
2576 else if (T2.isMoreQualifiedThan(T1)) {
2577 // T1 has fewer qualifiers, so it could be the better sequence.
2578 if (Result == ImplicitConversionSequence::Worse)
2579 // Neither has qualifiers that are a subset of the other's
2580 // qualifiers.
2581 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002582
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002583 Result = ImplicitConversionSequence::Better;
2584 } else if (T1.isMoreQualifiedThan(T2)) {
2585 // T2 has fewer qualifiers, so it could be the better sequence.
2586 if (Result == ImplicitConversionSequence::Better)
2587 // Neither has qualifiers that are a subset of the other's
2588 // qualifiers.
2589 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002590
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002591 Result = ImplicitConversionSequence::Worse;
2592 } else {
2593 // Qualifiers are disjoint.
2594 return ImplicitConversionSequence::Indistinguishable;
2595 }
2596
2597 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002598 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002599 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002600 }
2601
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002602 // Check that the winning standard conversion sequence isn't using
2603 // the deprecated string literal array to pointer conversion.
2604 switch (Result) {
2605 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002606 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002607 Result = ImplicitConversionSequence::Indistinguishable;
2608 break;
2609
2610 case ImplicitConversionSequence::Indistinguishable:
2611 break;
2612
2613 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002614 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002615 Result = ImplicitConversionSequence::Indistinguishable;
2616 break;
2617 }
2618
2619 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002620}
2621
Douglas Gregor5c407d92008-10-23 00:40:37 +00002622/// CompareDerivedToBaseConversions - Compares two standard conversion
2623/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002624/// various kinds of derived-to-base conversions (C++
2625/// [over.ics.rank]p4b3). As part of these checks, we also look at
2626/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002627ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002628CompareDerivedToBaseConversions(Sema &S,
2629 const StandardConversionSequence& SCS1,
2630 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002631 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002632 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002633 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002634 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002635
2636 // Adjust the types we're converting from via the array-to-pointer
2637 // conversion, if we need to.
2638 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002639 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002640 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002641 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002642
2643 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002644 FromType1 = S.Context.getCanonicalType(FromType1);
2645 ToType1 = S.Context.getCanonicalType(ToType1);
2646 FromType2 = S.Context.getCanonicalType(FromType2);
2647 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002648
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002649 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002650 //
2651 // If class B is derived directly or indirectly from class A and
2652 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002653 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002654 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002655 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002656 SCS2.Second == ICK_Pointer_Conversion &&
2657 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2658 FromType1->isPointerType() && FromType2->isPointerType() &&
2659 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002660 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002661 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002662 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002663 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002664 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002665 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002666 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002667 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002668
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002669 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002670 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002671 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002672 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002673 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002674 return ImplicitConversionSequence::Worse;
2675 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002676
2677 // -- conversion of B* to A* is better than conversion of C* to A*,
2678 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002679 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002680 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002681 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002682 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00002683 }
2684 } else if (SCS1.Second == ICK_Pointer_Conversion &&
2685 SCS2.Second == ICK_Pointer_Conversion) {
2686 const ObjCObjectPointerType *FromPtr1
2687 = FromType1->getAs<ObjCObjectPointerType>();
2688 const ObjCObjectPointerType *FromPtr2
2689 = FromType2->getAs<ObjCObjectPointerType>();
2690 const ObjCObjectPointerType *ToPtr1
2691 = ToType1->getAs<ObjCObjectPointerType>();
2692 const ObjCObjectPointerType *ToPtr2
2693 = ToType2->getAs<ObjCObjectPointerType>();
2694
2695 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
2696 // Apply the same conversion ranking rules for Objective-C pointer types
2697 // that we do for C++ pointers to class types. However, we employ the
2698 // Objective-C pseudo-subtyping relationship used for assignment of
2699 // Objective-C pointer types.
2700 bool FromAssignLeft
2701 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
2702 bool FromAssignRight
2703 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
2704 bool ToAssignLeft
2705 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
2706 bool ToAssignRight
2707 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
2708
2709 // A conversion to an a non-id object pointer type or qualified 'id'
2710 // type is better than a conversion to 'id'.
2711 if (ToPtr1->isObjCIdType() &&
2712 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
2713 return ImplicitConversionSequence::Worse;
2714 if (ToPtr2->isObjCIdType() &&
2715 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
2716 return ImplicitConversionSequence::Better;
2717
2718 // A conversion to a non-id object pointer type is better than a
2719 // conversion to a qualified 'id' type
2720 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
2721 return ImplicitConversionSequence::Worse;
2722 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
2723 return ImplicitConversionSequence::Better;
2724
2725 // A conversion to an a non-Class object pointer type or qualified 'Class'
2726 // type is better than a conversion to 'Class'.
2727 if (ToPtr1->isObjCClassType() &&
2728 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
2729 return ImplicitConversionSequence::Worse;
2730 if (ToPtr2->isObjCClassType() &&
2731 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
2732 return ImplicitConversionSequence::Better;
2733
2734 // A conversion to a non-Class object pointer type is better than a
2735 // conversion to a qualified 'Class' type.
2736 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
2737 return ImplicitConversionSequence::Worse;
2738 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
2739 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00002740
Douglas Gregor058d3de2011-01-31 18:51:41 +00002741 // -- "conversion of C* to B* is better than conversion of C* to A*,"
2742 if (S.Context.hasSameType(FromType1, FromType2) &&
2743 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
2744 (ToAssignLeft != ToAssignRight))
2745 return ToAssignLeft? ImplicitConversionSequence::Worse
2746 : ImplicitConversionSequence::Better;
2747
2748 // -- "conversion of B* to A* is better than conversion of C* to A*,"
2749 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
2750 (FromAssignLeft != FromAssignRight))
2751 return FromAssignLeft? ImplicitConversionSequence::Better
2752 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002753 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002754 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00002755
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002756 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002757 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2758 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2759 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002760 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002761 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002762 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002763 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002764 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002765 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002766 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002767 ToType2->getAs<MemberPointerType>();
2768 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2769 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2770 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2771 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2772 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2773 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2774 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2775 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002776 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002777 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002778 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002779 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002780 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002781 return ImplicitConversionSequence::Better;
2782 }
2783 // conversion of B::* to C::* is better than conversion of A::* to C::*
2784 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002785 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002786 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002787 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002788 return ImplicitConversionSequence::Worse;
2789 }
2790 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002791
Douglas Gregor5ab11652010-04-17 22:01:05 +00002792 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002793 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002794 // -- binding of an expression of type C to a reference of type
2795 // B& is better than binding an expression of type C to a
2796 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002797 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2798 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2799 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002800 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002801 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002802 return ImplicitConversionSequence::Worse;
2803 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002804
Douglas Gregor2fe98832008-11-03 19:09:14 +00002805 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002806 // -- binding of an expression of type B to a reference of type
2807 // A& is better than binding an expression of type C to a
2808 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002809 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2810 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2811 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002812 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002813 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002814 return ImplicitConversionSequence::Worse;
2815 }
2816 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002817
Douglas Gregor5c407d92008-10-23 00:40:37 +00002818 return ImplicitConversionSequence::Indistinguishable;
2819}
2820
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002821/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2822/// determine whether they are reference-related,
2823/// reference-compatible, reference-compatible with added
2824/// qualification, or incompatible, for use in C++ initialization by
2825/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2826/// type, and the first type (T1) is the pointee type of the reference
2827/// type being initialized.
2828Sema::ReferenceCompareResult
2829Sema::CompareReferenceRelationship(SourceLocation Loc,
2830 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002831 bool &DerivedToBase,
2832 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002833 assert(!OrigT1->isReferenceType() &&
2834 "T1 must be the pointee type of the reference type");
2835 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2836
2837 QualType T1 = Context.getCanonicalType(OrigT1);
2838 QualType T2 = Context.getCanonicalType(OrigT2);
2839 Qualifiers T1Quals, T2Quals;
2840 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2841 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2842
2843 // C++ [dcl.init.ref]p4:
2844 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2845 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2846 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002847 DerivedToBase = false;
2848 ObjCConversion = false;
2849 if (UnqualT1 == UnqualT2) {
2850 // Nothing to do.
2851 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002852 IsDerivedFrom(UnqualT2, UnqualT1))
2853 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002854 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2855 UnqualT2->isObjCObjectOrInterfaceType() &&
2856 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2857 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002858 else
2859 return Ref_Incompatible;
2860
2861 // At this point, we know that T1 and T2 are reference-related (at
2862 // least).
2863
2864 // If the type is an array type, promote the element qualifiers to the type
2865 // for comparison.
2866 if (isa<ArrayType>(T1) && T1Quals)
2867 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2868 if (isa<ArrayType>(T2) && T2Quals)
2869 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2870
2871 // C++ [dcl.init.ref]p4:
2872 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2873 // reference-related to T2 and cv1 is the same cv-qualification
2874 // as, or greater cv-qualification than, cv2. For purposes of
2875 // overload resolution, cases for which cv1 is greater
2876 // cv-qualification than cv2 are identified as
2877 // reference-compatible with added qualification (see 13.3.3.2).
2878 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2879 return Ref_Compatible;
2880 else if (T1.isMoreQualifiedThan(T2))
2881 return Ref_Compatible_With_Added_Qualification;
2882 else
2883 return Ref_Related;
2884}
2885
Douglas Gregor836a7e82010-08-11 02:15:33 +00002886/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002887/// with DeclType. Return true if something definite is found.
2888static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002889FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2890 QualType DeclType, SourceLocation DeclLoc,
2891 Expr *Init, QualType T2, bool AllowRvalues,
2892 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002893 assert(T2->isRecordType() && "Can only find conversions of record types.");
2894 CXXRecordDecl *T2RecordDecl
2895 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2896
2897 OverloadCandidateSet CandidateSet(DeclLoc);
2898 const UnresolvedSetImpl *Conversions
2899 = T2RecordDecl->getVisibleConversionFunctions();
2900 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2901 E = Conversions->end(); I != E; ++I) {
2902 NamedDecl *D = *I;
2903 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2904 if (isa<UsingShadowDecl>(D))
2905 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2906
2907 FunctionTemplateDecl *ConvTemplate
2908 = dyn_cast<FunctionTemplateDecl>(D);
2909 CXXConversionDecl *Conv;
2910 if (ConvTemplate)
2911 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2912 else
2913 Conv = cast<CXXConversionDecl>(D);
2914
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002915 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00002916 // explicit conversions, skip it.
2917 if (!AllowExplicit && Conv->isExplicit())
2918 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002919
Douglas Gregor836a7e82010-08-11 02:15:33 +00002920 if (AllowRvalues) {
2921 bool DerivedToBase = false;
2922 bool ObjCConversion = false;
2923 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00002924 S.CompareReferenceRelationship(
2925 DeclLoc,
2926 Conv->getConversionType().getNonReferenceType()
2927 .getUnqualifiedType(),
2928 DeclType.getNonReferenceType().getUnqualifiedType(),
2929 DerivedToBase, ObjCConversion) ==
2930 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00002931 continue;
2932 } else {
2933 // If the conversion function doesn't return a reference type,
2934 // it can't be considered for this conversion. An rvalue reference
2935 // is only acceptable if its referencee is a function type.
2936
2937 const ReferenceType *RefType =
2938 Conv->getConversionType()->getAs<ReferenceType>();
2939 if (!RefType ||
2940 (!RefType->isLValueReferenceType() &&
2941 !RefType->getPointeeType()->isFunctionType()))
2942 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002943 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002944
Douglas Gregor836a7e82010-08-11 02:15:33 +00002945 if (ConvTemplate)
2946 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00002947 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00002948 else
2949 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00002950 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002951 }
2952
2953 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002954 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002955 case OR_Success:
2956 // C++ [over.ics.ref]p1:
2957 //
2958 // [...] If the parameter binds directly to the result of
2959 // applying a conversion function to the argument
2960 // expression, the implicit conversion sequence is a
2961 // user-defined conversion sequence (13.3.3.1.2), with the
2962 // second standard conversion sequence either an identity
2963 // conversion or, if the conversion function returns an
2964 // entity of a type that is a derived class of the parameter
2965 // type, a derived-to-base Conversion.
2966 if (!Best->FinalConversion.DirectBinding)
2967 return false;
2968
2969 ICS.setUserDefined();
2970 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2971 ICS.UserDefined.After = Best->FinalConversion;
2972 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002973 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redld92badf2010-06-30 18:13:39 +00002974 ICS.UserDefined.EllipsisConversion = false;
2975 assert(ICS.UserDefined.After.ReferenceBinding &&
2976 ICS.UserDefined.After.DirectBinding &&
2977 "Expected a direct reference binding!");
2978 return true;
2979
2980 case OR_Ambiguous:
2981 ICS.setAmbiguous();
2982 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2983 Cand != CandidateSet.end(); ++Cand)
2984 if (Cand->Viable)
2985 ICS.Ambiguous.addConversion(Cand->Function);
2986 return true;
2987
2988 case OR_No_Viable_Function:
2989 case OR_Deleted:
2990 // There was no suitable conversion, or we found a deleted
2991 // conversion; continue with other checks.
2992 return false;
2993 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002994
Eric Christopheraba9fb22010-06-30 18:36:32 +00002995 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002996}
2997
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002998/// \brief Compute an implicit conversion sequence for reference
2999/// initialization.
3000static ImplicitConversionSequence
3001TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3002 SourceLocation DeclLoc,
3003 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003004 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003005 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3006
3007 // Most paths end in a failed conversion.
3008 ImplicitConversionSequence ICS;
3009 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3010
3011 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3012 QualType T2 = Init->getType();
3013
3014 // If the initializer is the address of an overloaded function, try
3015 // to resolve the overloaded function. If all goes well, T2 is the
3016 // type of the resulting function.
3017 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3018 DeclAccessPair Found;
3019 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3020 false, Found))
3021 T2 = Fn->getType();
3022 }
3023
3024 // Compute some basic properties of the types and the initializer.
3025 bool isRValRef = DeclType->isRValueReferenceType();
3026 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003027 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003028 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003029 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003030 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
3031 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003032
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003033
Sebastian Redld92badf2010-06-30 18:13:39 +00003034 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003035 // A reference to type "cv1 T1" is initialized by an expression
3036 // of type "cv2 T2" as follows:
3037
Sebastian Redld92badf2010-06-30 18:13:39 +00003038 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003039 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003040 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3041 // reference-compatible with "cv2 T2," or
3042 //
3043 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3044 if (InitCategory.isLValue() &&
3045 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003046 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003047 // When a parameter of reference type binds directly (8.5.3)
3048 // to an argument expression, the implicit conversion sequence
3049 // is the identity conversion, unless the argument expression
3050 // has a type that is a derived class of the parameter type,
3051 // in which case the implicit conversion sequence is a
3052 // derived-to-base Conversion (13.3.3.1).
3053 ICS.setStandard();
3054 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003055 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3056 : ObjCConversion? ICK_Compatible_Conversion
3057 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003058 ICS.Standard.Third = ICK_Identity;
3059 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3060 ICS.Standard.setToType(0, T2);
3061 ICS.Standard.setToType(1, T1);
3062 ICS.Standard.setToType(2, T1);
3063 ICS.Standard.ReferenceBinding = true;
3064 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003065 ICS.Standard.IsLvalueReference = !isRValRef;
3066 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3067 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003068 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003069 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003070
Sebastian Redld92badf2010-06-30 18:13:39 +00003071 // Nothing more to do: the inaccessibility/ambiguity check for
3072 // derived-to-base conversions is suppressed when we're
3073 // computing the implicit conversion sequence (C++
3074 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003075 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003076 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003077
Sebastian Redld92badf2010-06-30 18:13:39 +00003078 // -- has a class type (i.e., T2 is a class type), where T1 is
3079 // not reference-related to T2, and can be implicitly
3080 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3081 // is reference-compatible with "cv3 T3" 92) (this
3082 // conversion is selected by enumerating the applicable
3083 // conversion functions (13.3.1.6) and choosing the best
3084 // one through overload resolution (13.3)),
3085 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003086 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003087 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003088 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3089 Init, T2, /*AllowRvalues=*/false,
3090 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003091 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003092 }
3093 }
3094
Sebastian Redld92badf2010-06-30 18:13:39 +00003095 // -- Otherwise, the reference shall be an lvalue reference to a
3096 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003097 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003098 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003099 // We actually handle one oddity of C++ [over.ics.ref] at this
3100 // point, which is that, due to p2 (which short-circuits reference
3101 // binding by only attempting a simple conversion for non-direct
3102 // bindings) and p3's strange wording, we allow a const volatile
3103 // reference to bind to an rvalue. Hence the check for the presence
3104 // of "const" rather than checking for "const" being the only
3105 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003106 // This is also the point where rvalue references and lvalue inits no longer
3107 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003108 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003109 return ICS;
3110
Douglas Gregorf143cd52011-01-24 16:14:37 +00003111 // -- If the initializer expression
3112 //
3113 // -- is an xvalue, class prvalue, array prvalue or function
3114 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3115 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3116 (InitCategory.isXValue() ||
3117 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3118 (InitCategory.isLValue() && T2->isFunctionType()))) {
3119 ICS.setStandard();
3120 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003121 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003122 : ObjCConversion? ICK_Compatible_Conversion
3123 : ICK_Identity;
3124 ICS.Standard.Third = ICK_Identity;
3125 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3126 ICS.Standard.setToType(0, T2);
3127 ICS.Standard.setToType(1, T1);
3128 ICS.Standard.setToType(2, T1);
3129 ICS.Standard.ReferenceBinding = true;
3130 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3131 // binding unless we're binding to a class prvalue.
3132 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3133 // allow the use of rvalue references in C++98/03 for the benefit of
3134 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003135 ICS.Standard.DirectBinding =
3136 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003137 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003138 ICS.Standard.IsLvalueReference = !isRValRef;
3139 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003140 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003141 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003142 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003143 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003144 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003145
Douglas Gregorf143cd52011-01-24 16:14:37 +00003146 // -- has a class type (i.e., T2 is a class type), where T1 is not
3147 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003148 // an xvalue, class prvalue, or function lvalue of type
3149 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003150 // "cv3 T3",
3151 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003152 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003153 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003154 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003155 // class subobject).
3156 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003157 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003158 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3159 Init, T2, /*AllowRvalues=*/true,
3160 AllowExplicit)) {
3161 // In the second case, if the reference is an rvalue reference
3162 // and the second standard conversion sequence of the
3163 // user-defined conversion sequence includes an lvalue-to-rvalue
3164 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003165 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003166 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3167 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3168
Douglas Gregor95273c32011-01-21 16:36:05 +00003169 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003170 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003171
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003172 // -- Otherwise, a temporary of type "cv1 T1" is created and
3173 // initialized from the initializer expression using the
3174 // rules for a non-reference copy initialization (8.5). The
3175 // reference is then bound to the temporary. If T1 is
3176 // reference-related to T2, cv1 must be the same
3177 // cv-qualification as, or greater cv-qualification than,
3178 // cv2; otherwise, the program is ill-formed.
3179 if (RefRelationship == Sema::Ref_Related) {
3180 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3181 // we would be reference-compatible or reference-compatible with
3182 // added qualification. But that wasn't the case, so the reference
3183 // initialization fails.
3184 return ICS;
3185 }
3186
3187 // If at least one of the types is a class type, the types are not
3188 // related, and we aren't allowed any user conversions, the
3189 // reference binding fails. This case is important for breaking
3190 // recursion, since TryImplicitConversion below will attempt to
3191 // create a temporary through the use of a copy constructor.
3192 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3193 (T1->isRecordType() || T2->isRecordType()))
3194 return ICS;
3195
Douglas Gregorcba72b12011-01-21 05:18:22 +00003196 // If T1 is reference-related to T2 and the reference is an rvalue
3197 // reference, the initializer expression shall not be an lvalue.
3198 if (RefRelationship >= Sema::Ref_Related &&
3199 isRValRef && Init->Classify(S.Context).isLValue())
3200 return ICS;
3201
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003202 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003203 // When a parameter of reference type is not bound directly to
3204 // an argument expression, the conversion sequence is the one
3205 // required to convert the argument expression to the
3206 // underlying type of the reference according to
3207 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3208 // to copy-initializing a temporary of the underlying type with
3209 // the argument expression. Any difference in top-level
3210 // cv-qualification is subsumed by the initialization itself
3211 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003212 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3213 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003214 /*InOverloadResolution=*/false,
3215 /*CStyle=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003216
3217 // Of course, that's still a reference binding.
3218 if (ICS.isStandard()) {
3219 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003220 ICS.Standard.IsLvalueReference = !isRValRef;
3221 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3222 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003223 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003224 } else if (ICS.isUserDefined()) {
3225 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003226 ICS.Standard.IsLvalueReference = !isRValRef;
3227 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3228 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003229 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003230 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003231
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003232 return ICS;
3233}
3234
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003235/// TryCopyInitialization - Try to copy-initialize a value of type
3236/// ToType from the expression From. Return the implicit conversion
3237/// sequence required to pass this argument, which may be a bad
3238/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003239/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003240/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003241static ImplicitConversionSequence
3242TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003243 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003244 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003245 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003246 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003247 /*FIXME:*/From->getLocStart(),
3248 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003249 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003250
John McCall5c32be02010-08-24 20:38:10 +00003251 return TryImplicitConversion(S, From, ToType,
3252 SuppressUserConversions,
3253 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003254 InOverloadResolution,
3255 /*CStyle=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003256}
3257
Douglas Gregor436424c2008-11-18 23:14:02 +00003258/// TryObjectArgumentInitialization - Try to initialize the object
3259/// parameter of the given member function (@c Method) from the
3260/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003261static ImplicitConversionSequence
3262TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003263 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003264 CXXMethodDecl *Method,
3265 CXXRecordDecl *ActingContext) {
3266 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003267 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3268 // const volatile object.
3269 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3270 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003271 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003272
3273 // Set up the conversion sequence as a "bad" conversion, to allow us
3274 // to exit early.
3275 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003276
3277 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003278 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003279 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003280 FromType = PT->getPointeeType();
3281
Douglas Gregor02824322011-01-26 19:30:28 +00003282 // When we had a pointer, it's implicitly dereferenced, so we
3283 // better have an lvalue.
3284 assert(FromClassification.isLValue());
3285 }
3286
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003287 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003288
Douglas Gregor02824322011-01-26 19:30:28 +00003289 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003290 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003291 // parameter is
3292 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003293 // - "lvalue reference to cv X" for functions declared without a
3294 // ref-qualifier or with the & ref-qualifier
3295 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003296 // ref-qualifier
3297 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003298 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003299 // cv-qualification on the member function declaration.
3300 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003301 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003302 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003303 // (C++ [over.match.funcs]p5). We perform a simplified version of
3304 // reference binding here, that allows class rvalues to bind to
3305 // non-constant references.
3306
Douglas Gregor02824322011-01-26 19:30:28 +00003307 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003308 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003309 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003310 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003311 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003312 ICS.setBad(BadConversionSequence::bad_qualifiers,
3313 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003314 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003315 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003316
3317 // Check that we have either the same type or a derived type. It
3318 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003319 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003320 ImplicitConversionKind SecondKind;
3321 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3322 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003323 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003324 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003325 else {
John McCall65eb8792010-02-25 01:37:24 +00003326 ICS.setBad(BadConversionSequence::unrelated_class,
3327 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003328 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003329 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003330
Douglas Gregor02824322011-01-26 19:30:28 +00003331 // Check the ref-qualifier.
3332 switch (Method->getRefQualifier()) {
3333 case RQ_None:
3334 // Do nothing; we don't care about lvalueness or rvalueness.
3335 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003336
Douglas Gregor02824322011-01-26 19:30:28 +00003337 case RQ_LValue:
3338 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3339 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003340 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003341 ImplicitParamType);
3342 return ICS;
3343 }
3344 break;
3345
3346 case RQ_RValue:
3347 if (!FromClassification.isRValue()) {
3348 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003349 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003350 ImplicitParamType);
3351 return ICS;
3352 }
3353 break;
3354 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003355
Douglas Gregor436424c2008-11-18 23:14:02 +00003356 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003357 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003358 ICS.Standard.setAsIdentityConversion();
3359 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003360 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003361 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003362 ICS.Standard.ReferenceBinding = true;
3363 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003364 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003365 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003366 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3367 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3368 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003369 return ICS;
3370}
3371
3372/// PerformObjectArgumentInitialization - Perform initialization of
3373/// the implicit object parameter for the given Method with the given
3374/// expression.
3375bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003376Sema::PerformObjectArgumentInitialization(Expr *&From,
3377 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003378 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003379 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003380 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003381 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003382 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003383
Douglas Gregor02824322011-01-26 19:30:28 +00003384 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003385 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003386 FromRecordType = PT->getPointeeType();
3387 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003388 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003389 } else {
3390 FromRecordType = From->getType();
3391 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003392 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003393 }
3394
John McCall6e9f8f62009-12-03 04:06:58 +00003395 // Note that we always use the true parent context when performing
3396 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003397 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003398 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3399 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003400 if (ICS.isBad()) {
3401 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3402 Qualifiers FromQs = FromRecordType.getQualifiers();
3403 Qualifiers ToQs = DestType.getQualifiers();
3404 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3405 if (CVR) {
3406 Diag(From->getSourceRange().getBegin(),
3407 diag::err_member_function_call_bad_cvr)
3408 << Method->getDeclName() << FromRecordType << (CVR - 1)
3409 << From->getSourceRange();
3410 Diag(Method->getLocation(), diag::note_previous_decl)
3411 << Method->getDeclName();
3412 return true;
3413 }
3414 }
3415
Douglas Gregor436424c2008-11-18 23:14:02 +00003416 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003417 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003418 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003419 }
Mike Stump11289f42009-09-09 15:08:12 +00003420
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003421 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003422 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003423
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003424 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003425 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003426 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003427 return false;
3428}
3429
Douglas Gregor5fb53972009-01-14 15:45:31 +00003430/// TryContextuallyConvertToBool - Attempt to contextually convert the
3431/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003432static ImplicitConversionSequence
3433TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003434 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003435 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003436 // FIXME: Are these flags correct?
3437 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003438 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003439 /*InOverloadResolution=*/false,
3440 /*CStyle=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003441}
3442
3443/// PerformContextuallyConvertToBool - Perform a contextual conversion
3444/// of the expression From to bool (C++0x [conv]p3).
3445bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003446 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003447 if (!ICS.isBad())
3448 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003449
Fariborz Jahanian76197412009-11-18 18:26:29 +00003450 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003451 return Diag(From->getSourceRange().getBegin(),
3452 diag::err_typecheck_bool_condition)
3453 << From->getType() << From->getSourceRange();
3454 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003455}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003456
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003457/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3458/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003459static ImplicitConversionSequence
3460TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3461 QualType Ty = S.Context.getObjCIdType();
3462 return TryImplicitConversion(S, From, Ty,
3463 // FIXME: Are these flags correct?
3464 /*SuppressUserConversions=*/false,
3465 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003466 /*InOverloadResolution=*/false,
3467 /*CStyle=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003468}
John McCall5c32be02010-08-24 20:38:10 +00003469
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003470/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3471/// of the expression From to 'id'.
3472bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003473 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003474 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003475 if (!ICS.isBad())
3476 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3477 return true;
3478}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003479
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003480/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003481/// enumeration type.
3482///
3483/// This routine will attempt to convert an expression of class type to an
3484/// integral or enumeration type, if that class type only has a single
3485/// conversion to an integral or enumeration type.
3486///
Douglas Gregor4799d032010-06-30 00:20:43 +00003487/// \param Loc The source location of the construct that requires the
3488/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003489///
Douglas Gregor4799d032010-06-30 00:20:43 +00003490/// \param FromE The expression we're converting from.
3491///
3492/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3493/// have integral or enumeration type.
3494///
3495/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3496/// incomplete class type.
3497///
3498/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3499/// explicit conversion function (because no implicit conversion functions
3500/// were available). This is a recovery mode.
3501///
3502/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3503/// showing which conversion was picked.
3504///
3505/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3506/// conversion function that could convert to integral or enumeration type.
3507///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003508/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00003509/// usable conversion function.
3510///
3511/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3512/// function, which may be an extension in this case.
3513///
3514/// \returns The expression, converted to an integral or enumeration type if
3515/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003516ExprResult
John McCallb268a282010-08-23 23:25:46 +00003517Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003518 const PartialDiagnostic &NotIntDiag,
3519 const PartialDiagnostic &IncompleteDiag,
3520 const PartialDiagnostic &ExplicitConvDiag,
3521 const PartialDiagnostic &ExplicitConvNote,
3522 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003523 const PartialDiagnostic &AmbigNote,
3524 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003525 // We can't perform any more checking for type-dependent expressions.
3526 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003527 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003528
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003529 // If the expression already has integral or enumeration type, we're golden.
3530 QualType T = From->getType();
3531 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003532 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003533
3534 // FIXME: Check for missing '()' if T is a function type?
3535
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003536 // 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 +00003537 // expression of integral or enumeration type.
3538 const RecordType *RecordTy = T->getAs<RecordType>();
3539 if (!RecordTy || !getLangOptions().CPlusPlus) {
3540 Diag(Loc, NotIntDiag)
3541 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003542 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003543 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003544
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003545 // We must have a complete class type.
3546 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003547 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003548
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003549 // Look for a conversion to an integral or enumeration type.
3550 UnresolvedSet<4> ViableConversions;
3551 UnresolvedSet<4> ExplicitConversions;
3552 const UnresolvedSetImpl *Conversions
3553 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003554
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003555 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003556 E = Conversions->end();
3557 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003558 ++I) {
3559 if (CXXConversionDecl *Conversion
3560 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3561 if (Conversion->getConversionType().getNonReferenceType()
3562 ->isIntegralOrEnumerationType()) {
3563 if (Conversion->isExplicit())
3564 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3565 else
3566 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3567 }
3568 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003569
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003570 switch (ViableConversions.size()) {
3571 case 0:
3572 if (ExplicitConversions.size() == 1) {
3573 DeclAccessPair Found = ExplicitConversions[0];
3574 CXXConversionDecl *Conversion
3575 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003576
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003577 // The user probably meant to invoke the given explicit
3578 // conversion; use it.
3579 QualType ConvTy
3580 = Conversion->getConversionType().getNonReferenceType();
3581 std::string TypeStr;
3582 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003583
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003584 Diag(Loc, ExplicitConvDiag)
3585 << T << ConvTy
3586 << FixItHint::CreateInsertion(From->getLocStart(),
3587 "static_cast<" + TypeStr + ">(")
3588 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3589 ")");
3590 Diag(Conversion->getLocation(), ExplicitConvNote)
3591 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003592
3593 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003594 // explicit conversion function.
3595 if (isSFINAEContext())
3596 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003597
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003598 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00003599 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3600 if (Result.isInvalid())
3601 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003602
Douglas Gregor668443e2011-01-20 00:18:04 +00003603 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003605
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003606 // We'll complain below about a non-integral condition type.
3607 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003608
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003609 case 1: {
3610 // Apply this conversion.
3611 DeclAccessPair Found = ViableConversions[0];
3612 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003613
Douglas Gregor4799d032010-06-30 00:20:43 +00003614 CXXConversionDecl *Conversion
3615 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3616 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003617 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00003618 if (ConvDiag.getDiagID()) {
3619 if (isSFINAEContext())
3620 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003621
Douglas Gregor4799d032010-06-30 00:20:43 +00003622 Diag(Loc, ConvDiag)
3623 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3624 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003625
Douglas Gregor668443e2011-01-20 00:18:04 +00003626 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003627 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00003628 if (Result.isInvalid())
3629 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003630
Douglas Gregor668443e2011-01-20 00:18:04 +00003631 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003632 break;
3633 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003634
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003635 default:
3636 Diag(Loc, AmbigDiag)
3637 << T << From->getSourceRange();
3638 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3639 CXXConversionDecl *Conv
3640 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3641 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3642 Diag(Conv->getLocation(), AmbigNote)
3643 << ConvTy->isEnumeralType() << ConvTy;
3644 }
John McCallb268a282010-08-23 23:25:46 +00003645 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003646 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003647
Douglas Gregor5823da32010-06-29 23:25:20 +00003648 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003649 Diag(Loc, NotIntDiag)
3650 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003651
John McCallb268a282010-08-23 23:25:46 +00003652 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003653}
3654
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003655/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003656/// candidate functions, using the given function call arguments. If
3657/// @p SuppressUserConversions, then don't allow user-defined
3658/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003659///
3660/// \para PartialOverloading true if we are performing "partial" overloading
3661/// based on an incomplete set of function arguments. This feature is used by
3662/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003663void
3664Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003665 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003666 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003667 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003668 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003669 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003670 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003671 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003672 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003673 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003674 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003675
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003676 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003677 if (!isa<CXXConstructorDecl>(Method)) {
3678 // If we get here, it's because we're calling a member function
3679 // that is named without a member access expression (e.g.,
3680 // "this->f") that was either written explicitly or created
3681 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003682 // function, e.g., X::f(). We use an empty type for the implied
3683 // object argument (C++ [over.call.func]p3), and the acting context
3684 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003685 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003686 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00003687 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003688 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003689 return;
3690 }
3691 // We treat a constructor like a non-member function, since its object
3692 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003693 }
3694
Douglas Gregorff7028a2009-11-13 23:59:09 +00003695 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003696 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003697
Douglas Gregor27381f32009-11-23 12:27:39 +00003698 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003699 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003700
Douglas Gregorffe14e32009-11-14 01:20:54 +00003701 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3702 // C++ [class.copy]p3:
3703 // A member function template is never instantiated to perform the copy
3704 // of a class object to an object of its class type.
3705 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003706 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003707 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003708 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3709 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003710 return;
3711 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003712
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003713 // Add this candidate
3714 CandidateSet.push_back(OverloadCandidate());
3715 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003716 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003717 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003718 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003719 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003720 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003721 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003722
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003723 unsigned NumArgsInProto = Proto->getNumArgs();
3724
3725 // (C++ 13.3.2p2): A candidate function having fewer than m
3726 // parameters is viable only if it has an ellipsis in its parameter
3727 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003728 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00003729 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003730 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003731 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003732 return;
3733 }
3734
3735 // (C++ 13.3.2p2): A candidate function having more than m parameters
3736 // is viable only if the (m+1)st parameter has a default argument
3737 // (8.3.6). For the purposes of overload resolution, the
3738 // parameter list is truncated on the right, so that there are
3739 // exactly m parameters.
3740 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003741 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003742 // Not enough arguments.
3743 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003744 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003745 return;
3746 }
3747
3748 // Determine the implicit conversion sequences for each of the
3749 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003750 Candidate.Conversions.resize(NumArgs);
3751 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3752 if (ArgIdx < NumArgsInProto) {
3753 // (C++ 13.3.2p3): for F to be a viable function, there shall
3754 // exist for each argument an implicit conversion sequence
3755 // (13.3.3.1) that converts that argument to the corresponding
3756 // parameter of F.
3757 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003758 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003759 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003760 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003761 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003762 if (Candidate.Conversions[ArgIdx].isBad()) {
3763 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003764 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003765 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003766 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003767 } else {
3768 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3769 // argument for which there is no corresponding parameter is
3770 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003771 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003772 }
3773 }
3774}
3775
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003776/// \brief Add all of the function declarations in the given function set to
3777/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003778void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003779 Expr **Args, unsigned NumArgs,
3780 OverloadCandidateSet& CandidateSet,
3781 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003782 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003783 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3784 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003785 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003786 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003787 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00003788 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003789 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003790 CandidateSet, SuppressUserConversions);
3791 else
John McCalla0296f72010-03-19 07:35:19 +00003792 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003793 SuppressUserConversions);
3794 } else {
John McCalla0296f72010-03-19 07:35:19 +00003795 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003796 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3797 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003798 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003799 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003800 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003801 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00003802 Args[0]->Classify(Context),
3803 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003804 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003805 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003806 else
John McCalla0296f72010-03-19 07:35:19 +00003807 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003808 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003809 Args, NumArgs, CandidateSet,
3810 SuppressUserConversions);
3811 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003812 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003813}
3814
John McCallf0f1cf02009-11-17 07:50:12 +00003815/// AddMethodCandidate - Adds a named decl (which is some kind of
3816/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003817void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003818 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00003819 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00003820 Expr **Args, unsigned NumArgs,
3821 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003822 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003823 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003824 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003825
3826 if (isa<UsingShadowDecl>(Decl))
3827 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003828
John McCallf0f1cf02009-11-17 07:50:12 +00003829 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3830 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3831 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003832 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3833 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00003834 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003835 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003836 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003837 } else {
John McCalla0296f72010-03-19 07:35:19 +00003838 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00003839 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003840 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003841 }
3842}
3843
Douglas Gregor436424c2008-11-18 23:14:02 +00003844/// AddMethodCandidate - Adds the given C++ member function to the set
3845/// of candidate functions, using the given function call arguments
3846/// and the object argument (@c Object). For example, in a call
3847/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3848/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3849/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003850/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003851void
John McCalla0296f72010-03-19 07:35:19 +00003852Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003853 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00003854 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00003855 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003856 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003857 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003858 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003859 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003860 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003861 assert(!isa<CXXConstructorDecl>(Method) &&
3862 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003863
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003864 if (!CandidateSet.isNewCandidate(Method))
3865 return;
3866
Douglas Gregor27381f32009-11-23 12:27:39 +00003867 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003868 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003869
Douglas Gregor436424c2008-11-18 23:14:02 +00003870 // Add this candidate
3871 CandidateSet.push_back(OverloadCandidate());
3872 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003873 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003874 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003875 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003876 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003877 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00003878
3879 unsigned NumArgsInProto = Proto->getNumArgs();
3880
3881 // (C++ 13.3.2p2): A candidate function having fewer than m
3882 // parameters is viable only if it has an ellipsis in its parameter
3883 // list (8.3.5).
3884 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3885 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003886 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003887 return;
3888 }
3889
3890 // (C++ 13.3.2p2): A candidate function having more than m parameters
3891 // is viable only if the (m+1)st parameter has a default argument
3892 // (8.3.6). For the purposes of overload resolution, the
3893 // parameter list is truncated on the right, so that there are
3894 // exactly m parameters.
3895 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3896 if (NumArgs < MinRequiredArgs) {
3897 // Not enough arguments.
3898 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003899 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003900 return;
3901 }
3902
3903 Candidate.Viable = true;
3904 Candidate.Conversions.resize(NumArgs + 1);
3905
John McCall6e9f8f62009-12-03 04:06:58 +00003906 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003907 // The implicit object argument is ignored.
3908 Candidate.IgnoreObjectArgument = true;
3909 else {
3910 // Determine the implicit conversion sequence for the object
3911 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003912 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00003913 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
3914 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003915 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003916 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003917 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003918 return;
3919 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003920 }
3921
3922 // Determine the implicit conversion sequences for each of the
3923 // arguments.
3924 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3925 if (ArgIdx < NumArgsInProto) {
3926 // (C++ 13.3.2p3): for F to be a viable function, there shall
3927 // exist for each argument an implicit conversion sequence
3928 // (13.3.3.1) that converts that argument to the corresponding
3929 // parameter of F.
3930 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003931 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003932 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003933 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003934 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003935 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003936 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003937 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003938 break;
3939 }
3940 } else {
3941 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3942 // argument for which there is no corresponding parameter is
3943 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003944 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003945 }
3946 }
3947}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003948
Douglas Gregor97628d62009-08-21 00:16:32 +00003949/// \brief Add a C++ member function template as a candidate to the candidate
3950/// set, using template argument deduction to produce an appropriate member
3951/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003952void
Douglas Gregor97628d62009-08-21 00:16:32 +00003953Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003954 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003955 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003956 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003957 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00003958 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00003959 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003960 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003961 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003962 if (!CandidateSet.isNewCandidate(MethodTmpl))
3963 return;
3964
Douglas Gregor97628d62009-08-21 00:16:32 +00003965 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003966 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003967 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003968 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003969 // candidate functions in the usual way.113) A given name can refer to one
3970 // or more function templates and also to a set of overloaded non-template
3971 // functions. In such a case, the candidate functions generated from each
3972 // function template are combined with the set of non-template candidate
3973 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003974 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003975 FunctionDecl *Specialization = 0;
3976 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003977 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003978 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003979 CandidateSet.push_back(OverloadCandidate());
3980 OverloadCandidate &Candidate = CandidateSet.back();
3981 Candidate.FoundDecl = FoundDecl;
3982 Candidate.Function = MethodTmpl->getTemplatedDecl();
3983 Candidate.Viable = false;
3984 Candidate.FailureKind = ovl_fail_bad_deduction;
3985 Candidate.IsSurrogate = false;
3986 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003987 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003988 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003989 Info);
3990 return;
3991 }
Mike Stump11289f42009-09-09 15:08:12 +00003992
Douglas Gregor97628d62009-08-21 00:16:32 +00003993 // Add the function template specialization produced by template argument
3994 // deduction as a candidate.
3995 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003996 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003997 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003998 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00003999 ActingContext, ObjectType, ObjectClassification,
4000 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004001}
4002
Douglas Gregor05155d82009-08-21 23:19:43 +00004003/// \brief Add a C++ function template specialization as a candidate
4004/// in the candidate set, using template argument deduction to produce
4005/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004006void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004007Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004008 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00004009 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004010 Expr **Args, unsigned NumArgs,
4011 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004012 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004013 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4014 return;
4015
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004016 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004017 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004018 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004019 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004020 // candidate functions in the usual way.113) A given name can refer to one
4021 // or more function templates and also to a set of overloaded non-template
4022 // functions. In such a case, the candidate functions generated from each
4023 // function template are combined with the set of non-template candidate
4024 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004025 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004026 FunctionDecl *Specialization = 0;
4027 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004028 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004029 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004030 CandidateSet.push_back(OverloadCandidate());
4031 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004032 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004033 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4034 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004035 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004036 Candidate.IsSurrogate = false;
4037 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004038 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004040 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004041 return;
4042 }
Mike Stump11289f42009-09-09 15:08:12 +00004043
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004044 // Add the function template specialization produced by template argument
4045 // deduction as a candidate.
4046 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004047 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004048 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004049}
Mike Stump11289f42009-09-09 15:08:12 +00004050
Douglas Gregora1f013e2008-11-07 22:36:19 +00004051/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004052/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004053/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004054/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004055/// (which may or may not be the same type as the type that the
4056/// conversion function produces).
4057void
4058Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004059 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004060 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004061 Expr *From, QualType ToType,
4062 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004063 assert(!Conversion->getDescribedFunctionTemplate() &&
4064 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004065 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004066 if (!CandidateSet.isNewCandidate(Conversion))
4067 return;
4068
Douglas Gregor27381f32009-11-23 12:27:39 +00004069 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004070 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004071
Douglas Gregora1f013e2008-11-07 22:36:19 +00004072 // Add this candidate
4073 CandidateSet.push_back(OverloadCandidate());
4074 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004075 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004076 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004077 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004078 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004079 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004080 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004081 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004082 Candidate.Viable = true;
4083 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004084 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004085
Douglas Gregor6affc782010-08-19 15:37:02 +00004086 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004087 // For conversion functions, the function is considered to be a member of
4088 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004089 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004090 //
4091 // Determine the implicit conversion sequence for the implicit
4092 // object parameter.
4093 QualType ImplicitParamType = From->getType();
4094 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4095 ImplicitParamType = FromPtrType->getPointeeType();
4096 CXXRecordDecl *ConversionContext
4097 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004098
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004099 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004100 = TryObjectArgumentInitialization(*this, From->getType(),
4101 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004102 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004103
John McCall0d1da222010-01-12 00:44:57 +00004104 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004105 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004106 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004107 return;
4108 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004109
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004110 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004111 // derived to base as such conversions are given Conversion Rank. They only
4112 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4113 QualType FromCanon
4114 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4115 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4116 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4117 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004118 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004119 return;
4120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004121
Douglas Gregora1f013e2008-11-07 22:36:19 +00004122 // To determine what the conversion from the result of calling the
4123 // conversion function to the type we're eventually trying to
4124 // convert to (ToType), we need to synthesize a call to the
4125 // conversion function and attempt copy initialization from it. This
4126 // makes sure that we get the right semantics with respect to
4127 // lvalues/rvalues and the type. Fortunately, we can allocate this
4128 // call on the stack and we don't need its arguments to be
4129 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004130 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004131 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004132 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4133 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004134 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004135 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004136
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004137 QualType CallResultType
4138 = Conversion->getConversionType().getNonLValueExprType(Context);
4139 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4140 Candidate.Viable = false;
4141 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4142 return;
4143 }
4144
John McCall7decc9e2010-11-18 06:31:45 +00004145 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4146
Mike Stump11289f42009-09-09 15:08:12 +00004147 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004148 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4149 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00004150 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004151 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004152 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004153 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004154 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00004155 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004156
John McCall0d1da222010-01-12 00:44:57 +00004157 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004158 case ImplicitConversionSequence::StandardConversion:
4159 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004160
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004161 // C++ [over.ics.user]p3:
4162 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004163 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004164 // shall have exact match rank.
4165 if (Conversion->getPrimaryTemplate() &&
4166 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4167 Candidate.Viable = false;
4168 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4169 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004170
Douglas Gregorcba72b12011-01-21 05:18:22 +00004171 // C++0x [dcl.init.ref]p5:
4172 // In the second case, if the reference is an rvalue reference and
4173 // the second standard conversion sequence of the user-defined
4174 // conversion sequence includes an lvalue-to-rvalue conversion, the
4175 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004176 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004177 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4178 Candidate.Viable = false;
4179 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4180 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004181 break;
4182
4183 case ImplicitConversionSequence::BadConversion:
4184 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004185 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004186 break;
4187
4188 default:
Mike Stump11289f42009-09-09 15:08:12 +00004189 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004190 "Can only end up with a standard conversion sequence or failure");
4191 }
4192}
4193
Douglas Gregor05155d82009-08-21 23:19:43 +00004194/// \brief Adds a conversion function template specialization
4195/// candidate to the overload set, using template argument deduction
4196/// to deduce the template arguments of the conversion function
4197/// template from the type that we are converting to (C++
4198/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004199void
Douglas Gregor05155d82009-08-21 23:19:43 +00004200Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004201 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004202 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004203 Expr *From, QualType ToType,
4204 OverloadCandidateSet &CandidateSet) {
4205 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4206 "Only conversion function templates permitted here");
4207
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004208 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4209 return;
4210
John McCallbc077cf2010-02-08 23:07:23 +00004211 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004212 CXXConversionDecl *Specialization = 0;
4213 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004214 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004215 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004216 CandidateSet.push_back(OverloadCandidate());
4217 OverloadCandidate &Candidate = CandidateSet.back();
4218 Candidate.FoundDecl = FoundDecl;
4219 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4220 Candidate.Viable = false;
4221 Candidate.FailureKind = ovl_fail_bad_deduction;
4222 Candidate.IsSurrogate = false;
4223 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004224 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004225 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004226 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004227 return;
4228 }
Mike Stump11289f42009-09-09 15:08:12 +00004229
Douglas Gregor05155d82009-08-21 23:19:43 +00004230 // Add the conversion function template specialization produced by
4231 // template argument deduction as a candidate.
4232 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004233 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004234 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004235}
4236
Douglas Gregorab7897a2008-11-19 22:57:39 +00004237/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4238/// converts the given @c Object to a function pointer via the
4239/// conversion function @c Conversion, and then attempts to call it
4240/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4241/// the type of function that we'll eventually be calling.
4242void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004243 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004244 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004245 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004246 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004247 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004248 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004249 if (!CandidateSet.isNewCandidate(Conversion))
4250 return;
4251
Douglas Gregor27381f32009-11-23 12:27:39 +00004252 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004253 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004254
Douglas Gregorab7897a2008-11-19 22:57:39 +00004255 CandidateSet.push_back(OverloadCandidate());
4256 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004257 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004258 Candidate.Function = 0;
4259 Candidate.Surrogate = Conversion;
4260 Candidate.Viable = true;
4261 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004262 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004263 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004264 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004265
4266 // Determine the implicit conversion sequence for the implicit
4267 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004268 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004269 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004270 Object->Classify(Context),
4271 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004272 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004273 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004274 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004275 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004276 return;
4277 }
4278
4279 // The first conversion is actually a user-defined conversion whose
4280 // first conversion is ObjectInit's standard conversion (which is
4281 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004282 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004283 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004284 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004285 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004286 Candidate.Conversions[0].UserDefined.FoundConversionFunction
Douglas Gregor2bbfba02011-01-20 01:32:05 +00004287 = FoundDecl.getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004288 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004289 = Candidate.Conversions[0].UserDefined.Before;
4290 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4291
Mike Stump11289f42009-09-09 15:08:12 +00004292 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004293 unsigned NumArgsInProto = Proto->getNumArgs();
4294
4295 // (C++ 13.3.2p2): A candidate function having fewer than m
4296 // parameters is viable only if it has an ellipsis in its parameter
4297 // list (8.3.5).
4298 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4299 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004300 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004301 return;
4302 }
4303
4304 // Function types don't have any default arguments, so just check if
4305 // we have enough arguments.
4306 if (NumArgs < NumArgsInProto) {
4307 // Not enough arguments.
4308 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004309 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004310 return;
4311 }
4312
4313 // Determine the implicit conversion sequences for each of the
4314 // arguments.
4315 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4316 if (ArgIdx < NumArgsInProto) {
4317 // (C++ 13.3.2p3): for F to be a viable function, there shall
4318 // exist for each argument an implicit conversion sequence
4319 // (13.3.3.1) that converts that argument to the corresponding
4320 // parameter of F.
4321 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004322 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004323 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004324 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004325 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004326 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004327 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004328 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004329 break;
4330 }
4331 } else {
4332 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4333 // argument for which there is no corresponding parameter is
4334 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004335 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004336 }
4337 }
4338}
4339
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004340/// \brief Add overload candidates for overloaded operators that are
4341/// member functions.
4342///
4343/// Add the overloaded operator candidates that are member functions
4344/// for the operator Op that was used in an operator expression such
4345/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4346/// CandidateSet will store the added overload candidates. (C++
4347/// [over.match.oper]).
4348void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4349 SourceLocation OpLoc,
4350 Expr **Args, unsigned NumArgs,
4351 OverloadCandidateSet& CandidateSet,
4352 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004353 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4354
4355 // C++ [over.match.oper]p3:
4356 // For a unary operator @ with an operand of a type whose
4357 // cv-unqualified version is T1, and for a binary operator @ with
4358 // a left operand of a type whose cv-unqualified version is T1 and
4359 // a right operand of a type whose cv-unqualified version is T2,
4360 // three sets of candidate functions, designated member
4361 // candidates, non-member candidates and built-in candidates, are
4362 // constructed as follows:
4363 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004364
4365 // -- If T1 is a class type, the set of member candidates is the
4366 // result of the qualified lookup of T1::operator@
4367 // (13.3.1.1.1); otherwise, the set of member candidates is
4368 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004369 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004370 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004371 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004372 return;
Mike Stump11289f42009-09-09 15:08:12 +00004373
John McCall27b18f82009-11-17 02:14:36 +00004374 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4375 LookupQualifiedName(Operators, T1Rec->getDecl());
4376 Operators.suppressDiagnostics();
4377
Mike Stump11289f42009-09-09 15:08:12 +00004378 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004379 OperEnd = Operators.end();
4380 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004381 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004382 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004383 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00004384 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004385 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004386 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004387}
4388
Douglas Gregora11693b2008-11-12 17:17:38 +00004389/// AddBuiltinCandidate - Add a candidate for a built-in
4390/// operator. ResultTy and ParamTys are the result and parameter types
4391/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004392/// arguments being passed to the candidate. IsAssignmentOperator
4393/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004394/// operator. NumContextualBoolArguments is the number of arguments
4395/// (at the beginning of the argument list) that will be contextually
4396/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004397void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004398 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004399 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004400 bool IsAssignmentOperator,
4401 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004402 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004403 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004404
Douglas Gregora11693b2008-11-12 17:17:38 +00004405 // Add this candidate
4406 CandidateSet.push_back(OverloadCandidate());
4407 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004408 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004409 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004410 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004411 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004412 Candidate.BuiltinTypes.ResultTy = ResultTy;
4413 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4414 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4415
4416 // Determine the implicit conversion sequences for each of the
4417 // arguments.
4418 Candidate.Viable = true;
4419 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004420 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004421 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004422 // C++ [over.match.oper]p4:
4423 // For the built-in assignment operators, conversions of the
4424 // left operand are restricted as follows:
4425 // -- no temporaries are introduced to hold the left operand, and
4426 // -- no user-defined conversions are applied to the left
4427 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004428 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004429 //
4430 // We block these conversions by turning off user-defined
4431 // conversions, since that is the only way that initialization of
4432 // a reference to a non-class type can occur from something that
4433 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004434 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004435 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004436 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004437 Candidate.Conversions[ArgIdx]
4438 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004439 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004440 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004441 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004442 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004443 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004444 }
John McCall0d1da222010-01-12 00:44:57 +00004445 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004446 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004447 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004448 break;
4449 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004450 }
4451}
4452
4453/// BuiltinCandidateTypeSet - A set of types that will be used for the
4454/// candidate operator functions for built-in operators (C++
4455/// [over.built]). The types are separated into pointer types and
4456/// enumeration types.
4457class BuiltinCandidateTypeSet {
4458 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004459 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004460
4461 /// PointerTypes - The set of pointer types that will be used in the
4462 /// built-in candidates.
4463 TypeSet PointerTypes;
4464
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004465 /// MemberPointerTypes - The set of member pointer types that will be
4466 /// used in the built-in candidates.
4467 TypeSet MemberPointerTypes;
4468
Douglas Gregora11693b2008-11-12 17:17:38 +00004469 /// EnumerationTypes - The set of enumeration types that will be
4470 /// used in the built-in candidates.
4471 TypeSet EnumerationTypes;
4472
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004473 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004474 /// candidates.
4475 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004476
4477 /// \brief A flag indicating non-record types are viable candidates
4478 bool HasNonRecordTypes;
4479
4480 /// \brief A flag indicating whether either arithmetic or enumeration types
4481 /// were present in the candidate set.
4482 bool HasArithmeticOrEnumeralTypes;
4483
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004484 /// Sema - The semantic analysis instance where we are building the
4485 /// candidate type set.
4486 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004487
Douglas Gregora11693b2008-11-12 17:17:38 +00004488 /// Context - The AST context in which we will build the type sets.
4489 ASTContext &Context;
4490
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004491 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4492 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004493 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004494
4495public:
4496 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004497 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004498
Mike Stump11289f42009-09-09 15:08:12 +00004499 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004500 : HasNonRecordTypes(false),
4501 HasArithmeticOrEnumeralTypes(false),
4502 SemaRef(SemaRef),
4503 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004504
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004505 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004506 SourceLocation Loc,
4507 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004508 bool AllowExplicitConversions,
4509 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004510
4511 /// pointer_begin - First pointer type found;
4512 iterator pointer_begin() { return PointerTypes.begin(); }
4513
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004514 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004515 iterator pointer_end() { return PointerTypes.end(); }
4516
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004517 /// member_pointer_begin - First member pointer type found;
4518 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4519
4520 /// member_pointer_end - Past the last member pointer type found;
4521 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4522
Douglas Gregora11693b2008-11-12 17:17:38 +00004523 /// enumeration_begin - First enumeration type found;
4524 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4525
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004526 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004527 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004528
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004529 iterator vector_begin() { return VectorTypes.begin(); }
4530 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00004531
4532 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4533 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregora11693b2008-11-12 17:17:38 +00004534};
4535
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004536/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004537/// the set of pointer types along with any more-qualified variants of
4538/// that type. For example, if @p Ty is "int const *", this routine
4539/// will add "int const *", "int const volatile *", "int const
4540/// restrict *", and "int const volatile restrict *" to the set of
4541/// pointer types. Returns true if the add of @p Ty itself succeeded,
4542/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004543///
4544/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004545bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004546BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4547 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004548
Douglas Gregora11693b2008-11-12 17:17:38 +00004549 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004550 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004551 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004552
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004553 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004554 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004555 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004556 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004557 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004558 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004559 buildObjCPtr = true;
4560 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004561 else
4562 assert(false && "type was not a pointer type!");
4563 }
4564 else
4565 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004566
Sebastian Redl4990a632009-11-18 20:39:26 +00004567 // Don't add qualified variants of arrays. For one, they're not allowed
4568 // (the qualifier would sink to the element type), and for another, the
4569 // only overload situation where it matters is subscript or pointer +- int,
4570 // and those shouldn't have qualifier variants anyway.
4571 if (PointeeTy->isArrayType())
4572 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004573 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004574 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004575 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004576 bool hasVolatile = VisibleQuals.hasVolatile();
4577 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578
John McCall8ccfcb52009-09-24 19:53:00 +00004579 // Iterate through all strict supersets of BaseCVR.
4580 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4581 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004582 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4583 // in the types.
4584 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4585 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004586 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004587 if (!buildObjCPtr)
4588 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4589 else
4590 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004591 }
4592
4593 return true;
4594}
4595
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004596/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4597/// to the set of pointer types along with any more-qualified variants of
4598/// that type. For example, if @p Ty is "int const *", this routine
4599/// will add "int const *", "int const volatile *", "int const
4600/// restrict *", and "int const volatile restrict *" to the set of
4601/// pointer types. Returns true if the add of @p Ty itself succeeded,
4602/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004603///
4604/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004605bool
4606BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4607 QualType Ty) {
4608 // Insert this type.
4609 if (!MemberPointerTypes.insert(Ty))
4610 return false;
4611
John McCall8ccfcb52009-09-24 19:53:00 +00004612 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4613 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004614
John McCall8ccfcb52009-09-24 19:53:00 +00004615 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004616 // Don't add qualified variants of arrays. For one, they're not allowed
4617 // (the qualifier would sink to the element type), and for another, the
4618 // only overload situation where it matters is subscript or pointer +- int,
4619 // and those shouldn't have qualifier variants anyway.
4620 if (PointeeTy->isArrayType())
4621 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004622 const Type *ClassTy = PointerTy->getClass();
4623
4624 // Iterate through all strict supersets of the pointee type's CVR
4625 // qualifiers.
4626 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4627 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4628 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004629
John McCall8ccfcb52009-09-24 19:53:00 +00004630 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00004631 MemberPointerTypes.insert(
4632 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004633 }
4634
4635 return true;
4636}
4637
Douglas Gregora11693b2008-11-12 17:17:38 +00004638/// AddTypesConvertedFrom - Add each of the types to which the type @p
4639/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004640/// primarily interested in pointer types and enumeration types. We also
4641/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004642/// AllowUserConversions is true if we should look at the conversion
4643/// functions of a class type, and AllowExplicitConversions if we
4644/// should also include the explicit conversion functions of a class
4645/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004646void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004647BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004648 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004649 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004650 bool AllowExplicitConversions,
4651 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004652 // Only deal with canonical types.
4653 Ty = Context.getCanonicalType(Ty);
4654
4655 // Look through reference types; they aren't part of the type of an
4656 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004657 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004658 Ty = RefTy->getPointeeType();
4659
John McCall33ddac02011-01-19 10:06:00 +00004660 // If we're dealing with an array type, decay to the pointer.
4661 if (Ty->isArrayType())
4662 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4663
4664 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004665 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004666
Chandler Carruth00a38332010-12-13 01:44:01 +00004667 // Flag if we ever add a non-record type.
4668 const RecordType *TyRec = Ty->getAs<RecordType>();
4669 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4670
Chandler Carruth00a38332010-12-13 01:44:01 +00004671 // Flag if we encounter an arithmetic type.
4672 HasArithmeticOrEnumeralTypes =
4673 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4674
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004675 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4676 PointerTypes.insert(Ty);
4677 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004678 // Insert our type, and its more-qualified variants, into the set
4679 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004680 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004681 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004682 } else if (Ty->isMemberPointerType()) {
4683 // Member pointers are far easier, since the pointee can't be converted.
4684 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4685 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004686 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004687 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00004688 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004689 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004690 // We treat vector types as arithmetic types in many contexts as an
4691 // extension.
4692 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004693 VectorTypes.insert(Ty);
Chandler Carruth00a38332010-12-13 01:44:01 +00004694 } else if (AllowUserConversions && TyRec) {
4695 // No conversion functions in incomplete types.
4696 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4697 return;
Mike Stump11289f42009-09-09 15:08:12 +00004698
Chandler Carruth00a38332010-12-13 01:44:01 +00004699 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4700 const UnresolvedSetImpl *Conversions
4701 = ClassDecl->getVisibleConversionFunctions();
4702 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4703 E = Conversions->end(); I != E; ++I) {
4704 NamedDecl *D = I.getDecl();
4705 if (isa<UsingShadowDecl>(D))
4706 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004707
Chandler Carruth00a38332010-12-13 01:44:01 +00004708 // Skip conversion function templates; they don't tell us anything
4709 // about which builtin types we can convert to.
4710 if (isa<FunctionTemplateDecl>(D))
4711 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00004712
Chandler Carruth00a38332010-12-13 01:44:01 +00004713 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4714 if (AllowExplicitConversions || !Conv->isExplicit()) {
4715 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4716 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004717 }
4718 }
4719 }
4720}
4721
Douglas Gregor84605ae2009-08-24 13:43:27 +00004722/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4723/// the volatile- and non-volatile-qualified assignment operators for the
4724/// given type to the candidate set.
4725static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4726 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004727 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004728 unsigned NumArgs,
4729 OverloadCandidateSet &CandidateSet) {
4730 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004731
Douglas Gregor84605ae2009-08-24 13:43:27 +00004732 // T& operator=(T&, T)
4733 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4734 ParamTypes[1] = T;
4735 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4736 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004737
Douglas Gregor84605ae2009-08-24 13:43:27 +00004738 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4739 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004740 ParamTypes[0]
4741 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004742 ParamTypes[1] = T;
4743 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004744 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004745 }
4746}
Mike Stump11289f42009-09-09 15:08:12 +00004747
Sebastian Redl1054fae2009-10-25 17:03:50 +00004748/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4749/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004750static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4751 Qualifiers VRQuals;
4752 const RecordType *TyRec;
4753 if (const MemberPointerType *RHSMPType =
4754 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004755 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004756 else
4757 TyRec = ArgExpr->getType()->getAs<RecordType>();
4758 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004759 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004760 VRQuals.addVolatile();
4761 VRQuals.addRestrict();
4762 return VRQuals;
4763 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004764
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004765 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004766 if (!ClassDecl->hasDefinition())
4767 return VRQuals;
4768
John McCallad371252010-01-20 00:46:10 +00004769 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004770 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004771
John McCallad371252010-01-20 00:46:10 +00004772 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004773 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004774 NamedDecl *D = I.getDecl();
4775 if (isa<UsingShadowDecl>(D))
4776 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4777 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004778 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4779 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4780 CanTy = ResTypeRef->getPointeeType();
4781 // Need to go down the pointer/mempointer chain and add qualifiers
4782 // as see them.
4783 bool done = false;
4784 while (!done) {
4785 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4786 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004787 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004788 CanTy->getAs<MemberPointerType>())
4789 CanTy = ResTypeMPtr->getPointeeType();
4790 else
4791 done = true;
4792 if (CanTy.isVolatileQualified())
4793 VRQuals.addVolatile();
4794 if (CanTy.isRestrictQualified())
4795 VRQuals.addRestrict();
4796 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4797 return VRQuals;
4798 }
4799 }
4800 }
4801 return VRQuals;
4802}
John McCall52872982010-11-13 05:51:15 +00004803
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004804namespace {
John McCall52872982010-11-13 05:51:15 +00004805
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004806/// \brief Helper class to manage the addition of builtin operator overload
4807/// candidates. It provides shared state and utility methods used throughout
4808/// the process, as well as a helper method to add each group of builtin
4809/// operator overloads from the standard to a candidate set.
4810class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004811 // Common instance state available to all overload candidate addition methods.
4812 Sema &S;
4813 Expr **Args;
4814 unsigned NumArgs;
4815 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00004816 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruthc6586e52010-12-12 10:35:00 +00004817 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4818 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004819
Chandler Carruthc6586e52010-12-12 10:35:00 +00004820 // Define some constants used to index and iterate over the arithemetic types
4821 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00004822 // The "promoted arithmetic types" are the arithmetic
4823 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00004824 static const unsigned FirstIntegralType = 3;
4825 static const unsigned LastIntegralType = 18;
4826 static const unsigned FirstPromotedIntegralType = 3,
4827 LastPromotedIntegralType = 9;
4828 static const unsigned FirstPromotedArithmeticType = 0,
4829 LastPromotedArithmeticType = 9;
4830 static const unsigned NumArithmeticTypes = 18;
4831
Chandler Carruthc6586e52010-12-12 10:35:00 +00004832 /// \brief Get the canonical type for a given arithmetic type index.
4833 CanQualType getArithmeticType(unsigned index) {
4834 assert(index < NumArithmeticTypes);
4835 static CanQualType ASTContext::* const
4836 ArithmeticTypes[NumArithmeticTypes] = {
4837 // Start of promoted types.
4838 &ASTContext::FloatTy,
4839 &ASTContext::DoubleTy,
4840 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00004841
Chandler Carruthc6586e52010-12-12 10:35:00 +00004842 // Start of integral types.
4843 &ASTContext::IntTy,
4844 &ASTContext::LongTy,
4845 &ASTContext::LongLongTy,
4846 &ASTContext::UnsignedIntTy,
4847 &ASTContext::UnsignedLongTy,
4848 &ASTContext::UnsignedLongLongTy,
4849 // End of promoted types.
4850
4851 &ASTContext::BoolTy,
4852 &ASTContext::CharTy,
4853 &ASTContext::WCharTy,
4854 &ASTContext::Char16Ty,
4855 &ASTContext::Char32Ty,
4856 &ASTContext::SignedCharTy,
4857 &ASTContext::ShortTy,
4858 &ASTContext::UnsignedCharTy,
4859 &ASTContext::UnsignedShortTy,
4860 // End of integral types.
4861 // FIXME: What about complex?
4862 };
4863 return S.Context.*ArithmeticTypes[index];
4864 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004865
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004866 /// \brief Gets the canonical type resulting from the usual arithemetic
4867 /// converions for the given arithmetic types.
4868 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
4869 // Accelerator table for performing the usual arithmetic conversions.
4870 // The rules are basically:
4871 // - if either is floating-point, use the wider floating-point
4872 // - if same signedness, use the higher rank
4873 // - if same size, use unsigned of the higher rank
4874 // - use the larger type
4875 // These rules, together with the axiom that higher ranks are
4876 // never smaller, are sufficient to precompute all of these results
4877 // *except* when dealing with signed types of higher rank.
4878 // (we could precompute SLL x UI for all known platforms, but it's
4879 // better not to make any assumptions).
4880 enum PromotedType {
4881 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
4882 };
4883 static PromotedType ConversionsTable[LastPromotedArithmeticType]
4884 [LastPromotedArithmeticType] = {
4885 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4886 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4887 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4888 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4889 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4890 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4891 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4892 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4893 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
4894 };
4895
4896 assert(L < LastPromotedArithmeticType);
4897 assert(R < LastPromotedArithmeticType);
4898 int Idx = ConversionsTable[L][R];
4899
4900 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004901 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004902
4903 // Slow path: we need to compare widths.
4904 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004905 CanQualType LT = getArithmeticType(L),
4906 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004907 unsigned LW = S.Context.getIntWidth(LT),
4908 RW = S.Context.getIntWidth(RT);
4909
4910 // If they're different widths, use the signed type.
4911 if (LW > RW) return LT;
4912 else if (LW < RW) return RT;
4913
4914 // Otherwise, use the unsigned type of the signed type's rank.
4915 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
4916 assert(L == SLL || R == SLL);
4917 return S.Context.UnsignedLongLongTy;
4918 }
4919
Chandler Carruth5659c0c2010-12-12 09:22:45 +00004920 /// \brief Helper method to factor out the common pattern of adding overloads
4921 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004922 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
4923 bool HasVolatile) {
4924 QualType ParamTypes[2] = {
4925 S.Context.getLValueReferenceType(CandidateTy),
4926 S.Context.IntTy
4927 };
4928
4929 // Non-volatile version.
4930 if (NumArgs == 1)
4931 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4932 else
4933 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4934
4935 // Use a heuristic to reduce number of builtin candidates in the set:
4936 // add volatile version only if there are conversions to a volatile type.
4937 if (HasVolatile) {
4938 ParamTypes[0] =
4939 S.Context.getLValueReferenceType(
4940 S.Context.getVolatileType(CandidateTy));
4941 if (NumArgs == 1)
4942 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4943 else
4944 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4945 }
4946 }
4947
4948public:
4949 BuiltinOperatorOverloadBuilder(
4950 Sema &S, Expr **Args, unsigned NumArgs,
4951 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00004952 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004953 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
4954 OverloadCandidateSet &CandidateSet)
4955 : S(S), Args(Args), NumArgs(NumArgs),
4956 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00004957 HasArithmeticOrEnumeralCandidateType(
4958 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004959 CandidateTypes(CandidateTypes),
4960 CandidateSet(CandidateSet) {
4961 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004962 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004963 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004964 assert(getArithmeticType(LastPromotedIntegralType - 1)
4965 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004966 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004967 assert(getArithmeticType(FirstPromotedArithmeticType)
4968 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004969 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004970 assert(getArithmeticType(LastPromotedArithmeticType - 1)
4971 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004972 "Invalid last promoted arithmetic type");
4973 }
4974
4975 // C++ [over.built]p3:
4976 //
4977 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4978 // is either volatile or empty, there exist candidate operator
4979 // functions of the form
4980 //
4981 // VQ T& operator++(VQ T&);
4982 // T operator++(VQ T&, int);
4983 //
4984 // C++ [over.built]p4:
4985 //
4986 // For every pair (T, VQ), where T is an arithmetic type other
4987 // than bool, and VQ is either volatile or empty, there exist
4988 // candidate operator functions of the form
4989 //
4990 // VQ T& operator--(VQ T&);
4991 // T operator--(VQ T&, int);
4992 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004993 if (!HasArithmeticOrEnumeralCandidateType)
4994 return;
4995
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004996 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
4997 Arith < NumArithmeticTypes; ++Arith) {
4998 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00004999 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005000 VisibleTypeConversionsQuals.hasVolatile());
5001 }
5002 }
5003
5004 // C++ [over.built]p5:
5005 //
5006 // For every pair (T, VQ), where T is a cv-qualified or
5007 // cv-unqualified object type, and VQ is either volatile or
5008 // empty, there exist candidate operator functions of the form
5009 //
5010 // T*VQ& operator++(T*VQ&);
5011 // T*VQ& operator--(T*VQ&);
5012 // T* operator++(T*VQ&, int);
5013 // T* operator--(T*VQ&, int);
5014 void addPlusPlusMinusMinusPointerOverloads() {
5015 for (BuiltinCandidateTypeSet::iterator
5016 Ptr = CandidateTypes[0].pointer_begin(),
5017 PtrEnd = CandidateTypes[0].pointer_end();
5018 Ptr != PtrEnd; ++Ptr) {
5019 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005020 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005021 continue;
5022
5023 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5024 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5025 VisibleTypeConversionsQuals.hasVolatile()));
5026 }
5027 }
5028
5029 // C++ [over.built]p6:
5030 // For every cv-qualified or cv-unqualified object type T, there
5031 // exist candidate operator functions of the form
5032 //
5033 // T& operator*(T*);
5034 //
5035 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005036 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005037 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005038 // T& operator*(T*);
5039 void addUnaryStarPointerOverloads() {
5040 for (BuiltinCandidateTypeSet::iterator
5041 Ptr = CandidateTypes[0].pointer_begin(),
5042 PtrEnd = CandidateTypes[0].pointer_end();
5043 Ptr != PtrEnd; ++Ptr) {
5044 QualType ParamTy = *Ptr;
5045 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005046 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5047 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005048
Douglas Gregor02824322011-01-26 19:30:28 +00005049 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5050 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5051 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005052
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005053 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5054 &ParamTy, Args, 1, CandidateSet);
5055 }
5056 }
5057
5058 // C++ [over.built]p9:
5059 // For every promoted arithmetic type T, there exist candidate
5060 // operator functions of the form
5061 //
5062 // T operator+(T);
5063 // T operator-(T);
5064 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005065 if (!HasArithmeticOrEnumeralCandidateType)
5066 return;
5067
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005068 for (unsigned Arith = FirstPromotedArithmeticType;
5069 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005070 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005071 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5072 }
5073
5074 // Extension: We also add these operators for vector types.
5075 for (BuiltinCandidateTypeSet::iterator
5076 Vec = CandidateTypes[0].vector_begin(),
5077 VecEnd = CandidateTypes[0].vector_end();
5078 Vec != VecEnd; ++Vec) {
5079 QualType VecTy = *Vec;
5080 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5081 }
5082 }
5083
5084 // C++ [over.built]p8:
5085 // For every type T, there exist candidate operator functions of
5086 // the form
5087 //
5088 // T* operator+(T*);
5089 void addUnaryPlusPointerOverloads() {
5090 for (BuiltinCandidateTypeSet::iterator
5091 Ptr = CandidateTypes[0].pointer_begin(),
5092 PtrEnd = CandidateTypes[0].pointer_end();
5093 Ptr != PtrEnd; ++Ptr) {
5094 QualType ParamTy = *Ptr;
5095 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5096 }
5097 }
5098
5099 // C++ [over.built]p10:
5100 // For every promoted integral type T, there exist candidate
5101 // operator functions of the form
5102 //
5103 // T operator~(T);
5104 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005105 if (!HasArithmeticOrEnumeralCandidateType)
5106 return;
5107
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005108 for (unsigned Int = FirstPromotedIntegralType;
5109 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005110 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005111 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5112 }
5113
5114 // Extension: We also add this operator for vector types.
5115 for (BuiltinCandidateTypeSet::iterator
5116 Vec = CandidateTypes[0].vector_begin(),
5117 VecEnd = CandidateTypes[0].vector_end();
5118 Vec != VecEnd; ++Vec) {
5119 QualType VecTy = *Vec;
5120 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5121 }
5122 }
5123
5124 // C++ [over.match.oper]p16:
5125 // For every pointer to member type T, there exist candidate operator
5126 // functions of the form
5127 //
5128 // bool operator==(T,T);
5129 // bool operator!=(T,T);
5130 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5131 /// Set of (canonical) types that we've already handled.
5132 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5133
5134 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5135 for (BuiltinCandidateTypeSet::iterator
5136 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5137 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5138 MemPtr != MemPtrEnd;
5139 ++MemPtr) {
5140 // Don't add the same builtin candidate twice.
5141 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5142 continue;
5143
5144 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5145 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5146 CandidateSet);
5147 }
5148 }
5149 }
5150
5151 // C++ [over.built]p15:
5152 //
5153 // For every pointer or enumeration type T, there exist
5154 // candidate operator functions of the form
5155 //
5156 // bool operator<(T, T);
5157 // bool operator>(T, T);
5158 // bool operator<=(T, T);
5159 // bool operator>=(T, T);
5160 // bool operator==(T, T);
5161 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005162 void addRelationalPointerOrEnumeralOverloads() {
5163 // C++ [over.built]p1:
5164 // If there is a user-written candidate with the same name and parameter
5165 // types as a built-in candidate operator function, the built-in operator
5166 // function is hidden and is not included in the set of candidate
5167 // functions.
5168 //
5169 // The text is actually in a note, but if we don't implement it then we end
5170 // up with ambiguities when the user provides an overloaded operator for
5171 // an enumeration type. Note that only enumeration types have this problem,
5172 // so we track which enumeration types we've seen operators for. Also, the
5173 // only other overloaded operator with enumeration argumenst, operator=,
5174 // cannot be overloaded for enumeration types, so this is the only place
5175 // where we must suppress candidates like this.
5176 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5177 UserDefinedBinaryOperators;
5178
5179 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5180 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5181 CandidateTypes[ArgIdx].enumeration_end()) {
5182 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5183 CEnd = CandidateSet.end();
5184 C != CEnd; ++C) {
5185 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5186 continue;
5187
5188 QualType FirstParamType =
5189 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5190 QualType SecondParamType =
5191 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5192
5193 // Skip if either parameter isn't of enumeral type.
5194 if (!FirstParamType->isEnumeralType() ||
5195 !SecondParamType->isEnumeralType())
5196 continue;
5197
5198 // Add this operator to the set of known user-defined operators.
5199 UserDefinedBinaryOperators.insert(
5200 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5201 S.Context.getCanonicalType(SecondParamType)));
5202 }
5203 }
5204 }
5205
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005206 /// Set of (canonical) types that we've already handled.
5207 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5208
5209 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5210 for (BuiltinCandidateTypeSet::iterator
5211 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5212 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5213 Ptr != PtrEnd; ++Ptr) {
5214 // Don't add the same builtin candidate twice.
5215 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5216 continue;
5217
5218 QualType ParamTypes[2] = { *Ptr, *Ptr };
5219 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5220 CandidateSet);
5221 }
5222 for (BuiltinCandidateTypeSet::iterator
5223 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5224 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5225 Enum != EnumEnd; ++Enum) {
5226 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5227
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005228 // Don't add the same builtin candidate twice, or if a user defined
5229 // candidate exists.
5230 if (!AddedTypes.insert(CanonType) ||
5231 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5232 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005233 continue;
5234
5235 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005236 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5237 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005238 }
5239 }
5240 }
5241
5242 // C++ [over.built]p13:
5243 //
5244 // For every cv-qualified or cv-unqualified object type T
5245 // there exist candidate operator functions of the form
5246 //
5247 // T* operator+(T*, ptrdiff_t);
5248 // T& operator[](T*, ptrdiff_t); [BELOW]
5249 // T* operator-(T*, ptrdiff_t);
5250 // T* operator+(ptrdiff_t, T*);
5251 // T& operator[](ptrdiff_t, T*); [BELOW]
5252 //
5253 // C++ [over.built]p14:
5254 //
5255 // For every T, where T is a pointer to object type, there
5256 // exist candidate operator functions of the form
5257 //
5258 // ptrdiff_t operator-(T, T);
5259 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5260 /// Set of (canonical) types that we've already handled.
5261 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5262
5263 for (int Arg = 0; Arg < 2; ++Arg) {
5264 QualType AsymetricParamTypes[2] = {
5265 S.Context.getPointerDiffType(),
5266 S.Context.getPointerDiffType(),
5267 };
5268 for (BuiltinCandidateTypeSet::iterator
5269 Ptr = CandidateTypes[Arg].pointer_begin(),
5270 PtrEnd = CandidateTypes[Arg].pointer_end();
5271 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005272 QualType PointeeTy = (*Ptr)->getPointeeType();
5273 if (!PointeeTy->isObjectType())
5274 continue;
5275
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005276 AsymetricParamTypes[Arg] = *Ptr;
5277 if (Arg == 0 || Op == OO_Plus) {
5278 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5279 // T* operator+(ptrdiff_t, T*);
5280 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5281 CandidateSet);
5282 }
5283 if (Op == OO_Minus) {
5284 // ptrdiff_t operator-(T, T);
5285 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5286 continue;
5287
5288 QualType ParamTypes[2] = { *Ptr, *Ptr };
5289 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5290 Args, 2, CandidateSet);
5291 }
5292 }
5293 }
5294 }
5295
5296 // C++ [over.built]p12:
5297 //
5298 // For every pair of promoted arithmetic types L and R, there
5299 // exist candidate operator functions of the form
5300 //
5301 // LR operator*(L, R);
5302 // LR operator/(L, R);
5303 // LR operator+(L, R);
5304 // LR operator-(L, R);
5305 // bool operator<(L, R);
5306 // bool operator>(L, R);
5307 // bool operator<=(L, R);
5308 // bool operator>=(L, R);
5309 // bool operator==(L, R);
5310 // bool operator!=(L, R);
5311 //
5312 // where LR is the result of the usual arithmetic conversions
5313 // between types L and R.
5314 //
5315 // C++ [over.built]p24:
5316 //
5317 // For every pair of promoted arithmetic types L and R, there exist
5318 // candidate operator functions of the form
5319 //
5320 // LR operator?(bool, L, R);
5321 //
5322 // where LR is the result of the usual arithmetic conversions
5323 // between types L and R.
5324 // Our candidates ignore the first parameter.
5325 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005326 if (!HasArithmeticOrEnumeralCandidateType)
5327 return;
5328
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005329 for (unsigned Left = FirstPromotedArithmeticType;
5330 Left < LastPromotedArithmeticType; ++Left) {
5331 for (unsigned Right = FirstPromotedArithmeticType;
5332 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005333 QualType LandR[2] = { getArithmeticType(Left),
5334 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005335 QualType Result =
5336 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005337 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005338 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5339 }
5340 }
5341
5342 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5343 // conditional operator for vector types.
5344 for (BuiltinCandidateTypeSet::iterator
5345 Vec1 = CandidateTypes[0].vector_begin(),
5346 Vec1End = CandidateTypes[0].vector_end();
5347 Vec1 != Vec1End; ++Vec1) {
5348 for (BuiltinCandidateTypeSet::iterator
5349 Vec2 = CandidateTypes[1].vector_begin(),
5350 Vec2End = CandidateTypes[1].vector_end();
5351 Vec2 != Vec2End; ++Vec2) {
5352 QualType LandR[2] = { *Vec1, *Vec2 };
5353 QualType Result = S.Context.BoolTy;
5354 if (!isComparison) {
5355 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5356 Result = *Vec1;
5357 else
5358 Result = *Vec2;
5359 }
5360
5361 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5362 }
5363 }
5364 }
5365
5366 // C++ [over.built]p17:
5367 //
5368 // For every pair of promoted integral types L and R, there
5369 // exist candidate operator functions of the form
5370 //
5371 // LR operator%(L, R);
5372 // LR operator&(L, R);
5373 // LR operator^(L, R);
5374 // LR operator|(L, R);
5375 // L operator<<(L, R);
5376 // L operator>>(L, R);
5377 //
5378 // where LR is the result of the usual arithmetic conversions
5379 // between types L and R.
5380 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005381 if (!HasArithmeticOrEnumeralCandidateType)
5382 return;
5383
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005384 for (unsigned Left = FirstPromotedIntegralType;
5385 Left < LastPromotedIntegralType; ++Left) {
5386 for (unsigned Right = FirstPromotedIntegralType;
5387 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005388 QualType LandR[2] = { getArithmeticType(Left),
5389 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005390 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5391 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005392 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005393 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5394 }
5395 }
5396 }
5397
5398 // C++ [over.built]p20:
5399 //
5400 // For every pair (T, VQ), where T is an enumeration or
5401 // pointer to member type and VQ is either volatile or
5402 // empty, there exist candidate operator functions of the form
5403 //
5404 // VQ T& operator=(VQ T&, T);
5405 void addAssignmentMemberPointerOrEnumeralOverloads() {
5406 /// Set of (canonical) types that we've already handled.
5407 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5408
5409 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5410 for (BuiltinCandidateTypeSet::iterator
5411 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5412 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5413 Enum != EnumEnd; ++Enum) {
5414 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5415 continue;
5416
5417 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5418 CandidateSet);
5419 }
5420
5421 for (BuiltinCandidateTypeSet::iterator
5422 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5423 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5424 MemPtr != MemPtrEnd; ++MemPtr) {
5425 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5426 continue;
5427
5428 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5429 CandidateSet);
5430 }
5431 }
5432 }
5433
5434 // C++ [over.built]p19:
5435 //
5436 // For every pair (T, VQ), where T is any type and VQ is either
5437 // volatile or empty, there exist candidate operator functions
5438 // of the form
5439 //
5440 // T*VQ& operator=(T*VQ&, T*);
5441 //
5442 // C++ [over.built]p21:
5443 //
5444 // For every pair (T, VQ), where T is a cv-qualified or
5445 // cv-unqualified object type and VQ is either volatile or
5446 // empty, there exist candidate operator functions of the form
5447 //
5448 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5449 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5450 void addAssignmentPointerOverloads(bool isEqualOp) {
5451 /// Set of (canonical) types that we've already handled.
5452 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5453
5454 for (BuiltinCandidateTypeSet::iterator
5455 Ptr = CandidateTypes[0].pointer_begin(),
5456 PtrEnd = CandidateTypes[0].pointer_end();
5457 Ptr != PtrEnd; ++Ptr) {
5458 // If this is operator=, keep track of the builtin candidates we added.
5459 if (isEqualOp)
5460 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005461 else if (!(*Ptr)->getPointeeType()->isObjectType())
5462 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005463
5464 // non-volatile version
5465 QualType ParamTypes[2] = {
5466 S.Context.getLValueReferenceType(*Ptr),
5467 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5468 };
5469 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5470 /*IsAssigmentOperator=*/ isEqualOp);
5471
5472 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5473 VisibleTypeConversionsQuals.hasVolatile()) {
5474 // volatile version
5475 ParamTypes[0] =
5476 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5477 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5478 /*IsAssigmentOperator=*/isEqualOp);
5479 }
5480 }
5481
5482 if (isEqualOp) {
5483 for (BuiltinCandidateTypeSet::iterator
5484 Ptr = CandidateTypes[1].pointer_begin(),
5485 PtrEnd = CandidateTypes[1].pointer_end();
5486 Ptr != PtrEnd; ++Ptr) {
5487 // Make sure we don't add the same candidate twice.
5488 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5489 continue;
5490
Chandler Carruth8e543b32010-12-12 08:17:55 +00005491 QualType ParamTypes[2] = {
5492 S.Context.getLValueReferenceType(*Ptr),
5493 *Ptr,
5494 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005495
5496 // non-volatile version
5497 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5498 /*IsAssigmentOperator=*/true);
5499
5500 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5501 VisibleTypeConversionsQuals.hasVolatile()) {
5502 // volatile version
5503 ParamTypes[0] =
5504 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00005505 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5506 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005507 }
5508 }
5509 }
5510 }
5511
5512 // C++ [over.built]p18:
5513 //
5514 // For every triple (L, VQ, R), where L is an arithmetic type,
5515 // VQ is either volatile or empty, and R is a promoted
5516 // arithmetic type, there exist candidate operator functions of
5517 // the form
5518 //
5519 // VQ L& operator=(VQ L&, R);
5520 // VQ L& operator*=(VQ L&, R);
5521 // VQ L& operator/=(VQ L&, R);
5522 // VQ L& operator+=(VQ L&, R);
5523 // VQ L& operator-=(VQ L&, R);
5524 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005525 if (!HasArithmeticOrEnumeralCandidateType)
5526 return;
5527
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005528 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5529 for (unsigned Right = FirstPromotedArithmeticType;
5530 Right < LastPromotedArithmeticType; ++Right) {
5531 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005532 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005533
5534 // Add this built-in operator as a candidate (VQ is empty).
5535 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005536 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005537 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5538 /*IsAssigmentOperator=*/isEqualOp);
5539
5540 // Add this built-in operator as a candidate (VQ is 'volatile').
5541 if (VisibleTypeConversionsQuals.hasVolatile()) {
5542 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005543 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005544 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005545 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5546 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005547 /*IsAssigmentOperator=*/isEqualOp);
5548 }
5549 }
5550 }
5551
5552 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5553 for (BuiltinCandidateTypeSet::iterator
5554 Vec1 = CandidateTypes[0].vector_begin(),
5555 Vec1End = CandidateTypes[0].vector_end();
5556 Vec1 != Vec1End; ++Vec1) {
5557 for (BuiltinCandidateTypeSet::iterator
5558 Vec2 = CandidateTypes[1].vector_begin(),
5559 Vec2End = CandidateTypes[1].vector_end();
5560 Vec2 != Vec2End; ++Vec2) {
5561 QualType ParamTypes[2];
5562 ParamTypes[1] = *Vec2;
5563 // Add this built-in operator as a candidate (VQ is empty).
5564 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5565 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5566 /*IsAssigmentOperator=*/isEqualOp);
5567
5568 // Add this built-in operator as a candidate (VQ is 'volatile').
5569 if (VisibleTypeConversionsQuals.hasVolatile()) {
5570 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5571 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005572 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5573 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005574 /*IsAssigmentOperator=*/isEqualOp);
5575 }
5576 }
5577 }
5578 }
5579
5580 // C++ [over.built]p22:
5581 //
5582 // For every triple (L, VQ, R), where L is an integral type, VQ
5583 // is either volatile or empty, and R is a promoted integral
5584 // type, there exist candidate operator functions of the form
5585 //
5586 // VQ L& operator%=(VQ L&, R);
5587 // VQ L& operator<<=(VQ L&, R);
5588 // VQ L& operator>>=(VQ L&, R);
5589 // VQ L& operator&=(VQ L&, R);
5590 // VQ L& operator^=(VQ L&, R);
5591 // VQ L& operator|=(VQ L&, R);
5592 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005593 if (!HasArithmeticOrEnumeralCandidateType)
5594 return;
5595
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005596 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5597 for (unsigned Right = FirstPromotedIntegralType;
5598 Right < LastPromotedIntegralType; ++Right) {
5599 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005600 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005601
5602 // Add this built-in operator as a candidate (VQ is empty).
5603 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005604 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005605 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5606 if (VisibleTypeConversionsQuals.hasVolatile()) {
5607 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00005608 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005609 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5610 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5611 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5612 CandidateSet);
5613 }
5614 }
5615 }
5616 }
5617
5618 // C++ [over.operator]p23:
5619 //
5620 // There also exist candidate operator functions of the form
5621 //
5622 // bool operator!(bool);
5623 // bool operator&&(bool, bool);
5624 // bool operator||(bool, bool);
5625 void addExclaimOverload() {
5626 QualType ParamTy = S.Context.BoolTy;
5627 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5628 /*IsAssignmentOperator=*/false,
5629 /*NumContextualBoolArguments=*/1);
5630 }
5631 void addAmpAmpOrPipePipeOverload() {
5632 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5633 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5634 /*IsAssignmentOperator=*/false,
5635 /*NumContextualBoolArguments=*/2);
5636 }
5637
5638 // C++ [over.built]p13:
5639 //
5640 // For every cv-qualified or cv-unqualified object type T there
5641 // exist candidate operator functions of the form
5642 //
5643 // T* operator+(T*, ptrdiff_t); [ABOVE]
5644 // T& operator[](T*, ptrdiff_t);
5645 // T* operator-(T*, ptrdiff_t); [ABOVE]
5646 // T* operator+(ptrdiff_t, T*); [ABOVE]
5647 // T& operator[](ptrdiff_t, T*);
5648 void addSubscriptOverloads() {
5649 for (BuiltinCandidateTypeSet::iterator
5650 Ptr = CandidateTypes[0].pointer_begin(),
5651 PtrEnd = CandidateTypes[0].pointer_end();
5652 Ptr != PtrEnd; ++Ptr) {
5653 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5654 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005655 if (!PointeeType->isObjectType())
5656 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005657
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005658 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5659
5660 // T& operator[](T*, ptrdiff_t)
5661 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5662 }
5663
5664 for (BuiltinCandidateTypeSet::iterator
5665 Ptr = CandidateTypes[1].pointer_begin(),
5666 PtrEnd = CandidateTypes[1].pointer_end();
5667 Ptr != PtrEnd; ++Ptr) {
5668 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5669 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005670 if (!PointeeType->isObjectType())
5671 continue;
5672
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005673 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5674
5675 // T& operator[](ptrdiff_t, T*)
5676 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5677 }
5678 }
5679
5680 // C++ [over.built]p11:
5681 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5682 // C1 is the same type as C2 or is a derived class of C2, T is an object
5683 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5684 // there exist candidate operator functions of the form
5685 //
5686 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5687 //
5688 // where CV12 is the union of CV1 and CV2.
5689 void addArrowStarOverloads() {
5690 for (BuiltinCandidateTypeSet::iterator
5691 Ptr = CandidateTypes[0].pointer_begin(),
5692 PtrEnd = CandidateTypes[0].pointer_end();
5693 Ptr != PtrEnd; ++Ptr) {
5694 QualType C1Ty = (*Ptr);
5695 QualType C1;
5696 QualifierCollector Q1;
5697 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5698 if (!isa<RecordType>(C1))
5699 continue;
5700 // heuristic to reduce number of builtin candidates in the set.
5701 // Add volatile/restrict version only if there are conversions to a
5702 // volatile/restrict type.
5703 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5704 continue;
5705 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5706 continue;
5707 for (BuiltinCandidateTypeSet::iterator
5708 MemPtr = CandidateTypes[1].member_pointer_begin(),
5709 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5710 MemPtr != MemPtrEnd; ++MemPtr) {
5711 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5712 QualType C2 = QualType(mptr->getClass(), 0);
5713 C2 = C2.getUnqualifiedType();
5714 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5715 break;
5716 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5717 // build CV12 T&
5718 QualType T = mptr->getPointeeType();
5719 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5720 T.isVolatileQualified())
5721 continue;
5722 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5723 T.isRestrictQualified())
5724 continue;
5725 T = Q1.apply(S.Context, T);
5726 QualType ResultTy = S.Context.getLValueReferenceType(T);
5727 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5728 }
5729 }
5730 }
5731
5732 // Note that we don't consider the first argument, since it has been
5733 // contextually converted to bool long ago. The candidates below are
5734 // therefore added as binary.
5735 //
5736 // C++ [over.built]p25:
5737 // For every type T, where T is a pointer, pointer-to-member, or scoped
5738 // enumeration type, there exist candidate operator functions of the form
5739 //
5740 // T operator?(bool, T, T);
5741 //
5742 void addConditionalOperatorOverloads() {
5743 /// Set of (canonical) types that we've already handled.
5744 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5745
5746 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5747 for (BuiltinCandidateTypeSet::iterator
5748 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5749 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5750 Ptr != PtrEnd; ++Ptr) {
5751 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5752 continue;
5753
5754 QualType ParamTypes[2] = { *Ptr, *Ptr };
5755 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5756 }
5757
5758 for (BuiltinCandidateTypeSet::iterator
5759 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5760 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5761 MemPtr != MemPtrEnd; ++MemPtr) {
5762 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5763 continue;
5764
5765 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5766 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5767 }
5768
5769 if (S.getLangOptions().CPlusPlus0x) {
5770 for (BuiltinCandidateTypeSet::iterator
5771 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5772 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5773 Enum != EnumEnd; ++Enum) {
5774 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5775 continue;
5776
5777 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5778 continue;
5779
5780 QualType ParamTypes[2] = { *Enum, *Enum };
5781 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5782 }
5783 }
5784 }
5785 }
5786};
5787
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005788} // end anonymous namespace
5789
5790/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5791/// operator overloads to the candidate set (C++ [over.built]), based
5792/// on the operator @p Op and the arguments given. For example, if the
5793/// operator is a binary '+', this routine might add "int
5794/// operator+(int, int)" to cover integer addition.
5795void
5796Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5797 SourceLocation OpLoc,
5798 Expr **Args, unsigned NumArgs,
5799 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005800 // Find all of the types that the arguments can convert to, but only
5801 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00005802 // that make use of these types. Also record whether we encounter non-record
5803 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005804 Qualifiers VisibleTypeConversionsQuals;
5805 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005806 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5807 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00005808
5809 bool HasNonRecordCandidateType = false;
5810 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005811 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5812 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5813 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5814 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5815 OpLoc,
5816 true,
5817 (Op == OO_Exclaim ||
5818 Op == OO_AmpAmp ||
5819 Op == OO_PipePipe),
5820 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00005821 HasNonRecordCandidateType = HasNonRecordCandidateType ||
5822 CandidateTypes[ArgIdx].hasNonRecordTypes();
5823 HasArithmeticOrEnumeralCandidateType =
5824 HasArithmeticOrEnumeralCandidateType ||
5825 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005826 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005827
Chandler Carruth00a38332010-12-13 01:44:01 +00005828 // Exit early when no non-record types have been added to the candidate set
5829 // for any of the arguments to the operator.
5830 if (!HasNonRecordCandidateType)
5831 return;
5832
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005833 // Setup an object to manage the common state for building overloads.
5834 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
5835 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005836 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005837 CandidateTypes, CandidateSet);
5838
5839 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00005840 switch (Op) {
5841 case OO_None:
5842 case NUM_OVERLOADED_OPERATORS:
5843 assert(false && "Expected an overloaded operator");
5844 break;
5845
Chandler Carruth5184de02010-12-12 08:51:33 +00005846 case OO_New:
5847 case OO_Delete:
5848 case OO_Array_New:
5849 case OO_Array_Delete:
5850 case OO_Call:
5851 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
5852 break;
5853
5854 case OO_Comma:
5855 case OO_Arrow:
5856 // C++ [over.match.oper]p3:
5857 // -- For the operator ',', the unary operator '&', or the
5858 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00005859 break;
5860
5861 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00005862 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005863 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00005864 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00005865
5866 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00005867 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005868 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00005869 } else {
5870 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
5871 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5872 }
Douglas Gregord08452f2008-11-19 15:42:04 +00005873 break;
5874
Chandler Carruth5184de02010-12-12 08:51:33 +00005875 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00005876 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00005877 OpBuilder.addUnaryStarPointerOverloads();
5878 else
5879 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5880 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005881
Chandler Carruth5184de02010-12-12 08:51:33 +00005882 case OO_Slash:
5883 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00005884 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005885
5886 case OO_PlusPlus:
5887 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005888 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
5889 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00005890 break;
5891
Douglas Gregor84605ae2009-08-24 13:43:27 +00005892 case OO_EqualEqual:
5893 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005894 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00005895 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00005896
Douglas Gregora11693b2008-11-12 17:17:38 +00005897 case OO_Less:
5898 case OO_Greater:
5899 case OO_LessEqual:
5900 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005901 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00005902 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
5903 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005904
Douglas Gregora11693b2008-11-12 17:17:38 +00005905 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00005906 case OO_Caret:
5907 case OO_Pipe:
5908 case OO_LessLess:
5909 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005910 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00005911 break;
5912
Chandler Carruth5184de02010-12-12 08:51:33 +00005913 case OO_Amp: // '&' is either unary or binary
5914 if (NumArgs == 1)
5915 // C++ [over.match.oper]p3:
5916 // -- For the operator ',', the unary operator '&', or the
5917 // operator '->', the built-in candidates set is empty.
5918 break;
5919
5920 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
5921 break;
5922
5923 case OO_Tilde:
5924 OpBuilder.addUnaryTildePromotedIntegralOverloads();
5925 break;
5926
Douglas Gregora11693b2008-11-12 17:17:38 +00005927 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005928 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005929 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00005930
5931 case OO_PlusEqual:
5932 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005933 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005934 // Fall through.
5935
5936 case OO_StarEqual:
5937 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005938 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005939 break;
5940
5941 case OO_PercentEqual:
5942 case OO_LessLessEqual:
5943 case OO_GreaterGreaterEqual:
5944 case OO_AmpEqual:
5945 case OO_CaretEqual:
5946 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005947 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005948 break;
5949
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005950 case OO_Exclaim:
5951 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00005952 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005953
Douglas Gregora11693b2008-11-12 17:17:38 +00005954 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005955 case OO_PipePipe:
5956 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00005957 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005958
5959 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005960 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005961 break;
5962
5963 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005964 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005965 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005966
5967 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005968 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00005969 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5970 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005971 }
5972}
5973
Douglas Gregore254f902009-02-04 00:32:51 +00005974/// \brief Add function candidates found via argument-dependent lookup
5975/// to the set of overloading candidates.
5976///
5977/// This routine performs argument-dependent name lookup based on the
5978/// given function name (which may also be an operator name) and adds
5979/// all of the overload candidates found by ADL to the overload
5980/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005981void
Douglas Gregore254f902009-02-04 00:32:51 +00005982Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005983 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005984 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005985 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005986 OverloadCandidateSet& CandidateSet,
5987 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005988 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005989
John McCall91f61fc2010-01-26 06:04:06 +00005990 // FIXME: This approach for uniquing ADL results (and removing
5991 // redundant candidates from the set) relies on pointer-equality,
5992 // which means we need to key off the canonical decl. However,
5993 // always going back to the canonical decl might not get us the
5994 // right set of default arguments. What default arguments are
5995 // we supposed to consider on ADL candidates, anyway?
5996
Douglas Gregorcabea402009-09-22 15:41:20 +00005997 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005998 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005999
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006000 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006001 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6002 CandEnd = CandidateSet.end();
6003 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006004 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006005 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006006 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006007 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006008 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006009
6010 // For each of the ADL candidates we found, add it to the overload
6011 // set.
John McCall8fe68082010-01-26 07:16:45 +00006012 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006013 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006014 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006015 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006016 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006017
John McCalla0296f72010-03-19 07:35:19 +00006018 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006019 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006020 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006021 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006022 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006023 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006024 }
Douglas Gregore254f902009-02-04 00:32:51 +00006025}
6026
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006027/// isBetterOverloadCandidate - Determines whether the first overload
6028/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006029bool
John McCall5c32be02010-08-24 20:38:10 +00006030isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006031 const OverloadCandidate &Cand1,
6032 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006033 SourceLocation Loc,
6034 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006035 // Define viable functions to be better candidates than non-viable
6036 // functions.
6037 if (!Cand2.Viable)
6038 return Cand1.Viable;
6039 else if (!Cand1.Viable)
6040 return false;
6041
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006042 // C++ [over.match.best]p1:
6043 //
6044 // -- if F is a static member function, ICS1(F) is defined such
6045 // that ICS1(F) is neither better nor worse than ICS1(G) for
6046 // any function G, and, symmetrically, ICS1(G) is neither
6047 // better nor worse than ICS1(F).
6048 unsigned StartArg = 0;
6049 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6050 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006051
Douglas Gregord3cb3562009-07-07 23:38:56 +00006052 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006053 // A viable function F1 is defined to be a better function than another
6054 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006055 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006056 unsigned NumArgs = Cand1.Conversions.size();
6057 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6058 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006059 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006060 switch (CompareImplicitConversionSequences(S,
6061 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006062 Cand2.Conversions[ArgIdx])) {
6063 case ImplicitConversionSequence::Better:
6064 // Cand1 has a better conversion sequence.
6065 HasBetterConversion = true;
6066 break;
6067
6068 case ImplicitConversionSequence::Worse:
6069 // Cand1 can't be better than Cand2.
6070 return false;
6071
6072 case ImplicitConversionSequence::Indistinguishable:
6073 // Do nothing.
6074 break;
6075 }
6076 }
6077
Mike Stump11289f42009-09-09 15:08:12 +00006078 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006079 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006080 if (HasBetterConversion)
6081 return true;
6082
Mike Stump11289f42009-09-09 15:08:12 +00006083 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006084 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006085 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006086 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6087 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006088
6089 // -- F1 and F2 are function template specializations, and the function
6090 // template for F1 is more specialized than the template for F2
6091 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006092 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006093 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006094 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006095 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006096 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6097 Cand2.Function->getPrimaryTemplate(),
6098 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006099 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006100 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006101 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006102 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006103 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006104
Douglas Gregora1f013e2008-11-07 22:36:19 +00006105 // -- the context is an initialization by user-defined conversion
6106 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6107 // from the return type of F1 to the destination type (i.e.,
6108 // the type of the entity being initialized) is a better
6109 // conversion sequence than the standard conversion sequence
6110 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006111 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006112 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006113 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006114 switch (CompareStandardConversionSequences(S,
6115 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006116 Cand2.FinalConversion)) {
6117 case ImplicitConversionSequence::Better:
6118 // Cand1 has a better conversion sequence.
6119 return true;
6120
6121 case ImplicitConversionSequence::Worse:
6122 // Cand1 can't be better than Cand2.
6123 return false;
6124
6125 case ImplicitConversionSequence::Indistinguishable:
6126 // Do nothing
6127 break;
6128 }
6129 }
6130
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006131 return false;
6132}
6133
Mike Stump11289f42009-09-09 15:08:12 +00006134/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006135/// within an overload candidate set.
6136///
6137/// \param CandidateSet the set of candidate functions.
6138///
6139/// \param Loc the location of the function name (or operator symbol) for
6140/// which overload resolution occurs.
6141///
Mike Stump11289f42009-09-09 15:08:12 +00006142/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006143/// function, Best points to the candidate function found.
6144///
6145/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006146OverloadingResult
6147OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006148 iterator &Best,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006149 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006150 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006151 Best = end();
6152 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6153 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006154 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006155 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006156 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006157 }
6158
6159 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006160 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006161 return OR_No_Viable_Function;
6162
6163 // Make sure that this function is better than every other viable
6164 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006165 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006166 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006167 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006168 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006169 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006170 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006171 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006172 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006173 }
Mike Stump11289f42009-09-09 15:08:12 +00006174
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006175 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006176 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006177 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006178 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006179 return OR_Deleted;
6180
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006181 // C++ [basic.def.odr]p2:
6182 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00006183 // when referred to from a potentially-evaluated expression. [Note: this
6184 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006185 // (clause 13), user-defined conversions (12.3.2), allocation function for
6186 // placement new (5.3.4), as well as non-default initialization (8.5).
6187 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00006188 S.MarkDeclarationReferenced(Loc, Best->Function);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006189
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006190 return OR_Success;
6191}
6192
John McCall53262c92010-01-12 02:15:36 +00006193namespace {
6194
6195enum OverloadCandidateKind {
6196 oc_function,
6197 oc_method,
6198 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006199 oc_function_template,
6200 oc_method_template,
6201 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006202 oc_implicit_default_constructor,
6203 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006204 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00006205};
6206
John McCalle1ac8d12010-01-13 00:25:19 +00006207OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6208 FunctionDecl *Fn,
6209 std::string &Description) {
6210 bool isTemplate = false;
6211
6212 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6213 isTemplate = true;
6214 Description = S.getTemplateArgumentBindingsText(
6215 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6216 }
John McCallfd0b2f82010-01-06 09:43:14 +00006217
6218 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006219 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006220 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006221
John McCall53262c92010-01-12 02:15:36 +00006222 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6223 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006224 }
6225
6226 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6227 // This actually gets spelled 'candidate function' for now, but
6228 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006229 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006230 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006231
Douglas Gregorec3bec02010-09-27 22:37:28 +00006232 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006233 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006234 return oc_implicit_copy_assignment;
6235 }
6236
John McCalle1ac8d12010-01-13 00:25:19 +00006237 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006238}
6239
6240} // end anonymous namespace
6241
6242// Notes the location of an overload candidate.
6243void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006244 std::string FnDesc;
6245 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6246 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6247 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00006248}
6249
John McCall0d1da222010-01-12 00:44:57 +00006250/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6251/// "lead" diagnostic; it will be given two arguments, the source and
6252/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006253void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6254 Sema &S,
6255 SourceLocation CaretLoc,
6256 const PartialDiagnostic &PDiag) const {
6257 S.Diag(CaretLoc, PDiag)
6258 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006259 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006260 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6261 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006262 }
John McCall12f97bc2010-01-08 04:41:39 +00006263}
6264
John McCall0d1da222010-01-12 00:44:57 +00006265namespace {
6266
John McCall6a61b522010-01-13 09:16:55 +00006267void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6268 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6269 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006270 assert(Cand->Function && "for now, candidate must be a function");
6271 FunctionDecl *Fn = Cand->Function;
6272
6273 // There's a conversion slot for the object argument if this is a
6274 // non-constructor method. Note that 'I' corresponds the
6275 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006276 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006277 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006278 if (I == 0)
6279 isObjectArgument = true;
6280 else
6281 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006282 }
6283
John McCalle1ac8d12010-01-13 00:25:19 +00006284 std::string FnDesc;
6285 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6286
John McCall6a61b522010-01-13 09:16:55 +00006287 Expr *FromExpr = Conv.Bad.FromExpr;
6288 QualType FromTy = Conv.Bad.getFromType();
6289 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006290
John McCallfb7ad0f2010-02-02 02:42:52 +00006291 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006292 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006293 Expr *E = FromExpr->IgnoreParens();
6294 if (isa<UnaryOperator>(E))
6295 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006296 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006297
6298 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6299 << (unsigned) FnKind << FnDesc
6300 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6301 << ToTy << Name << I+1;
6302 return;
6303 }
6304
John McCall6d174642010-01-23 08:10:49 +00006305 // Do some hand-waving analysis to see if the non-viability is due
6306 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006307 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6308 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6309 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6310 CToTy = RT->getPointeeType();
6311 else {
6312 // TODO: detect and diagnose the full richness of const mismatches.
6313 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6314 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6315 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6316 }
6317
6318 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6319 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6320 // It is dumb that we have to do this here.
6321 while (isa<ArrayType>(CFromTy))
6322 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6323 while (isa<ArrayType>(CToTy))
6324 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6325
6326 Qualifiers FromQs = CFromTy.getQualifiers();
6327 Qualifiers ToQs = CToTy.getQualifiers();
6328
6329 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6330 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6331 << (unsigned) FnKind << FnDesc
6332 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6333 << FromTy
6334 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6335 << (unsigned) isObjectArgument << I+1;
6336 return;
6337 }
6338
6339 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6340 assert(CVR && "unexpected qualifiers mismatch");
6341
6342 if (isObjectArgument) {
6343 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6344 << (unsigned) FnKind << FnDesc
6345 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6346 << FromTy << (CVR - 1);
6347 } else {
6348 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6349 << (unsigned) FnKind << FnDesc
6350 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6351 << FromTy << (CVR - 1) << I+1;
6352 }
6353 return;
6354 }
6355
John McCall6d174642010-01-23 08:10:49 +00006356 // Diagnose references or pointers to incomplete types differently,
6357 // since it's far from impossible that the incompleteness triggered
6358 // the failure.
6359 QualType TempFromTy = FromTy.getNonReferenceType();
6360 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6361 TempFromTy = PTy->getPointeeType();
6362 if (TempFromTy->isIncompleteType()) {
6363 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6364 << (unsigned) FnKind << FnDesc
6365 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6366 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6367 return;
6368 }
6369
Douglas Gregor56f2e342010-06-30 23:01:39 +00006370 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006371 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006372 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6373 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6374 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6375 FromPtrTy->getPointeeType()) &&
6376 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6377 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006378 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00006379 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006380 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006381 }
6382 } else if (const ObjCObjectPointerType *FromPtrTy
6383 = FromTy->getAs<ObjCObjectPointerType>()) {
6384 if (const ObjCObjectPointerType *ToPtrTy
6385 = ToTy->getAs<ObjCObjectPointerType>())
6386 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6387 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6388 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6389 FromPtrTy->getPointeeType()) &&
6390 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006391 BaseToDerivedConversion = 2;
6392 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6393 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6394 !FromTy->isIncompleteType() &&
6395 !ToRefTy->getPointeeType()->isIncompleteType() &&
6396 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6397 BaseToDerivedConversion = 3;
6398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006399
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006400 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006401 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006402 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006403 << (unsigned) FnKind << FnDesc
6404 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006405 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006406 << FromTy << ToTy << I+1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006407 return;
6408 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006409
John McCall47000992010-01-14 03:28:57 +00006410 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006411 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6412 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006413 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006414 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00006415}
6416
6417void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6418 unsigned NumFormalArgs) {
6419 // TODO: treat calls to a missing default constructor as a special case
6420
6421 FunctionDecl *Fn = Cand->Function;
6422 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6423
6424 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006425
John McCall6a61b522010-01-13 09:16:55 +00006426 // at least / at most / exactly
6427 unsigned mode, modeCount;
6428 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006429 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6430 (Cand->FailureKind == ovl_fail_bad_deduction &&
6431 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006432 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00006433 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00006434 mode = 0; // "at least"
6435 else
6436 mode = 2; // "exactly"
6437 modeCount = MinParams;
6438 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006439 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6440 (Cand->FailureKind == ovl_fail_bad_deduction &&
6441 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006442 if (MinParams != FnTy->getNumArgs())
6443 mode = 1; // "at most"
6444 else
6445 mode = 2; // "exactly"
6446 modeCount = FnTy->getNumArgs();
6447 }
6448
6449 std::string Description;
6450 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6451
6452 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006453 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00006454 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00006455}
6456
John McCall8b9ed552010-02-01 18:53:26 +00006457/// Diagnose a failed template-argument deduction.
6458void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6459 Expr **Args, unsigned NumArgs) {
6460 FunctionDecl *Fn = Cand->Function; // pattern
6461
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006462 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006463 NamedDecl *ParamD;
6464 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6465 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6466 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006467 switch (Cand->DeductionFailure.Result) {
6468 case Sema::TDK_Success:
6469 llvm_unreachable("TDK_success while diagnosing bad deduction");
6470
6471 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006472 assert(ParamD && "no parameter found for incomplete deduction result");
6473 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6474 << ParamD->getDeclName();
6475 return;
6476 }
6477
John McCall42d7d192010-08-05 09:05:08 +00006478 case Sema::TDK_Underqualified: {
6479 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6480 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6481
6482 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6483
6484 // Param will have been canonicalized, but it should just be a
6485 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00006486 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00006487 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00006488 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00006489 assert(S.Context.hasSameType(Param, NonCanonParam));
6490
6491 // Arg has also been canonicalized, but there's nothing we can do
6492 // about that. It also doesn't matter as much, because it won't
6493 // have any template parameters in it (because deduction isn't
6494 // done on dependent types).
6495 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6496
6497 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6498 << ParamD->getDeclName() << Arg << NonCanonParam;
6499 return;
6500 }
6501
6502 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00006503 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006504 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006505 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006506 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006507 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006508 which = 1;
6509 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006510 which = 2;
6511 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006512
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006513 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006514 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006515 << *Cand->DeductionFailure.getFirstArg()
6516 << *Cand->DeductionFailure.getSecondArg();
6517 return;
6518 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006519
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006520 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006521 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006522 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006523 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006524 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6525 << ParamD->getDeclName();
6526 else {
6527 int index = 0;
6528 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6529 index = TTP->getIndex();
6530 else if (NonTypeTemplateParmDecl *NTTP
6531 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6532 index = NTTP->getIndex();
6533 else
6534 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006535 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006536 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6537 << (index + 1);
6538 }
6539 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006540
Douglas Gregor02eb4832010-05-08 18:13:28 +00006541 case Sema::TDK_TooManyArguments:
6542 case Sema::TDK_TooFewArguments:
6543 DiagnoseArityMismatch(S, Cand, NumArgs);
6544 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006545
6546 case Sema::TDK_InstantiationDepth:
6547 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6548 return;
6549
6550 case Sema::TDK_SubstitutionFailure: {
6551 std::string ArgString;
6552 if (TemplateArgumentList *Args
6553 = Cand->DeductionFailure.getTemplateArgumentList())
6554 ArgString = S.getTemplateArgumentBindingsText(
6555 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6556 *Args);
6557 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6558 << ArgString;
6559 return;
6560 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006561
John McCall8b9ed552010-02-01 18:53:26 +00006562 // TODO: diagnose these individually, then kill off
6563 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006564 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006565 case Sema::TDK_FailedOverloadResolution:
6566 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6567 return;
6568 }
6569}
6570
6571/// Generates a 'note' diagnostic for an overload candidate. We've
6572/// already generated a primary error at the call site.
6573///
6574/// It really does need to be a single diagnostic with its caret
6575/// pointed at the candidate declaration. Yes, this creates some
6576/// major challenges of technical writing. Yes, this makes pointing
6577/// out problems with specific arguments quite awkward. It's still
6578/// better than generating twenty screens of text for every failed
6579/// overload.
6580///
6581/// It would be great to be able to express per-candidate problems
6582/// more richly for those diagnostic clients that cared, but we'd
6583/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006584void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6585 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006586 FunctionDecl *Fn = Cand->Function;
6587
John McCall12f97bc2010-01-08 04:41:39 +00006588 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00006589 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006590 std::string FnDesc;
6591 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006592
6593 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006594 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00006595 return;
John McCall12f97bc2010-01-08 04:41:39 +00006596 }
6597
John McCalle1ac8d12010-01-13 00:25:19 +00006598 // We don't really have anything else to say about viable candidates.
6599 if (Cand->Viable) {
6600 S.NoteOverloadCandidate(Fn);
6601 return;
6602 }
John McCall0d1da222010-01-12 00:44:57 +00006603
John McCall6a61b522010-01-13 09:16:55 +00006604 switch (Cand->FailureKind) {
6605 case ovl_fail_too_many_arguments:
6606 case ovl_fail_too_few_arguments:
6607 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006608
John McCall6a61b522010-01-13 09:16:55 +00006609 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006610 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6611
John McCallfe796dd2010-01-23 05:17:32 +00006612 case ovl_fail_trivial_conversion:
6613 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006614 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006615 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006616
John McCall65eb8792010-02-25 01:37:24 +00006617 case ovl_fail_bad_conversion: {
6618 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6619 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006620 if (Cand->Conversions[I].isBad())
6621 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006622
John McCall6a61b522010-01-13 09:16:55 +00006623 // FIXME: this currently happens when we're called from SemaInit
6624 // when user-conversion overload fails. Figure out how to handle
6625 // those conditions and diagnose them well.
6626 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006627 }
John McCall65eb8792010-02-25 01:37:24 +00006628 }
John McCalld3224162010-01-08 00:58:21 +00006629}
6630
6631void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6632 // Desugar the type of the surrogate down to a function type,
6633 // retaining as many typedefs as possible while still showing
6634 // the function type (and, therefore, its parameter types).
6635 QualType FnType = Cand->Surrogate->getConversionType();
6636 bool isLValueReference = false;
6637 bool isRValueReference = false;
6638 bool isPointer = false;
6639 if (const LValueReferenceType *FnTypeRef =
6640 FnType->getAs<LValueReferenceType>()) {
6641 FnType = FnTypeRef->getPointeeType();
6642 isLValueReference = true;
6643 } else if (const RValueReferenceType *FnTypeRef =
6644 FnType->getAs<RValueReferenceType>()) {
6645 FnType = FnTypeRef->getPointeeType();
6646 isRValueReference = true;
6647 }
6648 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6649 FnType = FnTypePtr->getPointeeType();
6650 isPointer = true;
6651 }
6652 // Desugar down to a function type.
6653 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6654 // Reconstruct the pointer/reference as appropriate.
6655 if (isPointer) FnType = S.Context.getPointerType(FnType);
6656 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6657 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6658
6659 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6660 << FnType;
6661}
6662
6663void NoteBuiltinOperatorCandidate(Sema &S,
6664 const char *Opc,
6665 SourceLocation OpLoc,
6666 OverloadCandidate *Cand) {
6667 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6668 std::string TypeStr("operator");
6669 TypeStr += Opc;
6670 TypeStr += "(";
6671 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6672 if (Cand->Conversions.size() == 1) {
6673 TypeStr += ")";
6674 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6675 } else {
6676 TypeStr += ", ";
6677 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6678 TypeStr += ")";
6679 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6680 }
6681}
6682
6683void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6684 OverloadCandidate *Cand) {
6685 unsigned NoOperands = Cand->Conversions.size();
6686 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6687 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006688 if (ICS.isBad()) break; // all meaningless after first invalid
6689 if (!ICS.isAmbiguous()) continue;
6690
John McCall5c32be02010-08-24 20:38:10 +00006691 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006692 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006693 }
6694}
6695
John McCall3712d9e2010-01-15 23:32:50 +00006696SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6697 if (Cand->Function)
6698 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006699 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006700 return Cand->Surrogate->getLocation();
6701 return SourceLocation();
6702}
6703
John McCallad2587a2010-01-12 00:48:53 +00006704struct CompareOverloadCandidatesForDisplay {
6705 Sema &S;
6706 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006707
6708 bool operator()(const OverloadCandidate *L,
6709 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006710 // Fast-path this check.
6711 if (L == R) return false;
6712
John McCall12f97bc2010-01-08 04:41:39 +00006713 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006714 if (L->Viable) {
6715 if (!R->Viable) return true;
6716
6717 // TODO: introduce a tri-valued comparison for overload
6718 // candidates. Would be more worthwhile if we had a sort
6719 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006720 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6721 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006722 } else if (R->Viable)
6723 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006724
John McCall3712d9e2010-01-15 23:32:50 +00006725 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006726
John McCall3712d9e2010-01-15 23:32:50 +00006727 // Criteria by which we can sort non-viable candidates:
6728 if (!L->Viable) {
6729 // 1. Arity mismatches come after other candidates.
6730 if (L->FailureKind == ovl_fail_too_many_arguments ||
6731 L->FailureKind == ovl_fail_too_few_arguments)
6732 return false;
6733 if (R->FailureKind == ovl_fail_too_many_arguments ||
6734 R->FailureKind == ovl_fail_too_few_arguments)
6735 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006736
John McCallfe796dd2010-01-23 05:17:32 +00006737 // 2. Bad conversions come first and are ordered by the number
6738 // of bad conversions and quality of good conversions.
6739 if (L->FailureKind == ovl_fail_bad_conversion) {
6740 if (R->FailureKind != ovl_fail_bad_conversion)
6741 return true;
6742
6743 // If there's any ordering between the defined conversions...
6744 // FIXME: this might not be transitive.
6745 assert(L->Conversions.size() == R->Conversions.size());
6746
6747 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006748 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6749 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006750 switch (CompareImplicitConversionSequences(S,
6751 L->Conversions[I],
6752 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006753 case ImplicitConversionSequence::Better:
6754 leftBetter++;
6755 break;
6756
6757 case ImplicitConversionSequence::Worse:
6758 leftBetter--;
6759 break;
6760
6761 case ImplicitConversionSequence::Indistinguishable:
6762 break;
6763 }
6764 }
6765 if (leftBetter > 0) return true;
6766 if (leftBetter < 0) return false;
6767
6768 } else if (R->FailureKind == ovl_fail_bad_conversion)
6769 return false;
6770
John McCall3712d9e2010-01-15 23:32:50 +00006771 // TODO: others?
6772 }
6773
6774 // Sort everything else by location.
6775 SourceLocation LLoc = GetLocationForCandidate(L);
6776 SourceLocation RLoc = GetLocationForCandidate(R);
6777
6778 // Put candidates without locations (e.g. builtins) at the end.
6779 if (LLoc.isInvalid()) return false;
6780 if (RLoc.isInvalid()) return true;
6781
6782 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006783 }
6784};
6785
John McCallfe796dd2010-01-23 05:17:32 +00006786/// CompleteNonViableCandidate - Normally, overload resolution only
6787/// computes up to the first
6788void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6789 Expr **Args, unsigned NumArgs) {
6790 assert(!Cand->Viable);
6791
6792 // Don't do anything on failures other than bad conversion.
6793 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6794
6795 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006796 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006797 unsigned ConvCount = Cand->Conversions.size();
6798 while (true) {
6799 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6800 ConvIdx++;
6801 if (Cand->Conversions[ConvIdx - 1].isBad())
6802 break;
6803 }
6804
6805 if (ConvIdx == ConvCount)
6806 return;
6807
John McCall65eb8792010-02-25 01:37:24 +00006808 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6809 "remaining conversion is initialized?");
6810
Douglas Gregoradc7a702010-04-16 17:45:54 +00006811 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006812 // operation somehow.
6813 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006814
6815 const FunctionProtoType* Proto;
6816 unsigned ArgIdx = ConvIdx;
6817
6818 if (Cand->IsSurrogate) {
6819 QualType ConvType
6820 = Cand->Surrogate->getConversionType().getNonReferenceType();
6821 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6822 ConvType = ConvPtrType->getPointeeType();
6823 Proto = ConvType->getAs<FunctionProtoType>();
6824 ArgIdx--;
6825 } else if (Cand->Function) {
6826 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6827 if (isa<CXXMethodDecl>(Cand->Function) &&
6828 !isa<CXXConstructorDecl>(Cand->Function))
6829 ArgIdx--;
6830 } else {
6831 // Builtin binary operator with a bad first conversion.
6832 assert(ConvCount <= 3);
6833 for (; ConvIdx != ConvCount; ++ConvIdx)
6834 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006835 = TryCopyInitialization(S, Args[ConvIdx],
6836 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006837 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006838 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006839 return;
6840 }
6841
6842 // Fill in the rest of the conversions.
6843 unsigned NumArgsInProto = Proto->getNumArgs();
6844 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6845 if (ArgIdx < NumArgsInProto)
6846 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006847 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006848 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006849 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006850 else
6851 Cand->Conversions[ConvIdx].setEllipsis();
6852 }
6853}
6854
John McCalld3224162010-01-08 00:58:21 +00006855} // end anonymous namespace
6856
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006857/// PrintOverloadCandidates - When overload resolution fails, prints
6858/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006859/// set.
John McCall5c32be02010-08-24 20:38:10 +00006860void OverloadCandidateSet::NoteCandidates(Sema &S,
6861 OverloadCandidateDisplayKind OCD,
6862 Expr **Args, unsigned NumArgs,
6863 const char *Opc,
6864 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006865 // Sort the candidates by viability and position. Sorting directly would
6866 // be prohibitive, so we make a set of pointers and sort those.
6867 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00006868 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6869 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00006870 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006871 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006872 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00006873 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006874 if (Cand->Function || Cand->IsSurrogate)
6875 Cands.push_back(Cand);
6876 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6877 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006878 }
6879 }
6880
John McCallad2587a2010-01-12 00:48:53 +00006881 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00006882 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006883
John McCall0d1da222010-01-12 00:44:57 +00006884 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006885
John McCall12f97bc2010-01-08 04:41:39 +00006886 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00006887 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006888 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006889 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6890 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006891
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006892 // Set an arbitrary limit on the number of candidate functions we'll spam
6893 // the user with. FIXME: This limit should depend on details of the
6894 // candidate list.
6895 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6896 break;
6897 }
6898 ++CandsShown;
6899
John McCalld3224162010-01-08 00:58:21 +00006900 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00006901 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006902 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00006903 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006904 else {
6905 assert(Cand->Viable &&
6906 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006907 // Generally we only see ambiguities including viable builtin
6908 // operators if overload resolution got screwed up by an
6909 // ambiguous user-defined conversion.
6910 //
6911 // FIXME: It's quite possible for different conversions to see
6912 // different ambiguities, though.
6913 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00006914 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00006915 ReportedAmbiguousConversions = true;
6916 }
John McCalld3224162010-01-08 00:58:21 +00006917
John McCall0d1da222010-01-12 00:44:57 +00006918 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00006919 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006920 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006921 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006922
6923 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00006924 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006925}
6926
John McCalla0296f72010-03-19 07:35:19 +00006927static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006928 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006929 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006930
John McCalla0296f72010-03-19 07:35:19 +00006931 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006932}
6933
Douglas Gregorcd695e52008-11-10 20:40:00 +00006934/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6935/// an overloaded function (C++ [over.over]), where @p From is an
6936/// expression with overloaded function type and @p ToType is the type
6937/// we're trying to resolve to. For example:
6938///
6939/// @code
6940/// int f(double);
6941/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006942///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006943/// int (*pfd)(double) = f; // selects f(double)
6944/// @endcode
6945///
6946/// This routine returns the resulting FunctionDecl if it could be
6947/// resolved, and NULL otherwise. When @p Complain is true, this
6948/// routine will emit diagnostics if there is an error.
6949FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006950Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006951 bool Complain,
6952 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006953 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006954 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006955 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006956 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006957 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006958 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006959 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006960 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006961 FunctionType = MemTypePtr->getPointeeType();
6962 IsMember = true;
6963 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006964
Douglas Gregorcd695e52008-11-10 20:40:00 +00006965 // C++ [over.over]p1:
6966 // [...] [Note: any redundant set of parentheses surrounding the
6967 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006968 // C++ [over.over]p1:
6969 // [...] The overloaded function name can be preceded by the &
6970 // operator.
John McCall7d460512010-08-24 23:26:21 +00006971 // However, remember whether the expression has member-pointer form:
6972 // C++ [expr.unary.op]p4:
6973 // A pointer to member is only formed when an explicit & is used
6974 // and its operand is a qualified-id not enclosed in
6975 // parentheses.
John McCall8d08b9b2010-08-27 09:08:28 +00006976 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6977 OverloadExpr *OvlExpr = Ovl.Expression;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006978
Douglas Gregor064fdb22010-04-14 23:11:21 +00006979 // We expect a pointer or reference to function, or a function pointer.
6980 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6981 if (!FunctionType->isFunctionType()) {
6982 if (Complain)
6983 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6984 << OvlExpr->getName() << ToType;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006985
Douglas Gregor064fdb22010-04-14 23:11:21 +00006986 return 0;
6987 }
6988
John McCall24d18942010-08-24 22:52:39 +00006989 // If the overload expression doesn't have the form of a pointer to
John McCall7d460512010-08-24 23:26:21 +00006990 // member, don't try to convert it to a pointer-to-member type.
John McCall8d08b9b2010-08-27 09:08:28 +00006991 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCall24d18942010-08-24 22:52:39 +00006992 if (!Complain) return 0;
6993
6994 // TODO: Should we condition this on whether any functions might
6995 // have matched, or is it more appropriate to do that in callers?
6996 // TODO: a fixit wouldn't hurt.
6997 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6998 << ToType << OvlExpr->getSourceRange();
6999 return 0;
7000 }
7001
7002 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
7003 if (OvlExpr->hasExplicitTemplateArgs()) {
7004 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
7005 ExplicitTemplateArgs = &ETABuffer;
7006 }
7007
Douglas Gregor064fdb22010-04-14 23:11:21 +00007008 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00007009
Douglas Gregorcd695e52008-11-10 20:40:00 +00007010 // Look through all of the overloaded functions, searching for one
7011 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00007012 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00007013 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007014
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007015 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00007016 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7017 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007018 // Look through any using declarations to find the underlying function.
7019 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7020
Douglas Gregorcd695e52008-11-10 20:40:00 +00007021 // C++ [over.over]p3:
7022 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00007023 // targets of type "pointer-to-function" or "reference-to-function."
7024 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007025 // type "pointer-to-member-function."
7026 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00007027
Mike Stump11289f42009-09-09 15:08:12 +00007028 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007029 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00007030 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007031 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00007032 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007033 // static when converting to member pointer.
7034 if (Method->isStatic() == IsMember)
7035 continue;
7036 } else if (IsMember)
7037 continue;
Mike Stump11289f42009-09-09 15:08:12 +00007038
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007039 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00007040 // If the name is a function template, template argument deduction is
7041 // done (14.8.2.2), and if the argument deduction succeeds, the
7042 // resulting template argument list is used to generate a single
7043 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007044 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00007045 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00007046 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00007047 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00007048 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00007049 FunctionType, Specialization, Info)) {
7050 // FIXME: make a note of the failed deduction for diagnostics.
7051 (void)Result;
7052 } else {
Douglas Gregor4ed49f32010-09-29 21:14:36 +00007053 // Template argument deduction ensures that we have an exact match.
7054 // This function template specicalization works.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007055 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00007056 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00007057 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007058 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor9b146582009-07-08 20:55:45 +00007059 }
John McCalld14a8642009-11-21 08:51:07 +00007060
7061 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00007062 }
Mike Stump11289f42009-09-09 15:08:12 +00007063
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007064 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007065 // Skip non-static functions when converting to pointer, and static
7066 // when converting to member pointer.
7067 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00007068 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007069
Douglas Gregord3319842009-10-24 04:59:53 +00007070 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00007071 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00007072 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007073 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007074 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007075
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007076 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007077 QualType ResultTy;
7078 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007079 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007080 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00007081 Matches.push_back(std::make_pair(I.getPair(),
7082 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007083 FoundNonTemplateFunction = true;
7084 }
Mike Stump11289f42009-09-09 15:08:12 +00007085 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00007086 }
7087
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007088 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00007089 if (Matches.empty()) {
7090 if (Complain) {
7091 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
7092 << OvlExpr->getName() << FunctionType;
7093 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007094 E = OvlExpr->decls_end();
Douglas Gregor064fdb22010-04-14 23:11:21 +00007095 I != E; ++I)
7096 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
7097 NoteOverloadCandidate(F);
7098 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007099
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007100 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00007101 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00007102 FunctionDecl *Result = Matches[0].second;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007103 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007104 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007105 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00007106 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007107 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007108 return Result;
7109 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007110
7111 // C++ [over.over]p4:
7112 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00007113 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007114 // [...] and any given function template specialization F1 is
7115 // eliminated if the set contains a second function template
7116 // specialization whose function template is more specialized
7117 // than the function template of F1 according to the partial
7118 // ordering rules of 14.5.5.2.
7119
7120 // The algorithm specified above is quadratic. We instead use a
7121 // two-pass algorithm (similar to the one used to identify the
7122 // best viable function in an overload set) that identifies the
7123 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007124
7125 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7126 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7127 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007128
John McCall58cc69d2010-01-27 01:50:18 +00007129 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00007130 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00007131 TPOC_Other, 0, From->getLocStart(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007132 PDiag(),
7133 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00007134 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00007135 PDiag(diag::note_ovl_candidate)
7136 << (unsigned) oc_function_template);
Douglas Gregorbdd7b232010-09-12 08:16:09 +00007137 if (Result == MatchesCopy.end())
7138 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007139
John McCall58cc69d2010-01-27 01:50:18 +00007140 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00007141 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007142 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00007143 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00007144 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007145 }
Mike Stump11289f42009-09-09 15:08:12 +00007146
Douglas Gregorfae1d712009-09-26 03:56:17 +00007147 // [...] any function template specializations in the set are
7148 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00007149 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00007150 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00007151 ++I;
7152 else {
John McCalla0296f72010-03-19 07:35:19 +00007153 Matches[I] = Matches[--N];
7154 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00007155 }
7156 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007157
Mike Stump11289f42009-09-09 15:08:12 +00007158 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007159 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00007160 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00007161 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00007162 FoundResult = Matches[0].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007163 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00007164 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
7165 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007166 }
Mike Stump11289f42009-09-09 15:08:12 +00007167
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007168 // FIXME: We should probably return the same thing that BestViableFunction
7169 // returns (even if we issue the diagnostics here).
Douglas Gregore81f58e2010-11-08 03:40:48 +00007170 if (Complain) {
7171 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
7172 << Matches[0].second->getDeclName();
7173 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7174 NoteOverloadCandidate(Matches[I].second);
7175 }
7176
Douglas Gregorcd695e52008-11-10 20:40:00 +00007177 return 0;
7178}
7179
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007180/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007181/// resolve that overloaded function expression down to a single function.
7182///
7183/// This routine can only resolve template-ids that refer to a single function
7184/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007185/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007186/// as described in C++0x [temp.arg.explicit]p3.
7187FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
7188 // C++ [over.over]p1:
7189 // [...] [Note: any redundant set of parentheses surrounding the
7190 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007191 // C++ [over.over]p1:
7192 // [...] The overloaded function name can be preceded by the &
7193 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00007194
7195 if (From->getType() != Context.OverloadTy)
7196 return 0;
7197
John McCall8d08b9b2010-08-27 09:08:28 +00007198 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007199
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007200 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00007201 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007202 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007203
7204 TemplateArgumentListInfo ExplicitTemplateArgs;
7205 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007206
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007207 // Look through all of the overloaded functions, searching for one
7208 // whose type matches exactly.
7209 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00007210 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7211 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007212 // C++0x [temp.arg.explicit]p3:
7213 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007214 // where deduction is not done, if a template argument list is
7215 // specified and it, along with any default template arguments,
7216 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007217 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00007218 FunctionTemplateDecl *FunctionTemplate
7219 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007220
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007221 // C++ [over.over]p2:
7222 // If the name is a function template, template argument deduction is
7223 // done (14.8.2.2), and if the argument deduction succeeds, the
7224 // resulting template argument list is used to generate a single
7225 // function template specialization, which is added to the set of
7226 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007227 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00007228 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007229 if (TemplateDeductionResult Result
7230 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7231 Specialization, Info)) {
7232 // FIXME: make a note of the failed deduction for diagnostics.
7233 (void)Result;
7234 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007235 }
7236
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007237 // Multiple matches; we can't resolve to a single declaration.
7238 if (Matched)
7239 return 0;
7240
7241 Matched = Specialization;
7242 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007243
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007244 return Matched;
7245}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007246
Douglas Gregorcabea402009-09-22 15:41:20 +00007247/// \brief Add a single candidate to the overload set.
7248static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00007249 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00007250 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007251 Expr **Args, unsigned NumArgs,
7252 OverloadCandidateSet &CandidateSet,
7253 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00007254 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00007255 if (isa<UsingShadowDecl>(Callee))
7256 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7257
Douglas Gregorcabea402009-09-22 15:41:20 +00007258 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00007259 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00007260 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007261 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007262 return;
John McCalld14a8642009-11-21 08:51:07 +00007263 }
7264
7265 if (FunctionTemplateDecl *FuncTemplate
7266 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00007267 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7268 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007269 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00007270 return;
7271 }
7272
7273 assert(false && "unhandled case in overloaded call candidate");
7274
7275 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00007276}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007277
Douglas Gregorcabea402009-09-22 15:41:20 +00007278/// \brief Add the overload candidates named by callee and/or found by argument
7279/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00007280void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00007281 Expr **Args, unsigned NumArgs,
7282 OverloadCandidateSet &CandidateSet,
7283 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00007284
7285#ifndef NDEBUG
7286 // Verify that ArgumentDependentLookup is consistent with the rules
7287 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00007288 //
Douglas Gregorcabea402009-09-22 15:41:20 +00007289 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7290 // and let Y be the lookup set produced by argument dependent
7291 // lookup (defined as follows). If X contains
7292 //
7293 // -- a declaration of a class member, or
7294 //
7295 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00007296 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00007297 //
7298 // -- a declaration that is neither a function or a function
7299 // template
7300 //
7301 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00007302
John McCall57500772009-12-16 12:17:52 +00007303 if (ULE->requiresADL()) {
7304 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7305 E = ULE->decls_end(); I != E; ++I) {
7306 assert(!(*I)->getDeclContext()->isRecord());
7307 assert(isa<UsingShadowDecl>(*I) ||
7308 !(*I)->getDeclContext()->isFunctionOrMethod());
7309 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00007310 }
7311 }
7312#endif
7313
John McCall57500772009-12-16 12:17:52 +00007314 // It would be nice to avoid this copy.
7315 TemplateArgumentListInfo TABuffer;
7316 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7317 if (ULE->hasExplicitTemplateArgs()) {
7318 ULE->copyTemplateArgumentsInto(TABuffer);
7319 ExplicitTemplateArgs = &TABuffer;
7320 }
7321
7322 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7323 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00007324 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007325 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00007326 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00007327
John McCall57500772009-12-16 12:17:52 +00007328 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00007329 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7330 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007331 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007332 CandidateSet,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007333 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007334}
John McCalld681c392009-12-16 08:11:27 +00007335
7336/// Attempts to recover from a call where no functions were found.
7337///
7338/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00007339static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007340BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00007341 UnresolvedLookupExpr *ULE,
7342 SourceLocation LParenLoc,
7343 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007344 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00007345
7346 CXXScopeSpec SS;
7347 if (ULE->getQualifier()) {
7348 SS.setScopeRep(ULE->getQualifier());
7349 SS.setRange(ULE->getQualifierRange());
7350 }
7351
John McCall57500772009-12-16 12:17:52 +00007352 TemplateArgumentListInfo TABuffer;
7353 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7354 if (ULE->hasExplicitTemplateArgs()) {
7355 ULE->copyTemplateArgumentsInto(TABuffer);
7356 ExplicitTemplateArgs = &TABuffer;
7357 }
7358
John McCalld681c392009-12-16 08:11:27 +00007359 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7360 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00007361 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00007362 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00007363
John McCall57500772009-12-16 12:17:52 +00007364 assert(!R.empty() && "lookup results empty despite recovery");
7365
7366 // Build an implicit member call if appropriate. Just drop the
7367 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00007368 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00007369 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00007370 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7371 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00007372 else if (ExplicitTemplateArgs)
7373 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7374 else
7375 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7376
7377 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007378 return ExprError();
John McCall57500772009-12-16 12:17:52 +00007379
7380 // This shouldn't cause an infinite loop because we're giving it
7381 // an expression with non-empty lookup results, which should never
7382 // end up here.
John McCallb268a282010-08-23 23:25:46 +00007383 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007384 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007385}
Douglas Gregor4038cf42010-06-08 17:35:15 +00007386
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007387/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00007388/// (which eventually refers to the declaration Func) and the call
7389/// arguments Args/NumArgs, attempt to resolve the function call down
7390/// to a specific function. If overload resolution succeeds, returns
7391/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00007392/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007393/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00007394ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007395Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00007396 SourceLocation LParenLoc,
7397 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007398 SourceLocation RParenLoc) {
7399#ifndef NDEBUG
7400 if (ULE->requiresADL()) {
7401 // To do ADL, we must have found an unqualified name.
7402 assert(!ULE->getQualifier() && "qualified name with ADL");
7403
7404 // We don't perform ADL for implicit declarations of builtins.
7405 // Verify that this was correctly set up.
7406 FunctionDecl *F;
7407 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7408 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7409 F->getBuiltinID() && F->isImplicit())
7410 assert(0 && "performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007411
John McCall57500772009-12-16 12:17:52 +00007412 // We don't perform ADL in C.
7413 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7414 }
7415#endif
7416
John McCallbc077cf2010-02-08 23:07:23 +00007417 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007418
John McCall57500772009-12-16 12:17:52 +00007419 // Add the functions denoted by the callee to the set of candidate
7420 // functions, including those from argument-dependent lookup.
7421 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007422
7423 // If we found nothing, try to recover.
7424 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7425 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007426 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007427 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007428 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007429
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007430 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007431 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007432 case OR_Success: {
7433 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00007434 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007435 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7436 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007437 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007438 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
7439 RParenLoc);
John McCall57500772009-12-16 12:17:52 +00007440 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007441
7442 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007443 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007444 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007445 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007446 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007447 break;
7448
7449 case OR_Ambiguous:
7450 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007451 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007452 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007453 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007454
7455 case OR_Deleted:
7456 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7457 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00007458 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00007459 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007460 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007461 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007462 }
7463
Douglas Gregorb412e172010-07-25 18:17:45 +00007464 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007465 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007466}
7467
John McCall4c4c1df2010-01-26 03:27:55 +00007468static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007469 return Functions.size() > 1 ||
7470 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7471}
7472
Douglas Gregor084d8552009-03-13 23:49:33 +00007473/// \brief Create a unary operation that may resolve to an overloaded
7474/// operator.
7475///
7476/// \param OpLoc The location of the operator itself (e.g., '*').
7477///
7478/// \param OpcIn The UnaryOperator::Opcode that describes this
7479/// operator.
7480///
7481/// \param Functions The set of non-member functions that will be
7482/// considered by overload resolution. The caller needs to build this
7483/// set based on the context using, e.g.,
7484/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7485/// set should not contain any member functions; those will be added
7486/// by CreateOverloadedUnaryOp().
7487///
7488/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007489ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007490Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7491 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007492 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007493 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007494
7495 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7496 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7497 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007498 // TODO: provide better source location info.
7499 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007500
John McCalle26a8722010-12-04 08:14:53 +00007501 if (Input->getObjectKind() == OK_ObjCProperty)
7502 ConvertPropertyForRValue(Input);
7503
Douglas Gregor084d8552009-03-13 23:49:33 +00007504 Expr *Args[2] = { Input, 0 };
7505 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007506
Douglas Gregor084d8552009-03-13 23:49:33 +00007507 // For post-increment and post-decrement, add the implicit '0' as
7508 // the second argument, so that we know this is a post-increment or
7509 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007510 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007511 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007512 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7513 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007514 NumArgs = 2;
7515 }
7516
7517 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007518 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007519 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007520 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00007521 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007522 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00007523 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007524
John McCall58cc69d2010-01-27 01:50:18 +00007525 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007526 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007527 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007528 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007529 /*ADL*/ true, IsOverloaded(Fns),
7530 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007531 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7532 &Args[0], NumArgs,
7533 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007534 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00007535 OpLoc));
7536 }
7537
7538 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007539 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007540
7541 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007542 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007543
7544 // Add operator candidates that are member functions.
7545 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7546
John McCall4c4c1df2010-01-26 03:27:55 +00007547 // Add candidates from ADL.
7548 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007549 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007550 /*ExplicitTemplateArgs*/ 0,
7551 CandidateSet);
7552
Douglas Gregor084d8552009-03-13 23:49:33 +00007553 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007554 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007555
7556 // Perform overload resolution.
7557 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007558 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007559 case OR_Success: {
7560 // We found a built-in operator or an overloaded operator.
7561 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007562
Douglas Gregor084d8552009-03-13 23:49:33 +00007563 if (FnDecl) {
7564 // We matched an overloaded operator. Build a call to that
7565 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007566
Douglas Gregor084d8552009-03-13 23:49:33 +00007567 // Convert the arguments.
7568 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007569 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007570
John McCall16df1e52010-03-30 21:47:33 +00007571 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7572 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007573 return ExprError();
7574 } else {
7575 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007576 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007577 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007578 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007579 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007580 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007581 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007582 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007583 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007584 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007585 }
7586
John McCall4fa0d5f2010-05-06 18:15:07 +00007587 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7588
John McCall7decc9e2010-11-18 06:31:45 +00007589 // Determine the result type.
7590 QualType ResultTy = FnDecl->getResultType();
7591 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7592 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00007593
Douglas Gregor084d8552009-03-13 23:49:33 +00007594 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007595 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007596
Eli Friedman030eee42009-11-18 03:58:17 +00007597 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007598 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007599 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007600 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007601
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007602 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007603 FnDecl))
7604 return ExprError();
7605
John McCallb268a282010-08-23 23:25:46 +00007606 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007607 } else {
7608 // We matched a built-in operator. Convert the arguments, then
7609 // break out so that we will build the appropriate built-in
7610 // operator node.
7611 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007612 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007613 return ExprError();
7614
7615 break;
7616 }
7617 }
7618
7619 case OR_No_Viable_Function:
7620 // No viable function; fall through to handling this as a
7621 // built-in operator, which will produce an error message for us.
7622 break;
7623
7624 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007625 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregor084d8552009-03-13 23:49:33 +00007626 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007627 << Input->getType()
Douglas Gregor084d8552009-03-13 23:49:33 +00007628 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007629 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7630 Args, NumArgs,
7631 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007632 return ExprError();
7633
7634 case OR_Deleted:
7635 Diag(OpLoc, diag::err_ovl_deleted_oper)
7636 << Best->Function->isDeleted()
7637 << UnaryOperator::getOpcodeStr(Opc)
7638 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007639 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007640 return ExprError();
7641 }
7642
7643 // Either we found no viable overloaded operator or we matched a
7644 // built-in operator. In either case, fall through to trying to
7645 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007646 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007647}
7648
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007649/// \brief Create a binary operation that may resolve to an overloaded
7650/// operator.
7651///
7652/// \param OpLoc The location of the operator itself (e.g., '+').
7653///
7654/// \param OpcIn The BinaryOperator::Opcode that describes this
7655/// operator.
7656///
7657/// \param Functions The set of non-member functions that will be
7658/// considered by overload resolution. The caller needs to build this
7659/// set based on the context using, e.g.,
7660/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7661/// set should not contain any member functions; those will be added
7662/// by CreateOverloadedBinOp().
7663///
7664/// \param LHS Left-hand argument.
7665/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00007666ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007667Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007668 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00007669 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007670 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007671 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00007672 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007673
7674 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7675 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7676 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7677
7678 // If either side is type-dependent, create an appropriate dependent
7679 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00007680 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00007681 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007682 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00007683 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00007684 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00007685 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00007686 Context.DependentTy,
7687 VK_RValue, OK_Ordinary,
7688 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007689
Douglas Gregor5287f092009-11-05 00:51:44 +00007690 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7691 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007692 VK_LValue,
7693 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00007694 Context.DependentTy,
7695 Context.DependentTy,
7696 OpLoc));
7697 }
John McCall4c4c1df2010-01-26 03:27:55 +00007698
7699 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00007700 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007701 // TODO: provide better source location info in DNLoc component.
7702 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00007703 UnresolvedLookupExpr *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007704 = UnresolvedLookupExpr::Create(Context, NamingClass, 0, SourceRange(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00007705 OpNameInfo, /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007706 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007707 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00007708 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007709 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007710 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007711 OpLoc));
7712 }
7713
John McCalle26a8722010-12-04 08:14:53 +00007714 // Always do property rvalue conversions on the RHS.
7715 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7716 ConvertPropertyForRValue(Args[1]);
7717
7718 // The LHS is more complicated.
7719 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
7720
7721 // There's a tension for assignment operators between primitive
7722 // property assignment and the overloaded operators.
7723 if (BinaryOperator::isAssignmentOp(Opc)) {
7724 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7725
7726 // Is the property "logically" settable?
7727 bool Settable = (PRE->isExplicitProperty() ||
7728 PRE->getImplicitPropertySetter());
7729
7730 // To avoid gratuitously inventing semantics, use the primitive
7731 // unless it isn't. Thoughts in case we ever really care:
7732 // - If the property isn't logically settable, we have to
7733 // load and hope.
7734 // - If the property is settable and this is simple assignment,
7735 // we really should use the primitive.
7736 // - If the property is settable, then we could try overloading
7737 // on a generic lvalue of the appropriate type; if it works
7738 // out to a builtin candidate, we would do that same operation
7739 // on the property, and otherwise just error.
7740 if (Settable)
7741 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7742 }
7743
7744 ConvertPropertyForRValue(Args[0]);
7745 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007746
Sebastian Redl6a96bf72009-11-18 23:10:33 +00007747 // If this is the assignment operator, we only perform overload resolution
7748 // if the left-hand side is a class or enumeration type. This is actually
7749 // a hack. The standard requires that we do overload resolution between the
7750 // various built-in candidates, but as DR507 points out, this can lead to
7751 // problems. So we do it this way, which pretty much follows what GCC does.
7752 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00007753 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00007754 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007755
John McCalle26a8722010-12-04 08:14:53 +00007756 // If this is the .* operator, which is not overloadable, just
7757 // create a built-in binary operator.
7758 if (Opc == BO_PtrMemD)
7759 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7760
Douglas Gregor084d8552009-03-13 23:49:33 +00007761 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007762 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007763
7764 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007765 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007766
7767 // Add operator candidates that are member functions.
7768 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7769
John McCall4c4c1df2010-01-26 03:27:55 +00007770 // Add candidates from ADL.
7771 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7772 Args, 2,
7773 /*ExplicitTemplateArgs*/ 0,
7774 CandidateSet);
7775
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007776 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007777 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007778
7779 // Perform overload resolution.
7780 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007781 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00007782 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007783 // We found a built-in operator or an overloaded operator.
7784 FunctionDecl *FnDecl = Best->Function;
7785
7786 if (FnDecl) {
7787 // We matched an overloaded operator. Build a call to that
7788 // operator.
7789
7790 // Convert the arguments.
7791 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00007792 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00007793 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007794
Chandler Carruth8e543b32010-12-12 08:17:55 +00007795 ExprResult Arg1 =
7796 PerformCopyInitialization(
7797 InitializedEntity::InitializeParameter(Context,
7798 FnDecl->getParamDecl(0)),
7799 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007800 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007801 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007802
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007803 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007804 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007805 return ExprError();
7806
7807 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007808 } else {
7809 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00007810 ExprResult Arg0 = PerformCopyInitialization(
7811 InitializedEntity::InitializeParameter(Context,
7812 FnDecl->getParamDecl(0)),
7813 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007814 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007815 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007816
Chandler Carruth8e543b32010-12-12 08:17:55 +00007817 ExprResult Arg1 =
7818 PerformCopyInitialization(
7819 InitializedEntity::InitializeParameter(Context,
7820 FnDecl->getParamDecl(1)),
7821 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007822 if (Arg1.isInvalid())
7823 return ExprError();
7824 Args[0] = LHS = Arg0.takeAs<Expr>();
7825 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007826 }
7827
John McCall4fa0d5f2010-05-06 18:15:07 +00007828 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7829
John McCall7decc9e2010-11-18 06:31:45 +00007830 // Determine the result type.
7831 QualType ResultTy = FnDecl->getResultType();
7832 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7833 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007834
7835 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007836 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007837
John McCallb268a282010-08-23 23:25:46 +00007838 CXXOperatorCallExpr *TheCall =
7839 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007840 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007841
7842 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007843 FnDecl))
7844 return ExprError();
7845
John McCallb268a282010-08-23 23:25:46 +00007846 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007847 } else {
7848 // We matched a built-in operator. Convert the arguments, then
7849 // break out so that we will build the appropriate built-in
7850 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00007851 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007852 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00007853 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007854 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007855 return ExprError();
7856
7857 break;
7858 }
7859 }
7860
Douglas Gregor66950a32009-09-30 21:46:01 +00007861 case OR_No_Viable_Function: {
7862 // C++ [over.match.oper]p9:
7863 // If the operator is the operator , [...] and there are no
7864 // viable functions, then the operator is assumed to be the
7865 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00007866 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00007867 break;
7868
Chandler Carruth8e543b32010-12-12 08:17:55 +00007869 // For class as left operand for assignment or compound assigment
7870 // operator do not fall through to handling in built-in, but report that
7871 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007872 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007873 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00007874 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007875 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7876 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007877 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007878 } else {
7879 // No viable function; try to create a built-in operation, which will
7880 // produce an error. Then, show the non-viable candidates.
7881 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007882 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007883 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00007884 "C++ binary operator overloading is missing candidates!");
7885 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00007886 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7887 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007888 return move(Result);
7889 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007890
7891 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007892 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007893 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007894 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00007895 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007896 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7897 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007898 return ExprError();
7899
7900 case OR_Deleted:
7901 Diag(OpLoc, diag::err_ovl_deleted_oper)
7902 << Best->Function->isDeleted()
7903 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007904 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007905 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007906 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007907 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007908
Douglas Gregor66950a32009-09-30 21:46:01 +00007909 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007910 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007911}
7912
John McCalldadc5752010-08-24 06:29:42 +00007913ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007914Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7915 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007916 Expr *Base, Expr *Idx) {
7917 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007918 DeclarationName OpName =
7919 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7920
7921 // If either side is type-dependent, create an appropriate dependent
7922 // expression.
7923 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7924
John McCall58cc69d2010-01-27 01:50:18 +00007925 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007926 // CHECKME: no 'operator' keyword?
7927 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7928 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007929 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007930 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007931 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007932 /*ADL*/ true, /*Overloaded*/ false,
7933 UnresolvedSetIterator(),
7934 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007935 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007936
Sebastian Redladba46e2009-10-29 20:17:01 +00007937 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7938 Args, 2,
7939 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007940 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00007941 RLoc));
7942 }
7943
John McCalle26a8722010-12-04 08:14:53 +00007944 if (Args[0]->getObjectKind() == OK_ObjCProperty)
7945 ConvertPropertyForRValue(Args[0]);
7946 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7947 ConvertPropertyForRValue(Args[1]);
7948
Sebastian Redladba46e2009-10-29 20:17:01 +00007949 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007950 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007951
7952 // Subscript can only be overloaded as a member function.
7953
7954 // Add operator candidates that are member functions.
7955 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7956
7957 // Add builtin operator candidates.
7958 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7959
7960 // Perform overload resolution.
7961 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007962 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00007963 case OR_Success: {
7964 // We found a built-in operator or an overloaded operator.
7965 FunctionDecl *FnDecl = Best->Function;
7966
7967 if (FnDecl) {
7968 // We matched an overloaded operator. Build a call to that
7969 // operator.
7970
John McCalla0296f72010-03-19 07:35:19 +00007971 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007972 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007973
Sebastian Redladba46e2009-10-29 20:17:01 +00007974 // Convert the arguments.
7975 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007976 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007977 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007978 return ExprError();
7979
Anders Carlssona68e51e2010-01-29 18:37:50 +00007980 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007981 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007982 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007983 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00007984 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007985 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00007986 Owned(Args[1]));
7987 if (InputInit.isInvalid())
7988 return ExprError();
7989
7990 Args[1] = InputInit.takeAs<Expr>();
7991
Sebastian Redladba46e2009-10-29 20:17:01 +00007992 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00007993 QualType ResultTy = FnDecl->getResultType();
7994 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7995 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007996
7997 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007998 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007999
John McCallb268a282010-08-23 23:25:46 +00008000 CXXOperatorCallExpr *TheCall =
8001 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
8002 FnExpr, Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00008003 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008004
John McCallb268a282010-08-23 23:25:46 +00008005 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00008006 FnDecl))
8007 return ExprError();
8008
John McCallb268a282010-08-23 23:25:46 +00008009 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00008010 } else {
8011 // We matched a built-in operator. Convert the arguments, then
8012 // break out so that we will build the appropriate built-in
8013 // operator node.
8014 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008015 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00008016 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008017 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00008018 return ExprError();
8019
8020 break;
8021 }
8022 }
8023
8024 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00008025 if (CandidateSet.empty())
8026 Diag(LLoc, diag::err_ovl_no_oper)
8027 << Args[0]->getType() << /*subscript*/ 0
8028 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8029 else
8030 Diag(LLoc, diag::err_ovl_no_viable_subscript)
8031 << Args[0]->getType()
8032 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008033 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8034 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00008035 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00008036 }
8037
8038 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008039 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008040 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00008041 << Args[0]->getType() << Args[1]->getType()
8042 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008043 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8044 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008045 return ExprError();
8046
8047 case OR_Deleted:
8048 Diag(LLoc, diag::err_ovl_deleted_oper)
8049 << Best->Function->isDeleted() << "[]"
8050 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008051 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8052 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008053 return ExprError();
8054 }
8055
8056 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00008057 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008058}
8059
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008060/// BuildCallToMemberFunction - Build a call to a member
8061/// function. MemExpr is the expression that refers to the member
8062/// function (and includes the object parameter), Args/NumArgs are the
8063/// arguments to the function call (not including the object
8064/// parameter). The caller needs to validate that the member
8065/// expression refers to a member function or an overloaded member
8066/// function.
John McCalldadc5752010-08-24 06:29:42 +00008067ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008068Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8069 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008070 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008071 // Dig out the member expression. This holds both the object
8072 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00008073 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008074
John McCall10eae182009-11-30 22:42:35 +00008075 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008076 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00008077 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008078 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00008079 if (isa<MemberExpr>(NakedMemExpr)) {
8080 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00008081 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00008082 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008083 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00008084 } else {
8085 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008086 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008087
John McCall6e9f8f62009-12-03 04:06:58 +00008088 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00008089 Expr::Classification ObjectClassification
8090 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
8091 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00008092
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008093 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00008094 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00008095
John McCall2d74de92009-12-01 22:10:20 +00008096 // FIXME: avoid copy.
8097 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8098 if (UnresExpr->hasExplicitTemplateArgs()) {
8099 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8100 TemplateArgs = &TemplateArgsBuffer;
8101 }
8102
John McCall10eae182009-11-30 22:42:35 +00008103 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
8104 E = UnresExpr->decls_end(); I != E; ++I) {
8105
John McCall6e9f8f62009-12-03 04:06:58 +00008106 NamedDecl *Func = *I;
8107 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
8108 if (isa<UsingShadowDecl>(Func))
8109 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
8110
Douglas Gregor02824322011-01-26 19:30:28 +00008111
Francois Pichet64225792011-01-18 05:04:39 +00008112 // Microsoft supports direct constructor calls.
8113 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
8114 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
8115 CandidateSet);
8116 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00008117 // If explicit template arguments were provided, we can't call a
8118 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00008119 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00008120 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008121
John McCalla0296f72010-03-19 07:35:19 +00008122 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008123 ObjectClassification,
8124 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00008125 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008126 } else {
John McCall10eae182009-11-30 22:42:35 +00008127 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00008128 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008129 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00008130 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008131 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008132 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008133 }
Mike Stump11289f42009-09-09 15:08:12 +00008134
John McCall10eae182009-11-30 22:42:35 +00008135 DeclarationName DeclName = UnresExpr->getMemberName();
8136
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008137 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008138 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00008139 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008140 case OR_Success:
8141 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008142 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00008143 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008144 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008145 break;
8146
8147 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00008148 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008149 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008150 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008151 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008152 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008153 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008154
8155 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00008156 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008157 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008158 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008159 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008160 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008161
8162 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00008163 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00008164 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00008165 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008166 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008167 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008168 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008169 }
8170
John McCall16df1e52010-03-30 21:47:33 +00008171 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00008172
John McCall2d74de92009-12-01 22:10:20 +00008173 // If overload resolution picked a static member, build a
8174 // non-member call based on that function.
8175 if (Method->isStatic()) {
8176 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8177 Args, NumArgs, RParenLoc);
8178 }
8179
John McCall10eae182009-11-30 22:42:35 +00008180 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008181 }
8182
John McCall7decc9e2010-11-18 06:31:45 +00008183 QualType ResultType = Method->getResultType();
8184 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8185 ResultType = ResultType.getNonLValueExprType(Context);
8186
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008187 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008188 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00008189 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008190 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008191
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008192 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008193 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00008194 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00008195 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008196
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008197 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00008198 // We only need to do this if there was actually an overload; otherwise
8199 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00008200 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00008201 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00008202 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
8203 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00008204 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008205 MemExpr->setBase(ObjectArg);
8206
8207 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00008208 const FunctionProtoType *Proto =
8209 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00008210 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008211 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00008212 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008213
John McCallb268a282010-08-23 23:25:46 +00008214 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00008215 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00008216
John McCallb268a282010-08-23 23:25:46 +00008217 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008218}
8219
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008220/// BuildCallToObjectOfClassType - Build a call to an object of class
8221/// type (C++ [over.call.object]), which can end up invoking an
8222/// overloaded function call operator (@c operator()) or performing a
8223/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00008224ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008225Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00008226 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008227 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008228 SourceLocation RParenLoc) {
John McCalle26a8722010-12-04 08:14:53 +00008229 if (Object->getObjectKind() == OK_ObjCProperty)
8230 ConvertPropertyForRValue(Object);
8231
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008232 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008233 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00008234
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008235 // C++ [over.call.object]p1:
8236 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00008237 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008238 // candidate functions includes at least the function call
8239 // operators of T. The function call operators of T are obtained by
8240 // ordinary lookup of the name operator() in the context of
8241 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00008242 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00008243 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008244
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008245 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00008246 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008247 << Object->getSourceRange()))
8248 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008249
John McCall27b18f82009-11-17 02:14:36 +00008250 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8251 LookupQualifiedName(R, Record->getDecl());
8252 R.suppressDiagnostics();
8253
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008254 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00008255 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008256 AddMethodCandidate(Oper.getPair(), Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00008257 Object->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00008258 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00008259 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008260
Douglas Gregorab7897a2008-11-19 22:57:39 +00008261 // C++ [over.call.object]p2:
8262 // In addition, for each conversion function declared in T of the
8263 // form
8264 //
8265 // operator conversion-type-id () cv-qualifier;
8266 //
8267 // where cv-qualifier is the same cv-qualification as, or a
8268 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00008269 // denotes the type "pointer to function of (P1,...,Pn) returning
8270 // R", or the type "reference to pointer to function of
8271 // (P1,...,Pn) returning R", or the type "reference to function
8272 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00008273 // is also considered as a candidate function. Similarly,
8274 // surrogate call functions are added to the set of candidate
8275 // functions for each conversion function declared in an
8276 // accessible base class provided the function is not hidden
8277 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00008278 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00008279 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00008280 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00008281 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00008282 NamedDecl *D = *I;
8283 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8284 if (isa<UsingShadowDecl>(D))
8285 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008286
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008287 // Skip over templated conversion functions; they aren't
8288 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00008289 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008290 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00008291
John McCall6e9f8f62009-12-03 04:06:58 +00008292 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00008293
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008294 // Strip the reference type (if any) and then the pointer type (if
8295 // any) to get down to what might be a function type.
8296 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8297 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8298 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00008299
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008300 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00008301 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00008302 Object, Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008303 }
Mike Stump11289f42009-09-09 15:08:12 +00008304
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008305 // Perform overload resolution.
8306 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008307 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
8308 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008309 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00008310 // Overload resolution succeeded; we'll build the appropriate call
8311 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008312 break;
8313
8314 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00008315 if (CandidateSet.empty())
8316 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8317 << Object->getType() << /*call*/ 1
8318 << Object->getSourceRange();
8319 else
8320 Diag(Object->getSourceRange().getBegin(),
8321 diag::err_ovl_no_viable_object_call)
8322 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008323 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008324 break;
8325
8326 case OR_Ambiguous:
8327 Diag(Object->getSourceRange().getBegin(),
8328 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008329 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008330 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008331 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008332
8333 case OR_Deleted:
8334 Diag(Object->getSourceRange().getBegin(),
8335 diag::err_ovl_deleted_object_call)
8336 << Best->Function->isDeleted()
8337 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008338 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008339 break;
Mike Stump11289f42009-09-09 15:08:12 +00008340 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008341
Douglas Gregorb412e172010-07-25 18:17:45 +00008342 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008343 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008344
Douglas Gregorab7897a2008-11-19 22:57:39 +00008345 if (Best->Function == 0) {
8346 // Since there is no function declaration, this is one of the
8347 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00008348 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00008349 = cast<CXXConversionDecl>(
8350 Best->Conversions[0].UserDefined.ConversionFunction);
8351
John McCalla0296f72010-03-19 07:35:19 +00008352 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008353 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008354
Douglas Gregorab7897a2008-11-19 22:57:39 +00008355 // We selected one of the surrogate functions that converts the
8356 // object parameter to a function pointer. Perform the conversion
8357 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008358
Fariborz Jahanian774cf792009-09-28 18:35:46 +00008359 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00008360 // and then call it.
Douglas Gregor668443e2011-01-20 00:18:04 +00008361 ExprResult Call = BuildCXXMemberCallExpr(Object, Best->FoundDecl, Conv);
8362 if (Call.isInvalid())
8363 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008364
Douglas Gregor668443e2011-01-20 00:18:04 +00008365 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008366 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008367 }
8368
John McCalla0296f72010-03-19 07:35:19 +00008369 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008370 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008371
Douglas Gregorab7897a2008-11-19 22:57:39 +00008372 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8373 // that calls this method, using Object for the implicit object
8374 // parameter and passing along the remaining arguments.
8375 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008376 const FunctionProtoType *Proto =
8377 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008378
8379 unsigned NumArgsInProto = Proto->getNumArgs();
8380 unsigned NumArgsToCheck = NumArgs;
8381
8382 // Build the full argument list for the method call (the
8383 // implicit object parameter is placed at the beginning of the
8384 // list).
8385 Expr **MethodArgs;
8386 if (NumArgs < NumArgsInProto) {
8387 NumArgsToCheck = NumArgsInProto;
8388 MethodArgs = new Expr*[NumArgsInProto + 1];
8389 } else {
8390 MethodArgs = new Expr*[NumArgs + 1];
8391 }
8392 MethodArgs[0] = Object;
8393 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8394 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00008395
John McCall7decc9e2010-11-18 06:31:45 +00008396 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008397
8398 // Once we've built TheCall, all of the expressions are properly
8399 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00008400 QualType ResultTy = Method->getResultType();
8401 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8402 ResultTy = ResultTy.getNonLValueExprType(Context);
8403
John McCallb268a282010-08-23 23:25:46 +00008404 CXXOperatorCallExpr *TheCall =
8405 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
8406 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00008407 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008408 delete [] MethodArgs;
8409
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008410 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00008411 Method))
8412 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008413
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008414 // We may have default arguments. If so, we need to allocate more
8415 // slots in the call for them.
8416 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00008417 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008418 else if (NumArgs > NumArgsInProto)
8419 NumArgsToCheck = NumArgsInProto;
8420
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008421 bool IsError = false;
8422
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008423 // Initialize the implicit object parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008424 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008425 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008426 TheCall->setArg(0, Object);
8427
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008428
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008429 // Check the argument types.
8430 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008431 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008432 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008433 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00008434
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008435 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008436
John McCalldadc5752010-08-24 06:29:42 +00008437 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008438 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008439 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008440 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00008441 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008442
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008443 IsError |= InputInit.isInvalid();
8444 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008445 } else {
John McCalldadc5752010-08-24 06:29:42 +00008446 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008447 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8448 if (DefArg.isInvalid()) {
8449 IsError = true;
8450 break;
8451 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008452
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008453 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008454 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008455
8456 TheCall->setArg(i + 1, Arg);
8457 }
8458
8459 // If this is a variadic call, handle args passed through "...".
8460 if (Proto->isVariadic()) {
8461 // Promote the arguments (C99 6.5.2.2p7).
8462 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8463 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00008464 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008465 TheCall->setArg(i + 1, Arg);
8466 }
8467 }
8468
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008469 if (IsError) return true;
8470
John McCallb268a282010-08-23 23:25:46 +00008471 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00008472 return true;
8473
John McCalle172be52010-08-24 06:09:16 +00008474 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008475}
8476
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008477/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00008478/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008479/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00008480ExprResult
John McCallb268a282010-08-23 23:25:46 +00008481Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008482 assert(Base->getType()->isRecordType() &&
8483 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00008484
John McCalle26a8722010-12-04 08:14:53 +00008485 if (Base->getObjectKind() == OK_ObjCProperty)
8486 ConvertPropertyForRValue(Base);
8487
John McCallbc077cf2010-02-08 23:07:23 +00008488 SourceLocation Loc = Base->getExprLoc();
8489
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008490 // C++ [over.ref]p1:
8491 //
8492 // [...] An expression x->m is interpreted as (x.operator->())->m
8493 // for a class object x of type T if T::operator->() exists and if
8494 // the operator is selected as the best match function by the
8495 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00008496 DeclarationName OpName =
8497 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00008498 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008499 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00008500
John McCallbc077cf2010-02-08 23:07:23 +00008501 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00008502 PDiag(diag::err_typecheck_incomplete_tag)
8503 << Base->getSourceRange()))
8504 return ExprError();
8505
John McCall27b18f82009-11-17 02:14:36 +00008506 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8507 LookupQualifiedName(R, BaseRecord->getDecl());
8508 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00008509
8510 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00008511 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00008512 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
8513 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00008514 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008515
8516 // Perform overload resolution.
8517 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008518 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008519 case OR_Success:
8520 // Overload resolution succeeded; we'll build the call below.
8521 break;
8522
8523 case OR_No_Viable_Function:
8524 if (CandidateSet.empty())
8525 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008526 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008527 else
8528 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008529 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008530 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008531 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008532
8533 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008534 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8535 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008536 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008537 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008538
8539 case OR_Deleted:
8540 Diag(OpLoc, diag::err_ovl_deleted_oper)
8541 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00008542 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008543 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008544 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008545 }
8546
John McCalla0296f72010-03-19 07:35:19 +00008547 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008548 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00008549
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008550 // Convert the object parameter.
8551 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008552 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8553 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00008554 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00008555
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008556 // Build the operator call.
John McCall7decc9e2010-11-18 06:31:45 +00008557 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008558
John McCall7decc9e2010-11-18 06:31:45 +00008559 QualType ResultTy = Method->getResultType();
8560 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8561 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00008562 CXXOperatorCallExpr *TheCall =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008563 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008564 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008565
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008566 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008567 Method))
8568 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008569 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008570}
8571
Douglas Gregorcd695e52008-11-10 20:40:00 +00008572/// FixOverloadedFunctionReference - E is an expression that refers to
8573/// a C++ overloaded function (possibly with some parentheses and
8574/// perhaps a '&' around it). We have resolved the overloaded function
8575/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008576/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00008577Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00008578 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00008579 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008580 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8581 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008582 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008583 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008584
Douglas Gregor51c538b2009-11-20 19:42:02 +00008585 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008586 }
8587
Douglas Gregor51c538b2009-11-20 19:42:02 +00008588 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008589 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8590 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008591 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008592 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00008593 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00008594 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00008595 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008596 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008597
8598 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +00008599 ICE->getCastKind(),
8600 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00008601 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008602 }
8603
Douglas Gregor51c538b2009-11-20 19:42:02 +00008604 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00008605 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008606 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008607 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8608 if (Method->isStatic()) {
8609 // Do nothing: static member functions aren't any different
8610 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008611 } else {
John McCalle66edc12009-11-24 19:00:30 +00008612 // Fix the sub expression, which really has to be an
8613 // UnresolvedLookupExpr holding an overloaded member function
8614 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008615 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8616 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008617 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008618 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008619
John McCalld14a8642009-11-21 08:51:07 +00008620 assert(isa<DeclRefExpr>(SubExpr)
8621 && "fixed to something other than a decl ref");
8622 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8623 && "fixed to a member ref with no nested name qualifier");
8624
8625 // We have taken the address of a pointer to member
8626 // function. Perform the computation here so that we get the
8627 // appropriate pointer to member type.
8628 QualType ClassType
8629 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8630 QualType MemPtrType
8631 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8632
John McCall7decc9e2010-11-18 06:31:45 +00008633 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8634 VK_RValue, OK_Ordinary,
8635 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008636 }
8637 }
John McCall16df1e52010-03-30 21:47:33 +00008638 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8639 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008640 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008641 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008642
John McCalle3027922010-08-25 11:45:40 +00008643 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008644 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00008645 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008646 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008647 }
John McCalld14a8642009-11-21 08:51:07 +00008648
8649 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00008650 // FIXME: avoid copy.
8651 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00008652 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00008653 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8654 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00008655 }
8656
John McCalld14a8642009-11-21 08:51:07 +00008657 return DeclRefExpr::Create(Context,
8658 ULE->getQualifier(),
8659 ULE->getQualifierRange(),
8660 Fn,
8661 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00008662 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008663 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008664 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00008665 }
8666
John McCall10eae182009-11-30 22:42:35 +00008667 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00008668 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00008669 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8670 if (MemExpr->hasExplicitTemplateArgs()) {
8671 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8672 TemplateArgs = &TemplateArgsBuffer;
8673 }
John McCall6b51f282009-11-23 01:53:49 +00008674
John McCall2d74de92009-12-01 22:10:20 +00008675 Expr *Base;
8676
John McCall7decc9e2010-11-18 06:31:45 +00008677 // If we're filling in a static method where we used to have an
8678 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00008679 if (MemExpr->isImplicitAccess()) {
8680 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8681 return DeclRefExpr::Create(Context,
8682 MemExpr->getQualifier(),
8683 MemExpr->getQualifierRange(),
8684 Fn,
8685 MemExpr->getMemberLoc(),
8686 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008687 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008688 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00008689 } else {
8690 SourceLocation Loc = MemExpr->getMemberLoc();
8691 if (MemExpr->getQualifier())
8692 Loc = MemExpr->getQualifierRange().getBegin();
8693 Base = new (Context) CXXThisExpr(Loc,
8694 MemExpr->getBaseType(),
8695 /*isImplicit=*/true);
8696 }
John McCall2d74de92009-12-01 22:10:20 +00008697 } else
John McCallc3007a22010-10-26 07:05:15 +00008698 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00008699
8700 return MemberExpr::Create(Context, Base,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008701 MemExpr->isArrow(),
8702 MemExpr->getQualifier(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008703 MemExpr->getQualifierRange(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008704 Fn,
John McCall16df1e52010-03-30 21:47:33 +00008705 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008706 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00008707 TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008708 Fn->getType(),
8709 cast<CXXMethodDecl>(Fn)->isStatic()
8710 ? VK_LValue : VK_RValue,
8711 OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008713
John McCallc3007a22010-10-26 07:05:15 +00008714 llvm_unreachable("Invalid reference to overloaded function");
8715 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008716}
8717
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008718ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +00008719 DeclAccessPair Found,
8720 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00008721 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008722}
8723
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008724} // end namespace clang