blob: 8d03285ee4436b42f3d8c174365532c035d10af0 [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036
John McCall7decc9e2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
39static Expr *
40CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41 SourceLocation Loc = SourceLocation()) {
42 Expr *E = new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc);
43 S.DefaultFunctionArrayConversion(E);
44 return E;
45}
46
John McCall5c32be02010-08-24 20:38:10 +000047static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
48 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000049 StandardConversionSequence &SCS,
50 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000051static OverloadingResult
52IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
53 UserDefinedConversionSequence& User,
54 OverloadCandidateSet& Conversions,
55 bool AllowExplicit);
56
57
58static ImplicitConversionSequence::CompareKind
59CompareStandardConversionSequences(Sema &S,
60 const StandardConversionSequence& SCS1,
61 const StandardConversionSequence& SCS2);
62
63static ImplicitConversionSequence::CompareKind
64CompareQualificationConversions(Sema &S,
65 const StandardConversionSequence& SCS1,
66 const StandardConversionSequence& SCS2);
67
68static ImplicitConversionSequence::CompareKind
69CompareDerivedToBaseConversions(Sema &S,
70 const StandardConversionSequence& SCS1,
71 const StandardConversionSequence& SCS2);
72
73
74
Douglas Gregor5251f1b2008-10-21 16:13:35 +000075/// GetConversionCategory - Retrieve the implicit conversion
76/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000077ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000078GetConversionCategory(ImplicitConversionKind Kind) {
79 static const ImplicitConversionCategory
80 Category[(int)ICK_Num_Conversion_Kinds] = {
81 ICC_Identity,
82 ICC_Lvalue_Transformation,
83 ICC_Lvalue_Transformation,
84 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000085 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000086 ICC_Qualification_Adjustment,
87 ICC_Promotion,
88 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000089 ICC_Promotion,
90 ICC_Conversion,
91 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092 ICC_Conversion,
93 ICC_Conversion,
94 ICC_Conversion,
95 ICC_Conversion,
96 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000097 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000098 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000099 ICC_Conversion,
100 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000101 ICC_Conversion
102 };
103 return Category[(int)Kind];
104}
105
106/// GetConversionRank - Retrieve the implicit conversion rank
107/// corresponding to the given implicit conversion kind.
108ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
109 static const ImplicitConversionRank
110 Rank[(int)ICK_Num_Conversion_Kinds] = {
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
115 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000116 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000117 ICR_Promotion,
118 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000119 ICR_Promotion,
120 ICR_Conversion,
121 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
126 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000127 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000128 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000129 ICR_Conversion,
130 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000131 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000132 };
133 return Rank[(int)Kind];
134}
135
136/// GetImplicitConversionName - Return the name of this kind of
137/// implicit conversion.
138const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000139 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000140 "No conversion",
141 "Lvalue-to-rvalue",
142 "Array-to-pointer",
143 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000144 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000145 "Qualification",
146 "Integral promotion",
147 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000148 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000149 "Integral conversion",
150 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000151 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000152 "Floating-integral conversion",
153 "Pointer conversion",
154 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000155 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000156 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000157 "Derived-to-base conversion",
158 "Vector conversion",
159 "Vector splat",
160 "Complex-real conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000161 };
162 return Name[Kind];
163}
164
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000165/// StandardConversionSequence - Set the standard conversion
166/// sequence to the identity conversion.
167void StandardConversionSequence::setAsIdentityConversion() {
168 First = ICK_Identity;
169 Second = ICK_Identity;
170 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000171 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000172 ReferenceBinding = false;
173 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000174 IsLvalueReference = true;
175 BindsToFunctionLvalue = false;
176 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000177 BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000178 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000179}
180
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000181/// getRank - Retrieve the rank of this standard conversion sequence
182/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
183/// implicit conversions.
184ImplicitConversionRank StandardConversionSequence::getRank() const {
185 ImplicitConversionRank Rank = ICR_Exact_Match;
186 if (GetConversionRank(First) > Rank)
187 Rank = GetConversionRank(First);
188 if (GetConversionRank(Second) > Rank)
189 Rank = GetConversionRank(Second);
190 if (GetConversionRank(Third) > Rank)
191 Rank = GetConversionRank(Third);
192 return Rank;
193}
194
195/// isPointerConversionToBool - Determines whether this conversion is
196/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000197/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000198/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000199bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000200 // Note that FromType has not necessarily been transformed by the
201 // array-to-pointer or function-to-pointer implicit conversions, so
202 // check for their presence as well as checking whether FromType is
203 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000204 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000205 (getFromType()->isPointerType() ||
206 getFromType()->isObjCObjectPointerType() ||
207 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000208 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000209 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
210 return true;
211
212 return false;
213}
214
Douglas Gregor5c407d92008-10-23 00:40:37 +0000215/// isPointerConversionToVoidPointer - Determines whether this
216/// conversion is a conversion of a pointer to a void pointer. This is
217/// used as part of the ranking of standard conversion sequences (C++
218/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000219bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000220StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000221isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000222 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000223 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000224
225 // Note that FromType has not necessarily been transformed by the
226 // array-to-pointer implicit conversion, so check for its presence
227 // and redo the conversion to get a pointer.
228 if (First == ICK_Array_To_Pointer)
229 FromType = Context.getArrayDecayedType(FromType);
230
John McCall75851b12010-10-26 06:40:27 +0000231 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000232 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000233 return ToPtrType->getPointeeType()->isVoidType();
234
235 return false;
236}
237
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000238/// DebugPrint - Print this standard conversion sequence to standard
239/// error. Useful for debugging overloading issues.
240void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000241 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000242 bool PrintedSomething = false;
243 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000244 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000245 PrintedSomething = true;
246 }
247
248 if (Second != ICK_Identity) {
249 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000250 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000251 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000252 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000253
254 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000255 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000256 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000257 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000258 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000259 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000260 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000261 PrintedSomething = true;
262 }
263
264 if (Third != ICK_Identity) {
265 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000266 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000267 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000268 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000269 PrintedSomething = true;
270 }
271
272 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000273 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000274 }
275}
276
277/// DebugPrint - Print this user-defined conversion sequence to standard
278/// error. Useful for debugging overloading issues.
279void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000280 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000281 if (Before.First || Before.Second || Before.Third) {
282 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000283 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000284 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000285 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000286 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000287 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000288 After.DebugPrint();
289 }
290}
291
292/// DebugPrint - Print this implicit conversion sequence to standard
293/// error. Useful for debugging overloading issues.
294void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000295 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000296 switch (ConversionKind) {
297 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000298 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000299 Standard.DebugPrint();
300 break;
301 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000302 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000303 UserDefined.DebugPrint();
304 break;
305 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000306 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000307 break;
John McCall0d1da222010-01-12 00:44:57 +0000308 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000309 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000310 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000311 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000312 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000313 break;
314 }
315
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000316 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000317}
318
John McCall0d1da222010-01-12 00:44:57 +0000319void AmbiguousConversionSequence::construct() {
320 new (&conversions()) ConversionSet();
321}
322
323void AmbiguousConversionSequence::destruct() {
324 conversions().~ConversionSet();
325}
326
327void
328AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
329 FromTypePtr = O.FromTypePtr;
330 ToTypePtr = O.ToTypePtr;
331 new (&conversions()) ConversionSet(O.conversions());
332}
333
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000334namespace {
335 // Structure used by OverloadCandidate::DeductionFailureInfo to store
336 // template parameter and template argument information.
337 struct DFIParamWithArguments {
338 TemplateParameter Param;
339 TemplateArgument FirstArg;
340 TemplateArgument SecondArg;
341 };
342}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000343
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000344/// \brief Convert from Sema's representation of template deduction information
345/// to the form used in overload-candidate information.
346OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000347static MakeDeductionFailureInfo(ASTContext &Context,
348 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000349 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000350 OverloadCandidate::DeductionFailureInfo Result;
351 Result.Result = static_cast<unsigned>(TDK);
352 Result.Data = 0;
353 switch (TDK) {
354 case Sema::TDK_Success:
355 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000356 case Sema::TDK_TooManyArguments:
357 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000358 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000359
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000360 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000361 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000362 Result.Data = Info.Param.getOpaqueValue();
363 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000364
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000365 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000366 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000367 // FIXME: Should allocate from normal heap so that we can free this later.
368 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000369 Saved->Param = Info.Param;
370 Saved->FirstArg = Info.FirstArg;
371 Saved->SecondArg = Info.SecondArg;
372 Result.Data = Saved;
373 break;
374 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000375
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000376 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000377 Result.Data = Info.take();
378 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000379
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000380 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000381 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000382 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000383 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000384
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000385 return Result;
386}
John McCall0d1da222010-01-12 00:44:57 +0000387
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000388void OverloadCandidate::DeductionFailureInfo::Destroy() {
389 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
390 case Sema::TDK_Success:
391 case Sema::TDK_InstantiationDepth:
392 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000393 case Sema::TDK_TooManyArguments:
394 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000395 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000396 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000397
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000398 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000399 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000400 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000401 Data = 0;
402 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000403
404 case Sema::TDK_SubstitutionFailure:
405 // FIXME: Destroy the template arugment list?
406 Data = 0;
407 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000408
Douglas Gregor461761d2010-05-08 18:20:53 +0000409 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000410 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000411 case Sema::TDK_FailedOverloadResolution:
412 break;
413 }
414}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000415
416TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000417OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
418 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
419 case Sema::TDK_Success:
420 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000421 case Sema::TDK_TooManyArguments:
422 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000423 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000424 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000425
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000426 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000427 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000428 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000429
430 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000431 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000432 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000433
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000434 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000435 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000436 case Sema::TDK_FailedOverloadResolution:
437 break;
438 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000439
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000440 return TemplateParameter();
441}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000442
Douglas Gregord09efd42010-05-08 20:07:26 +0000443TemplateArgumentList *
444OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
445 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
446 case Sema::TDK_Success:
447 case Sema::TDK_InstantiationDepth:
448 case Sema::TDK_TooManyArguments:
449 case Sema::TDK_TooFewArguments:
450 case Sema::TDK_Incomplete:
451 case Sema::TDK_InvalidExplicitArguments:
452 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000453 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000454 return 0;
455
456 case Sema::TDK_SubstitutionFailure:
457 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000458
Douglas Gregord09efd42010-05-08 20:07:26 +0000459 // Unhandled
460 case Sema::TDK_NonDeducedMismatch:
461 case Sema::TDK_FailedOverloadResolution:
462 break;
463 }
464
465 return 0;
466}
467
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000468const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
469 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
470 case Sema::TDK_Success:
471 case Sema::TDK_InstantiationDepth:
472 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000473 case Sema::TDK_TooManyArguments:
474 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000475 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000476 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000477 return 0;
478
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000479 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000480 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000481 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000482
Douglas Gregor461761d2010-05-08 18:20:53 +0000483 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000484 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000485 case Sema::TDK_FailedOverloadResolution:
486 break;
487 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000488
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000489 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000490}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000491
492const TemplateArgument *
493OverloadCandidate::DeductionFailureInfo::getSecondArg() {
494 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
495 case Sema::TDK_Success:
496 case Sema::TDK_InstantiationDepth:
497 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000498 case Sema::TDK_TooManyArguments:
499 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000500 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000501 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000502 return 0;
503
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000504 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000505 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000506 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
507
Douglas Gregor461761d2010-05-08 18:20:53 +0000508 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000509 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000510 case Sema::TDK_FailedOverloadResolution:
511 break;
512 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000513
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000514 return 0;
515}
516
517void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000518 inherited::clear();
519 Functions.clear();
520}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000521
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000522// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000523// overload of the declarations in Old. This routine returns false if
524// New and Old cannot be overloaded, e.g., if New has the same
525// signature as some function in Old (C++ 1.3.10) or if the Old
526// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000527// it does return false, MatchedDecl will point to the decl that New
528// cannot be overloaded with. This decl may be a UsingShadowDecl on
529// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000530//
531// Example: Given the following input:
532//
533// void f(int, float); // #1
534// void f(int, int); // #2
535// int f(int, int); // #3
536//
537// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000538// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000539//
John McCall3d988d92009-12-02 08:47:38 +0000540// When we process #2, Old contains only the FunctionDecl for #1. By
541// comparing the parameter types, we see that #1 and #2 are overloaded
542// (since they have different signatures), so this routine returns
543// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000544//
John McCall3d988d92009-12-02 08:47:38 +0000545// When we process #3, Old is an overload set containing #1 and #2. We
546// compare the signatures of #3 to #1 (they're overloaded, so we do
547// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
548// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000549// signature), IsOverload returns false and MatchedDecl will be set to
550// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000551//
552// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
553// into a class by a using declaration. The rules for whether to hide
554// shadow declarations ignore some properties which otherwise figure
555// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000556Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000557Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
558 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000559 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000560 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000561 NamedDecl *OldD = *I;
562
563 bool OldIsUsingDecl = false;
564 if (isa<UsingShadowDecl>(OldD)) {
565 OldIsUsingDecl = true;
566
567 // We can always introduce two using declarations into the same
568 // context, even if they have identical signatures.
569 if (NewIsUsingDecl) continue;
570
571 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
572 }
573
574 // If either declaration was introduced by a using declaration,
575 // we'll need to use slightly different rules for matching.
576 // Essentially, these rules are the normal rules, except that
577 // function templates hide function templates with different
578 // return types or template parameter lists.
579 bool UseMemberUsingDeclRules =
580 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
581
John McCall3d988d92009-12-02 08:47:38 +0000582 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000583 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
584 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
585 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
586 continue;
587 }
588
John McCalldaa3d6b2009-12-09 03:35:25 +0000589 Match = *I;
590 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000591 }
John McCall3d988d92009-12-02 08:47:38 +0000592 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000593 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
594 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
595 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
596 continue;
597 }
598
John McCalldaa3d6b2009-12-09 03:35:25 +0000599 Match = *I;
600 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000601 }
John McCalla8987a2942010-11-10 03:01:53 +0000602 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000603 // We can overload with these, which can show up when doing
604 // redeclaration checks for UsingDecls.
605 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000606 } else if (isa<TagDecl>(OldD)) {
607 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000608 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
609 // Optimistically assume that an unresolved using decl will
610 // overload; if it doesn't, we'll have to diagnose during
611 // template instantiation.
612 } else {
John McCall1f82f242009-11-18 22:49:29 +0000613 // (C++ 13p1):
614 // Only function declarations can be overloaded; object and type
615 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000616 Match = *I;
617 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000618 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000619 }
John McCall1f82f242009-11-18 22:49:29 +0000620
John McCalldaa3d6b2009-12-09 03:35:25 +0000621 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000622}
623
John McCalle9cccd82010-06-16 08:42:20 +0000624bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
625 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000626 // If both of the functions are extern "C", then they are not
627 // overloads.
628 if (Old->isExternC() && New->isExternC())
629 return false;
630
John McCall1f82f242009-11-18 22:49:29 +0000631 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
632 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
633
634 // C++ [temp.fct]p2:
635 // A function template can be overloaded with other function templates
636 // and with normal (non-template) functions.
637 if ((OldTemplate == 0) != (NewTemplate == 0))
638 return true;
639
640 // Is the function New an overload of the function Old?
641 QualType OldQType = Context.getCanonicalType(Old->getType());
642 QualType NewQType = Context.getCanonicalType(New->getType());
643
644 // Compare the signatures (C++ 1.3.10) of the two functions to
645 // determine whether they are overloads. If we find any mismatch
646 // in the signature, they are overloads.
647
648 // If either of these functions is a K&R-style function (no
649 // prototype), then we consider them to have matching signatures.
650 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
651 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
652 return false;
653
John McCall424cec92011-01-19 06:33:43 +0000654 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
655 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000656
657 // The signature of a function includes the types of its
658 // parameters (C++ 1.3.10), which includes the presence or absence
659 // of the ellipsis; see C++ DR 357).
660 if (OldQType != NewQType &&
661 (OldType->getNumArgs() != NewType->getNumArgs() ||
662 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000663 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000664 return true;
665
666 // C++ [temp.over.link]p4:
667 // The signature of a function template consists of its function
668 // signature, its return type and its template parameter list. The names
669 // of the template parameters are significant only for establishing the
670 // relationship between the template parameters and the rest of the
671 // signature.
672 //
673 // We check the return type and template parameter lists for function
674 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000675 //
676 // However, we don't consider either of these when deciding whether
677 // a member introduced by a shadow declaration is hidden.
678 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000679 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
680 OldTemplate->getTemplateParameters(),
681 false, TPL_TemplateMatch) ||
682 OldType->getResultType() != NewType->getResultType()))
683 return true;
684
685 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000686 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000687 //
688 // As part of this, also check whether one of the member functions
689 // is static, in which case they are not overloads (C++
690 // 13.1p2). While not part of the definition of the signature,
691 // this check is important to determine whether these functions
692 // can be overloaded.
693 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
694 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
695 if (OldMethod && NewMethod &&
696 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000697 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000698 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
699 if (!UseUsingDeclRules &&
700 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
701 (OldMethod->getRefQualifier() == RQ_None ||
702 NewMethod->getRefQualifier() == RQ_None)) {
703 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000704 // - Member function declarations with the same name and the same
705 // parameter-type-list as well as member function template
706 // declarations with the same name, the same parameter-type-list, and
707 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000708 // them, but not all, have a ref-qualifier (8.3.5).
709 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
710 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
711 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000713
John McCall1f82f242009-11-18 22:49:29 +0000714 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000715 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716
John McCall1f82f242009-11-18 22:49:29 +0000717 // The signatures match; this is not an overload.
718 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000719}
720
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000721/// TryImplicitConversion - Attempt to perform an implicit conversion
722/// from the given expression (Expr) to the given type (ToType). This
723/// function returns an implicit conversion sequence that can be used
724/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000725///
726/// void f(float f);
727/// void g(int i) { f(i); }
728///
729/// this routine would produce an implicit conversion sequence to
730/// describe the initialization of f from i, which will be a standard
731/// conversion sequence containing an lvalue-to-rvalue conversion (C++
732/// 4.1) followed by a floating-integral conversion (C++ 4.9).
733//
734/// Note that this routine only determines how the conversion can be
735/// performed; it does not actually perform the conversion. As such,
736/// it will not produce any diagnostics if no conversion is available,
737/// but will instead return an implicit conversion sequence of kind
738/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000739///
740/// If @p SuppressUserConversions, then user-defined conversions are
741/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000742/// If @p AllowExplicit, then explicit user-defined conversions are
743/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000744static ImplicitConversionSequence
745TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
746 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000747 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000748 bool InOverloadResolution,
749 bool CStyle) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000750 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000751 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +0000752 ICS.Standard, CStyle)) {
John McCall0d1da222010-01-12 00:44:57 +0000753 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000754 return ICS;
755 }
756
John McCall5c32be02010-08-24 20:38:10 +0000757 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000758 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000759 return ICS;
760 }
761
Douglas Gregor836a7e82010-08-11 02:15:33 +0000762 // C++ [over.ics.user]p4:
763 // A conversion of an expression of class type to the same class
764 // type is given Exact Match rank, and a conversion of an
765 // expression of class type to a base class of that type is
766 // given Conversion rank, in spite of the fact that a copy/move
767 // constructor (i.e., a user-defined conversion function) is
768 // called for those cases.
769 QualType FromType = From->getType();
770 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000771 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
772 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000773 ICS.setStandard();
774 ICS.Standard.setAsIdentityConversion();
775 ICS.Standard.setFromType(FromType);
776 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000777
Douglas Gregor5ab11652010-04-17 22:01:05 +0000778 // We don't actually check at this point whether there is a valid
779 // copy/move constructor, since overloading just assumes that it
780 // exists. When we actually perform initialization, we'll find the
781 // appropriate constructor to copy the returned object, if needed.
782 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000783
Douglas Gregor5ab11652010-04-17 22:01:05 +0000784 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000785 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000786 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000787
Douglas Gregor836a7e82010-08-11 02:15:33 +0000788 return ICS;
789 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000790
Douglas Gregor836a7e82010-08-11 02:15:33 +0000791 if (SuppressUserConversions) {
792 // We're not in the case above, so there is no conversion that
793 // we can perform.
794 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000795 return ICS;
796 }
797
798 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000799 OverloadCandidateSet Conversions(From->getExprLoc());
800 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000801 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000802 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000803
804 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000805 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000806 // C++ [over.ics.user]p4:
807 // A conversion of an expression of class type to the same class
808 // type is given Exact Match rank, and a conversion of an
809 // expression of class type to a base class of that type is
810 // given Conversion rank, in spite of the fact that a copy
811 // constructor (i.e., a user-defined conversion function) is
812 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000813 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000814 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000815 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000816 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
817 QualType ToCanon
818 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000819 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000820 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000821 // Turn this into a "standard" conversion sequence, so that it
822 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000823 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000824 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000825 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000826 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000827 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000828 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000829 ICS.Standard.Second = ICK_Derived_To_Base;
830 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000831 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000832
833 // C++ [over.best.ics]p4:
834 // However, when considering the argument of a user-defined
835 // conversion function that is a candidate by 13.3.1.3 when
836 // invoked for the copying of the temporary in the second step
837 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
838 // 13.3.1.6 in all cases, only standard conversion sequences and
839 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000840 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000841 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000842 }
John McCalle8c8cd22010-01-13 22:30:33 +0000843 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000844 ICS.setAmbiguous();
845 ICS.Ambiguous.setFromType(From->getType());
846 ICS.Ambiguous.setToType(ToType);
847 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
848 Cand != Conversions.end(); ++Cand)
849 if (Cand->Viable)
850 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000851 } else {
John McCall65eb8792010-02-25 01:37:24 +0000852 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000853 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000854
855 return ICS;
856}
857
John McCall5c32be02010-08-24 20:38:10 +0000858bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
859 const InitializedEntity &Entity,
860 Expr *Initializer,
861 bool SuppressUserConversions,
862 bool AllowExplicitConversions,
Douglas Gregor58281352011-01-27 00:58:17 +0000863 bool InOverloadResolution,
864 bool CStyle) {
John McCall5c32be02010-08-24 20:38:10 +0000865 ImplicitConversionSequence ICS
866 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
867 SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000868 AllowExplicitConversions,
Douglas Gregor58281352011-01-27 00:58:17 +0000869 InOverloadResolution,
870 CStyle);
John McCall5c32be02010-08-24 20:38:10 +0000871 if (ICS.isBad()) return true;
872
873 // Perform the actual conversion.
874 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
875 return false;
876}
877
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000878/// PerformImplicitConversion - Perform an implicit conversion of the
879/// expression From to the type ToType. Returns true if there was an
880/// error, false otherwise. The expression From is replaced with the
881/// converted expression. Flavor is the kind of conversion we're
882/// performing, used in the error message. If @p AllowExplicit,
883/// explicit user-defined conversions are permitted.
884bool
885Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
886 AssignmentAction Action, bool AllowExplicit) {
887 ImplicitConversionSequence ICS;
888 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
889}
890
891bool
892Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
893 AssignmentAction Action, bool AllowExplicit,
894 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000895 ICS = clang::TryImplicitConversion(*this, From, ToType,
896 /*SuppressUserConversions=*/false,
897 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000898 /*InOverloadResolution=*/false,
899 /*CStyle=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000900 return PerformImplicitConversion(From, ToType, ICS, Action);
901}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000902
903/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000904/// conversion that strips "noreturn" off the nested function type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000905static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000906 QualType ToType, QualType &ResultTy) {
907 if (Context.hasSameUnqualifiedType(FromType, ToType))
908 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000909
John McCall991eb4b2010-12-21 00:44:39 +0000910 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
911 // where F adds one of the following at most once:
912 // - a pointer
913 // - a member pointer
914 // - a block pointer
915 CanQualType CanTo = Context.getCanonicalType(ToType);
916 CanQualType CanFrom = Context.getCanonicalType(FromType);
917 Type::TypeClass TyClass = CanTo->getTypeClass();
918 if (TyClass != CanFrom->getTypeClass()) return false;
919 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
920 if (TyClass == Type::Pointer) {
921 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
922 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
923 } else if (TyClass == Type::BlockPointer) {
924 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
925 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
926 } else if (TyClass == Type::MemberPointer) {
927 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
928 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
929 } else {
930 return false;
931 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000932
John McCall991eb4b2010-12-21 00:44:39 +0000933 TyClass = CanTo->getTypeClass();
934 if (TyClass != CanFrom->getTypeClass()) return false;
935 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
936 return false;
937 }
938
939 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
940 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
941 if (!EInfo.getNoReturn()) return false;
942
943 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
944 assert(QualType(FromFn, 0).isCanonical());
945 if (QualType(FromFn, 0) != CanTo) return false;
946
947 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000948 return true;
949}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000950
Douglas Gregor46188682010-05-18 22:42:18 +0000951/// \brief Determine whether the conversion from FromType to ToType is a valid
952/// vector conversion.
953///
954/// \param ICK Will be set to the vector conversion kind, if this is a vector
955/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000956static bool IsVectorConversion(ASTContext &Context, QualType FromType,
957 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +0000958 // We need at least one of these types to be a vector type to have a vector
959 // conversion.
960 if (!ToType->isVectorType() && !FromType->isVectorType())
961 return false;
962
963 // Identical types require no conversions.
964 if (Context.hasSameUnqualifiedType(FromType, ToType))
965 return false;
966
967 // There are no conversions between extended vector types, only identity.
968 if (ToType->isExtVectorType()) {
969 // There are no conversions between extended vector types other than the
970 // identity conversion.
971 if (FromType->isExtVectorType())
972 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000973
Douglas Gregor46188682010-05-18 22:42:18 +0000974 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000975 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000976 ICK = ICK_Vector_Splat;
977 return true;
978 }
979 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000980
981 // We can perform the conversion between vector types in the following cases:
982 // 1)vector types are equivalent AltiVec and GCC vector types
983 // 2)lax vector conversions are permitted and the vector types are of the
984 // same size
985 if (ToType->isVectorType() && FromType->isVectorType()) {
986 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000987 (Context.getLangOptions().LaxVectorConversions &&
988 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000989 ICK = ICK_Vector_Conversion;
990 return true;
991 }
Douglas Gregor46188682010-05-18 22:42:18 +0000992 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000993
Douglas Gregor46188682010-05-18 22:42:18 +0000994 return false;
995}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000996
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000997/// IsStandardConversion - Determines whether there is a standard
998/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
999/// expression From to the type ToType. Standard conversion sequences
1000/// only consider non-class types; for conversions that involve class
1001/// types, use TryImplicitConversion. If a conversion exists, SCS will
1002/// contain the standard conversion sequence required to perform this
1003/// conversion and this routine will return true. Otherwise, this
1004/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001005static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1006 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001007 StandardConversionSequence &SCS,
1008 bool CStyle) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001009 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001010
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001011 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001012 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001013 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001014 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001015 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001016 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001017
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001018 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001019 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001020 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001021 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001022 return false;
1023
Mike Stump11289f42009-09-09 15:08:12 +00001024 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001025 }
1026
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001027 // The first conversion can be an lvalue-to-rvalue conversion,
1028 // array-to-pointer conversion, or function-to-pointer conversion
1029 // (C++ 4p1).
1030
John McCall5c32be02010-08-24 20:38:10 +00001031 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001032 DeclAccessPair AccessPair;
1033 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001034 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001035 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001036 // We were able to resolve the address of the overloaded function,
1037 // so we can convert to the type of that function.
1038 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001039
1040 // we can sometimes resolve &foo<int> regardless of ToType, so check
1041 // if the type matches (identity) or we are converting to bool
1042 if (!S.Context.hasSameUnqualifiedType(
1043 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1044 QualType resultTy;
1045 // if the function type matches except for [[noreturn]], it's ok
1046 if (!IsNoReturnConversion(S.Context, FromType,
1047 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1048 // otherwise, only a boolean conversion is standard
1049 if (!ToType->isBooleanType())
1050 return false;
1051
1052 }
1053
Douglas Gregor980fb162010-04-29 18:24:40 +00001054 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
1055 if (!Method->isStatic()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001056 const Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +00001057 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1058 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +00001059 }
1060 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001061
Douglas Gregor980fb162010-04-29 18:24:40 +00001062 // If the "from" expression takes the address of the overloaded
1063 // function, update the type of the resulting expression accordingly.
1064 if (FromType->getAs<FunctionType>())
1065 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +00001066 if (UnOp->getOpcode() == UO_AddrOf)
John McCall5c32be02010-08-24 20:38:10 +00001067 FromType = S.Context.getPointerType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001068
Douglas Gregor980fb162010-04-29 18:24:40 +00001069 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00001070 assert(S.Context.hasSameType(FromType,
1071 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001072 } else {
1073 return false;
1074 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001075 }
Mike Stump11289f42009-09-09 15:08:12 +00001076 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001077 // An lvalue (3.10) of a non-function, non-array type T can be
1078 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001079 bool argIsLValue = From->isLValue();
1080 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001081 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001082 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001083 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001084
1085 // If T is a non-class type, the type of the rvalue is the
1086 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001087 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1088 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001089 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001090 } else if (FromType->isArrayType()) {
1091 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001092 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001093
1094 // An lvalue or rvalue of type "array of N T" or "array of unknown
1095 // bound of T" can be converted to an rvalue of type "pointer to
1096 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001097 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001098
John McCall5c32be02010-08-24 20:38:10 +00001099 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001100 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001101 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001102
1103 // For the purpose of ranking in overload resolution
1104 // (13.3.3.1.1), this conversion is considered an
1105 // array-to-pointer conversion followed by a qualification
1106 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001107 SCS.Second = ICK_Identity;
1108 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001109 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001110 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001111 }
John McCall086a4642010-11-24 05:12:34 +00001112 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001113 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001114 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001115
1116 // An lvalue of function type T can be converted to an rvalue of
1117 // type "pointer to T." The result is a pointer to the
1118 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001119 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001120 } else {
1121 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001122 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001123 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001124 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001125
1126 // The second conversion can be an integral promotion, floating
1127 // point promotion, integral conversion, floating point conversion,
1128 // floating-integral conversion, pointer conversion,
1129 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001130 // For overloading in C, this can also be a "compatible-type"
1131 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001132 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001133 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001134 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001135 // The unqualified versions of the types are the same: there's no
1136 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001137 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001138 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001139 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001140 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001141 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001142 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001143 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001144 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001145 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001146 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001147 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001148 SCS.Second = ICK_Complex_Promotion;
1149 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001150 } else if (ToType->isBooleanType() &&
1151 (FromType->isArithmeticType() ||
1152 FromType->isAnyPointerType() ||
1153 FromType->isBlockPointerType() ||
1154 FromType->isMemberPointerType() ||
1155 FromType->isNullPtrType())) {
1156 // Boolean conversions (C++ 4.12).
1157 SCS.Second = ICK_Boolean_Conversion;
1158 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001159 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001160 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001161 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001162 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001163 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001164 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001165 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001166 SCS.Second = ICK_Complex_Conversion;
1167 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001168 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1169 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001170 // Complex-real conversions (C99 6.3.1.7)
1171 SCS.Second = ICK_Complex_Real;
1172 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001173 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001174 // Floating point conversions (C++ 4.8).
1175 SCS.Second = ICK_Floating_Conversion;
1176 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001177 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001178 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001179 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001180 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001181 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001182 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001183 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001184 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1185 SCS.Second = ICK_Block_Pointer_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001186 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1187 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001188 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001189 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001190 SCS.IncompatibleObjC = IncompatibleObjC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001191 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001192 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001193 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001194 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001195 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001196 SCS.Second = SecondICK;
1197 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001198 } else if (!S.getLangOptions().CPlusPlus &&
1199 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001200 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001201 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001202 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001203 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001204 // Treat a conversion that strips "noreturn" as an identity conversion.
1205 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001206 } else {
1207 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001208 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001209 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001210 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001211
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001212 QualType CanonFrom;
1213 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001214 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor58281352011-01-27 00:58:17 +00001215 if (S.IsQualificationConversion(FromType, ToType, CStyle)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001216 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001217 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001218 CanonFrom = S.Context.getCanonicalType(FromType);
1219 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001220 } else {
1221 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001222 SCS.Third = ICK_Identity;
1223
Mike Stump11289f42009-09-09 15:08:12 +00001224 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001225 // [...] Any difference in top-level cv-qualification is
1226 // subsumed by the initialization itself and does not constitute
1227 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001228 CanonFrom = S.Context.getCanonicalType(FromType);
1229 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001230 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001231 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001232 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1233 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001234 FromType = ToType;
1235 CanonFrom = CanonTo;
1236 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001237 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001238 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001239
1240 // If we have not converted the argument type to the parameter type,
1241 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001242 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001243 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001244
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001245 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001246}
1247
1248/// IsIntegralPromotion - Determines whether the conversion from the
1249/// expression From (whose potentially-adjusted type is FromType) to
1250/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1251/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001252bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001253 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001254 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001255 if (!To) {
1256 return false;
1257 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001258
1259 // An rvalue of type char, signed char, unsigned char, short int, or
1260 // unsigned short int can be converted to an rvalue of type int if
1261 // int can represent all the values of the source type; otherwise,
1262 // the source rvalue can be converted to an rvalue of type unsigned
1263 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001264 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1265 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001266 if (// We can promote any signed, promotable integer type to an int
1267 (FromType->isSignedIntegerType() ||
1268 // We can promote any unsigned integer type whose size is
1269 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001270 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001271 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001272 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001273 }
1274
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001275 return To->getKind() == BuiltinType::UInt;
1276 }
1277
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001278 // C++0x [conv.prom]p3:
1279 // A prvalue of an unscoped enumeration type whose underlying type is not
1280 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1281 // following types that can represent all the values of the enumeration
1282 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1283 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001284 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001285 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001286 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001287 // with lowest integer conversion rank (4.13) greater than the rank of long
1288 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001289 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001290 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1291 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1292 // provided for a scoped enumeration.
1293 if (FromEnumType->getDecl()->isScoped())
1294 return false;
1295
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001296 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001297 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001298 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001299 return Context.hasSameUnqualifiedType(ToType,
1300 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001301 }
John McCall56774992009-12-09 09:09:27 +00001302
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001303 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001304 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1305 // to an rvalue a prvalue of the first of the following types that can
1306 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001307 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001308 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001309 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001310 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001311 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001312 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001313 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001314 // Determine whether the type we're converting from is signed or
1315 // unsigned.
1316 bool FromIsSigned;
1317 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001318
John McCall56774992009-12-09 09:09:27 +00001319 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1320 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001321
1322 // The types we'll try to promote to, in the appropriate
1323 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001324 QualType PromoteTypes[6] = {
1325 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001326 Context.LongTy, Context.UnsignedLongTy ,
1327 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001328 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001329 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001330 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1331 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001332 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001333 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1334 // We found the type that we can promote to. If this is the
1335 // type we wanted, we have a promotion. Otherwise, no
1336 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001337 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001338 }
1339 }
1340 }
1341
1342 // An rvalue for an integral bit-field (9.6) can be converted to an
1343 // rvalue of type int if int can represent all the values of the
1344 // bit-field; otherwise, it can be converted to unsigned int if
1345 // unsigned int can represent all the values of the bit-field. If
1346 // the bit-field is larger yet, no integral promotion applies to
1347 // it. If the bit-field has an enumerated type, it is treated as any
1348 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001349 // FIXME: We should delay checking of bit-fields until we actually perform the
1350 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001351 using llvm::APSInt;
1352 if (From)
1353 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001354 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001355 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001356 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1357 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1358 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001359
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001360 // Are we promoting to an int from a bitfield that fits in an int?
1361 if (BitWidth < ToSize ||
1362 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1363 return To->getKind() == BuiltinType::Int;
1364 }
Mike Stump11289f42009-09-09 15:08:12 +00001365
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001366 // Are we promoting to an unsigned int from an unsigned bitfield
1367 // that fits into an unsigned int?
1368 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1369 return To->getKind() == BuiltinType::UInt;
1370 }
Mike Stump11289f42009-09-09 15:08:12 +00001371
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001372 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001373 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001374 }
Mike Stump11289f42009-09-09 15:08:12 +00001375
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001376 // An rvalue of type bool can be converted to an rvalue of type int,
1377 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001378 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001379 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001380 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001381
1382 return false;
1383}
1384
1385/// IsFloatingPointPromotion - Determines whether the conversion from
1386/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1387/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001388bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001389 /// An rvalue of type float can be converted to an rvalue of type
1390 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001391 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1392 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001393 if (FromBuiltin->getKind() == BuiltinType::Float &&
1394 ToBuiltin->getKind() == BuiltinType::Double)
1395 return true;
1396
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001397 // C99 6.3.1.5p1:
1398 // When a float is promoted to double or long double, or a
1399 // double is promoted to long double [...].
1400 if (!getLangOptions().CPlusPlus &&
1401 (FromBuiltin->getKind() == BuiltinType::Float ||
1402 FromBuiltin->getKind() == BuiltinType::Double) &&
1403 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1404 return true;
1405 }
1406
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001407 return false;
1408}
1409
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001410/// \brief Determine if a conversion is a complex promotion.
1411///
1412/// A complex promotion is defined as a complex -> complex conversion
1413/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001414/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001415bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001416 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001417 if (!FromComplex)
1418 return false;
1419
John McCall9dd450b2009-09-21 23:43:11 +00001420 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001421 if (!ToComplex)
1422 return false;
1423
1424 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001425 ToComplex->getElementType()) ||
1426 IsIntegralPromotion(0, FromComplex->getElementType(),
1427 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001428}
1429
Douglas Gregor237f96c2008-11-26 23:31:11 +00001430/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1431/// the pointer type FromPtr to a pointer to type ToPointee, with the
1432/// same type qualifiers as FromPtr has on its pointee type. ToType,
1433/// if non-empty, will be a pointer to ToType that may or may not have
1434/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001435static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001436BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001437 QualType ToPointee, QualType ToType,
1438 ASTContext &Context) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001439 assert((FromPtr->getTypeClass() == Type::Pointer ||
1440 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1441 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001442
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001443 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1444 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1445 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001446
1447 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001448 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001449 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001450 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001451
1452 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001453 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001454 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001455 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001456 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001457
1458 // Build a pointer to ToPointee. It has the right qualifiers
1459 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001460 if (isa<ObjCObjectPointerType>(ToType))
1461 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001462 return Context.getPointerType(ToPointee);
1463 }
1464
1465 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001466 QualType QualifiedCanonToPointee
1467 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001468
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001469 if (isa<ObjCObjectPointerType>(ToType))
1470 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1471 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001472}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001473
Mike Stump11289f42009-09-09 15:08:12 +00001474static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001475 bool InOverloadResolution,
1476 ASTContext &Context) {
1477 // Handle value-dependent integral null pointer constants correctly.
1478 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1479 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001480 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001481 return !InOverloadResolution;
1482
Douglas Gregor56751b52009-09-25 04:25:58 +00001483 return Expr->isNullPointerConstant(Context,
1484 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1485 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001486}
Mike Stump11289f42009-09-09 15:08:12 +00001487
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001488/// IsPointerConversion - Determines whether the conversion of the
1489/// expression From, which has the (possibly adjusted) type FromType,
1490/// can be converted to the type ToType via a pointer conversion (C++
1491/// 4.10). If so, returns true and places the converted type (that
1492/// might differ from ToType in its cv-qualifiers at some level) into
1493/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001494///
Douglas Gregora29dc052008-11-27 01:19:21 +00001495/// This routine also supports conversions to and from block pointers
1496/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1497/// pointers to interfaces. FIXME: Once we've determined the
1498/// appropriate overloading rules for Objective-C, we may want to
1499/// split the Objective-C checks into a different routine; however,
1500/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001501/// conversions, so for now they live here. IncompatibleObjC will be
1502/// set if the conversion is an allowed Objective-C conversion that
1503/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001504bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001505 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001506 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001507 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001508 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001509 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1510 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001511 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001512
Mike Stump11289f42009-09-09 15:08:12 +00001513 // Conversion from a null pointer constant to any Objective-C pointer type.
1514 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001515 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001516 ConvertedType = ToType;
1517 return true;
1518 }
1519
Douglas Gregor231d1c62008-11-27 00:15:41 +00001520 // Blocks: Block pointers can be converted to void*.
1521 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001522 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001523 ConvertedType = ToType;
1524 return true;
1525 }
1526 // Blocks: A null pointer constant can be converted to a block
1527 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001528 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001529 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001530 ConvertedType = ToType;
1531 return true;
1532 }
1533
Sebastian Redl576fd422009-05-10 18:38:11 +00001534 // If the left-hand-side is nullptr_t, the right side can be a null
1535 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001536 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001537 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001538 ConvertedType = ToType;
1539 return true;
1540 }
1541
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001542 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001543 if (!ToTypePtr)
1544 return false;
1545
1546 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001547 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001548 ConvertedType = ToType;
1549 return true;
1550 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001551
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001552 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001553 // , including objective-c pointers.
1554 QualType ToPointeeType = ToTypePtr->getPointeeType();
1555 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001556 ConvertedType = BuildSimilarlyQualifiedPointerType(
1557 FromType->getAs<ObjCObjectPointerType>(),
1558 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001559 ToType, Context);
1560 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001561 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001562 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001563 if (!FromTypePtr)
1564 return false;
1565
1566 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001567
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001568 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001569 // pointer conversion, so don't do all of the work below.
1570 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1571 return false;
1572
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001573 // An rvalue of type "pointer to cv T," where T is an object type,
1574 // can be converted to an rvalue of type "pointer to cv void" (C++
1575 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001576 if (FromPointeeType->isIncompleteOrObjectType() &&
1577 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001578 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001579 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001580 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001581 return true;
1582 }
1583
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001584 // When we're overloading in C, we allow a special kind of pointer
1585 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001586 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001587 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001588 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001589 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001590 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001591 return true;
1592 }
1593
Douglas Gregor5c407d92008-10-23 00:40:37 +00001594 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001595 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001596 // An rvalue of type "pointer to cv D," where D is a class type,
1597 // can be converted to an rvalue of type "pointer to cv B," where
1598 // B is a base class (clause 10) of D. If B is an inaccessible
1599 // (clause 11) or ambiguous (10.2) base class of D, a program that
1600 // necessitates this conversion is ill-formed. The result of the
1601 // conversion is a pointer to the base class sub-object of the
1602 // derived class object. The null pointer value is converted to
1603 // the null pointer value of the destination type.
1604 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001605 // Note that we do not check for ambiguity or inaccessibility
1606 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001607 if (getLangOptions().CPlusPlus &&
1608 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001609 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001610 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001611 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001612 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001613 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001614 ToType, Context);
1615 return true;
1616 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001617
Douglas Gregora119f102008-12-19 19:13:09 +00001618 return false;
1619}
1620
1621/// isObjCPointerConversion - Determines whether this is an
1622/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1623/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001624bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001625 QualType& ConvertedType,
1626 bool &IncompatibleObjC) {
1627 if (!getLangOptions().ObjC1)
1628 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001629
Steve Naroff7cae42b2009-07-10 23:34:53 +00001630 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001631 const ObjCObjectPointerType* ToObjCPtr =
1632 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001633 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001634 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001635
Steve Naroff7cae42b2009-07-10 23:34:53 +00001636 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001637 // If the pointee types are the same (ignoring qualifications),
1638 // then this is not a pointer conversion.
1639 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1640 FromObjCPtr->getPointeeType()))
1641 return false;
1642
Steve Naroff1329fa02009-07-15 18:40:39 +00001643 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001644 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001645 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001646 ConvertedType = ToType;
1647 return true;
1648 }
1649 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001650 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001651 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001652 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001653 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001654 ConvertedType = ToType;
1655 return true;
1656 }
1657 // Objective C++: We're able to convert from a pointer to an
1658 // interface to a pointer to a different interface.
1659 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001660 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1661 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1662 if (getLangOptions().CPlusPlus && LHS && RHS &&
1663 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1664 FromObjCPtr->getPointeeType()))
1665 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001666 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001667 ToObjCPtr->getPointeeType(),
1668 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001669 return true;
1670 }
1671
1672 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1673 // Okay: this is some kind of implicit downcast of Objective-C
1674 // interfaces, which is permitted. However, we're going to
1675 // complain about it.
1676 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001677 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001678 ToObjCPtr->getPointeeType(),
1679 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001680 return true;
1681 }
Mike Stump11289f42009-09-09 15:08:12 +00001682 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001683 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001684 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001685 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001686 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001687 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001688 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001689 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001690 // to a block pointer type.
1691 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1692 ConvertedType = ToType;
1693 return true;
1694 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001695 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001696 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001697 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001698 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001699 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001700 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001701 ConvertedType = ToType;
1702 return true;
1703 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001704 else
Douglas Gregora119f102008-12-19 19:13:09 +00001705 return false;
1706
Douglas Gregor033f56d2008-12-23 00:53:59 +00001707 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001708 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001709 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001710 else if (const BlockPointerType *FromBlockPtr =
1711 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001712 FromPointeeType = FromBlockPtr->getPointeeType();
1713 else
Douglas Gregora119f102008-12-19 19:13:09 +00001714 return false;
1715
Douglas Gregora119f102008-12-19 19:13:09 +00001716 // If we have pointers to pointers, recursively check whether this
1717 // is an Objective-C conversion.
1718 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1719 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1720 IncompatibleObjC)) {
1721 // We always complain about this conversion.
1722 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001723 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregora119f102008-12-19 19:13:09 +00001724 return true;
1725 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001726 // Allow conversion of pointee being objective-c pointer to another one;
1727 // as in I* to id.
1728 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1729 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1730 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1731 IncompatibleObjC)) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001732 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001733 return true;
1734 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001735
Douglas Gregor033f56d2008-12-23 00:53:59 +00001736 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001737 // differences in the argument and result types are in Objective-C
1738 // pointer conversions. If so, we permit the conversion (but
1739 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001740 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001741 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001742 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001743 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001744 if (FromFunctionType && ToFunctionType) {
1745 // If the function types are exactly the same, this isn't an
1746 // Objective-C pointer conversion.
1747 if (Context.getCanonicalType(FromPointeeType)
1748 == Context.getCanonicalType(ToPointeeType))
1749 return false;
1750
1751 // Perform the quick checks that will tell us whether these
1752 // function types are obviously different.
1753 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1754 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1755 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1756 return false;
1757
1758 bool HasObjCConversion = false;
1759 if (Context.getCanonicalType(FromFunctionType->getResultType())
1760 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1761 // Okay, the types match exactly. Nothing to do.
1762 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1763 ToFunctionType->getResultType(),
1764 ConvertedType, IncompatibleObjC)) {
1765 // Okay, we have an Objective-C pointer conversion.
1766 HasObjCConversion = true;
1767 } else {
1768 // Function types are too different. Abort.
1769 return false;
1770 }
Mike Stump11289f42009-09-09 15:08:12 +00001771
Douglas Gregora119f102008-12-19 19:13:09 +00001772 // Check argument types.
1773 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1774 ArgIdx != NumArgs; ++ArgIdx) {
1775 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1776 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1777 if (Context.getCanonicalType(FromArgType)
1778 == Context.getCanonicalType(ToArgType)) {
1779 // Okay, the types match exactly. Nothing to do.
1780 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1781 ConvertedType, IncompatibleObjC)) {
1782 // Okay, we have an Objective-C pointer conversion.
1783 HasObjCConversion = true;
1784 } else {
1785 // Argument types are too different. Abort.
1786 return false;
1787 }
1788 }
1789
1790 if (HasObjCConversion) {
1791 // We had an Objective-C conversion. Allow this pointer
1792 // conversion, but complain about it.
1793 ConvertedType = ToType;
1794 IncompatibleObjC = true;
1795 return true;
1796 }
1797 }
1798
Sebastian Redl72b597d2009-01-25 19:43:20 +00001799 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001800}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001801
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001802bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1803 QualType& ConvertedType) {
1804 QualType ToPointeeType;
1805 if (const BlockPointerType *ToBlockPtr =
1806 ToType->getAs<BlockPointerType>())
1807 ToPointeeType = ToBlockPtr->getPointeeType();
1808 else
1809 return false;
1810
1811 QualType FromPointeeType;
1812 if (const BlockPointerType *FromBlockPtr =
1813 FromType->getAs<BlockPointerType>())
1814 FromPointeeType = FromBlockPtr->getPointeeType();
1815 else
1816 return false;
1817 // We have pointer to blocks, check whether the only
1818 // differences in the argument and result types are in Objective-C
1819 // pointer conversions. If so, we permit the conversion.
1820
1821 const FunctionProtoType *FromFunctionType
1822 = FromPointeeType->getAs<FunctionProtoType>();
1823 const FunctionProtoType *ToFunctionType
1824 = ToPointeeType->getAs<FunctionProtoType>();
1825
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001826 if (!FromFunctionType || !ToFunctionType)
1827 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001828
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001829 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001830 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001831
1832 // Perform the quick checks that will tell us whether these
1833 // function types are obviously different.
1834 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1835 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
1836 return false;
1837
1838 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
1839 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
1840 if (FromEInfo != ToEInfo)
1841 return false;
1842
1843 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00001844 if (Context.hasSameType(FromFunctionType->getResultType(),
1845 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001846 // Okay, the types match exactly. Nothing to do.
1847 } else {
1848 QualType RHS = FromFunctionType->getResultType();
1849 QualType LHS = ToFunctionType->getResultType();
1850 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
1851 !RHS.hasQualifiers() && LHS.hasQualifiers())
1852 LHS = LHS.getUnqualifiedType();
1853
1854 if (Context.hasSameType(RHS,LHS)) {
1855 // OK exact match.
1856 } else if (isObjCPointerConversion(RHS, LHS,
1857 ConvertedType, IncompatibleObjC)) {
1858 if (IncompatibleObjC)
1859 return false;
1860 // Okay, we have an Objective-C pointer conversion.
1861 }
1862 else
1863 return false;
1864 }
1865
1866 // Check argument types.
1867 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1868 ArgIdx != NumArgs; ++ArgIdx) {
1869 IncompatibleObjC = false;
1870 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1871 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1872 if (Context.hasSameType(FromArgType, ToArgType)) {
1873 // Okay, the types match exactly. Nothing to do.
1874 } else if (isObjCPointerConversion(ToArgType, FromArgType,
1875 ConvertedType, IncompatibleObjC)) {
1876 if (IncompatibleObjC)
1877 return false;
1878 // Okay, we have an Objective-C pointer conversion.
1879 } else
1880 // Argument types are too different. Abort.
1881 return false;
1882 }
1883 ConvertedType = ToType;
1884 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001885}
1886
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001887/// FunctionArgTypesAreEqual - This routine checks two function proto types
1888/// for equlity of their argument types. Caller has already checked that
1889/// they have same number of arguments. This routine assumes that Objective-C
1890/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001891bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00001892 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001893 if (!getLangOptions().ObjC1)
1894 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1895 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001896
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001897 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1898 N = NewType->arg_type_begin(),
1899 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1900 QualType ToType = (*O);
1901 QualType FromType = (*N);
1902 if (ToType != FromType) {
1903 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1904 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001905 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1906 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1907 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1908 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001909 continue;
1910 }
John McCall8b07ec22010-05-15 11:32:37 +00001911 else if (const ObjCObjectPointerType *PTTo =
1912 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001913 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00001914 FromType->getAs<ObjCObjectPointerType>())
1915 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1916 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001917 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001918 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001919 }
1920 }
1921 return true;
1922}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001923
Douglas Gregor39c16d42008-10-24 04:54:22 +00001924/// CheckPointerConversion - Check the pointer conversion from the
1925/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001926/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001927/// conversions for which IsPointerConversion has already returned
1928/// true. It returns true and produces a diagnostic if there was an
1929/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001930bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001931 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001932 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001933 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001934 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001935 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001936
John McCall8cb679e2010-11-15 09:13:47 +00001937 Kind = CK_BitCast;
1938
Douglas Gregor4038cf42010-06-08 17:35:15 +00001939 if (CXXBoolLiteralExpr* LitBool
1940 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001941 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregor4038cf42010-06-08 17:35:15 +00001942 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1943 << ToType;
1944
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001945 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1946 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001947 QualType FromPointeeType = FromPtrType->getPointeeType(),
1948 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001949
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001950 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1951 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001952 // We must have a derived-to-base conversion. Check an
1953 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001954 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1955 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001956 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001957 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001958 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001959
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001960 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00001961 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001962 }
1963 }
Mike Stump11289f42009-09-09 15:08:12 +00001964 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00001965 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001966 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001967 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001968 // Objective-C++ conversions are always okay.
1969 // FIXME: We should have a different class of conversions for the
1970 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001971 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001972 return false;
John McCall8cb679e2010-11-15 09:13:47 +00001973 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001974 }
John McCall8cb679e2010-11-15 09:13:47 +00001975
1976 // We shouldn't fall into this case unless it's valid for other
1977 // reasons.
1978 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1979 Kind = CK_NullToPointer;
1980
Douglas Gregor39c16d42008-10-24 04:54:22 +00001981 return false;
1982}
1983
Sebastian Redl72b597d2009-01-25 19:43:20 +00001984/// IsMemberPointerConversion - Determines whether the conversion of the
1985/// expression From, which has the (possibly adjusted) type FromType, can be
1986/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1987/// If so, returns true and places the converted type (that might differ from
1988/// ToType in its cv-qualifiers at some level) into ConvertedType.
1989bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001990 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001991 bool InOverloadResolution,
1992 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001993 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001994 if (!ToTypePtr)
1995 return false;
1996
1997 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001998 if (From->isNullPointerConstant(Context,
1999 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2000 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002001 ConvertedType = ToType;
2002 return true;
2003 }
2004
2005 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002006 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002007 if (!FromTypePtr)
2008 return false;
2009
2010 // A pointer to member of B can be converted to a pointer to member of D,
2011 // where D is derived from B (C++ 4.11p2).
2012 QualType FromClass(FromTypePtr->getClass(), 0);
2013 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002014
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002015 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2016 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2017 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002018 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2019 ToClass.getTypePtr());
2020 return true;
2021 }
2022
2023 return false;
2024}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002025
Sebastian Redl72b597d2009-01-25 19:43:20 +00002026/// CheckMemberPointerConversion - Check the member pointer conversion from the
2027/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002028/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002029/// for which IsMemberPointerConversion has already returned true. It returns
2030/// true and produces a diagnostic if there was an error, or returns false
2031/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002032bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002033 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002034 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002035 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002036 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002037 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002038 if (!FromPtrType) {
2039 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002040 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002041 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002042 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002043 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002044 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002045 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002046
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002047 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002048 assert(ToPtrType && "No member pointer cast has a target type "
2049 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002050
Sebastian Redled8f2002009-01-28 18:33:18 +00002051 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2052 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002053
Sebastian Redled8f2002009-01-28 18:33:18 +00002054 // FIXME: What about dependent types?
2055 assert(FromClass->isRecordType() && "Pointer into non-class.");
2056 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002057
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002058 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002059 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002060 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2061 assert(DerivationOkay &&
2062 "Should not have been called if derivation isn't OK.");
2063 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002064
Sebastian Redled8f2002009-01-28 18:33:18 +00002065 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2066 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002067 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2068 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2069 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2070 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002071 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002072
Douglas Gregor89ee6822009-02-28 01:32:25 +00002073 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002074 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2075 << FromClass << ToClass << QualType(VBase, 0)
2076 << From->getSourceRange();
2077 return true;
2078 }
2079
John McCall5b0829a2010-02-10 09:31:12 +00002080 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002081 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2082 Paths.front(),
2083 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002084
Anders Carlssond7923c62009-08-22 23:33:40 +00002085 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002086 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002087 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002088 return false;
2089}
2090
Douglas Gregor9a657932008-10-21 23:43:52 +00002091/// IsQualificationConversion - Determines whether the conversion from
2092/// an rvalue of type FromType to ToType is a qualification conversion
2093/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00002094bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002095Sema::IsQualificationConversion(QualType FromType, QualType ToType,
Douglas Gregor58281352011-01-27 00:58:17 +00002096 bool CStyle) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002097 FromType = Context.getCanonicalType(FromType);
2098 ToType = Context.getCanonicalType(ToType);
2099
2100 // If FromType and ToType are the same type, this is not a
2101 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002102 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002103 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002104
Douglas Gregor9a657932008-10-21 23:43:52 +00002105 // (C++ 4.4p4):
2106 // A conversion can add cv-qualifiers at levels other than the first
2107 // in multi-level pointers, subject to the following rules: [...]
2108 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002109 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002110 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002111 // Within each iteration of the loop, we check the qualifiers to
2112 // determine if this still looks like a qualification
2113 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002114 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002115 // until there are no more pointers or pointers-to-members left to
2116 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002117 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002118
2119 // -- for every j > 0, if const is in cv 1,j then const is in cv
2120 // 2,j, and similarly for volatile.
Douglas Gregor58281352011-01-27 00:58:17 +00002121 if (!CStyle && !ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00002122 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002123
Douglas Gregor9a657932008-10-21 23:43:52 +00002124 // -- if the cv 1,j and cv 2,j are different, then const is in
2125 // every cv for 0 < k < j.
Douglas Gregor58281352011-01-27 00:58:17 +00002126 if (!CStyle && FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002127 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002128 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002129
Douglas Gregor9a657932008-10-21 23:43:52 +00002130 // Keep track of whether all prior cv-qualifiers in the "to" type
2131 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002132 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00002133 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002134 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002135
2136 // We are left with FromType and ToType being the pointee types
2137 // after unwrapping the original FromType and ToType the same number
2138 // of types. If we unwrapped any pointers, and if FromType and
2139 // ToType have the same unqualified type (since we checked
2140 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002141 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002142}
2143
Douglas Gregor576e98c2009-01-30 23:27:23 +00002144/// Determines whether there is a user-defined conversion sequence
2145/// (C++ [over.ics.user]) that converts expression From to the type
2146/// ToType. If such a conversion exists, User will contain the
2147/// user-defined conversion sequence that performs such a conversion
2148/// and this routine will return true. Otherwise, this routine returns
2149/// false and User is unspecified.
2150///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002151/// \param AllowExplicit true if the conversion should consider C++0x
2152/// "explicit" conversion functions as well as non-explicit conversion
2153/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002154static OverloadingResult
2155IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2156 UserDefinedConversionSequence& User,
2157 OverloadCandidateSet& CandidateSet,
2158 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002159 // Whether we will only visit constructors.
2160 bool ConstructorsOnly = false;
2161
2162 // If the type we are conversion to is a class type, enumerate its
2163 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002164 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002165 // C++ [over.match.ctor]p1:
2166 // When objects of class type are direct-initialized (8.5), or
2167 // copy-initialized from an expression of the same or a
2168 // derived class type (8.5), overload resolution selects the
2169 // constructor. [...] For copy-initialization, the candidate
2170 // functions are all the converting constructors (12.3.1) of
2171 // that class. The argument list is the expression-list within
2172 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002173 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002174 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002175 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002176 ConstructorsOnly = true;
2177
John McCall5c32be02010-08-24 20:38:10 +00002178 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002179 // We're not going to find any constructors.
2180 } else if (CXXRecordDecl *ToRecordDecl
2181 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002182 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002183 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002184 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002185 NamedDecl *D = *Con;
2186 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2187
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002188 // Find the constructor (which may be a template).
2189 CXXConstructorDecl *Constructor = 0;
2190 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002191 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002192 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002193 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002194 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2195 else
John McCalla0296f72010-03-19 07:35:19 +00002196 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002197
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002198 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002199 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002200 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002201 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2202 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002203 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002204 /*SuppressUserConversions=*/
2205 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002206 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002207 // Allow one user-defined conversion when user specifies a
2208 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002209 S.AddOverloadCandidate(Constructor, FoundDecl,
2210 &From, 1, CandidateSet,
2211 /*SuppressUserConversions=*/
2212 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002213 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002214 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002215 }
2216 }
2217
Douglas Gregor5ab11652010-04-17 22:01:05 +00002218 // Enumerate conversion functions, if we're allowed to.
2219 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002220 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2221 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002222 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002223 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002224 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002225 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002226 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2227 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002228 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002229 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002230 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002231 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002232 DeclAccessPair FoundDecl = I.getPair();
2233 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002234 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2235 if (isa<UsingShadowDecl>(D))
2236 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2237
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002238 CXXConversionDecl *Conv;
2239 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002240 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2241 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002242 else
John McCallda4458e2010-03-31 01:36:47 +00002243 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002244
2245 if (AllowExplicit || !Conv->isExplicit()) {
2246 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002247 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2248 ActingContext, From, ToType,
2249 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002250 else
John McCall5c32be02010-08-24 20:38:10 +00002251 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2252 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002253 }
2254 }
2255 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002256 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002257
2258 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002259 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002260 case OR_Success:
2261 // Record the standard conversion we used and the conversion function.
2262 if (CXXConstructorDecl *Constructor
2263 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002264 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2265
John McCall5c32be02010-08-24 20:38:10 +00002266 // C++ [over.ics.user]p1:
2267 // If the user-defined conversion is specified by a
2268 // constructor (12.3.1), the initial standard conversion
2269 // sequence converts the source type to the type required by
2270 // the argument of the constructor.
2271 //
2272 QualType ThisType = Constructor->getThisType(S.Context);
2273 if (Best->Conversions[0].isEllipsis())
2274 User.EllipsisConversion = true;
2275 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002276 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002277 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002278 }
John McCall5c32be02010-08-24 20:38:10 +00002279 User.ConversionFunction = Constructor;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002280 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002281 User.After.setAsIdentityConversion();
2282 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2283 User.After.setAllToTypes(ToType);
2284 return OR_Success;
2285 } else if (CXXConversionDecl *Conversion
2286 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002287 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2288
John McCall5c32be02010-08-24 20:38:10 +00002289 // C++ [over.ics.user]p1:
2290 //
2291 // [...] If the user-defined conversion is specified by a
2292 // conversion function (12.3.2), the initial standard
2293 // conversion sequence converts the source type to the
2294 // implicit object parameter of the conversion function.
2295 User.Before = Best->Conversions[0].Standard;
2296 User.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002297 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002298 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002299
John McCall5c32be02010-08-24 20:38:10 +00002300 // C++ [over.ics.user]p2:
2301 // The second standard conversion sequence converts the
2302 // result of the user-defined conversion to the target type
2303 // for the sequence. Since an implicit conversion sequence
2304 // is an initialization, the special rules for
2305 // initialization by user-defined conversion apply when
2306 // selecting the best user-defined conversion for a
2307 // user-defined conversion sequence (see 13.3.3 and
2308 // 13.3.3.1).
2309 User.After = Best->FinalConversion;
2310 return OR_Success;
2311 } else {
2312 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002313 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002314 }
2315
John McCall5c32be02010-08-24 20:38:10 +00002316 case OR_No_Viable_Function:
2317 return OR_No_Viable_Function;
2318 case OR_Deleted:
2319 // No conversion here! We're done.
2320 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002321
John McCall5c32be02010-08-24 20:38:10 +00002322 case OR_Ambiguous:
2323 return OR_Ambiguous;
2324 }
2325
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002326 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002327}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002328
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002329bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002330Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002331 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002332 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002333 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002334 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002335 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002336 if (OvResult == OR_Ambiguous)
2337 Diag(From->getSourceRange().getBegin(),
2338 diag::err_typecheck_ambiguous_condition)
2339 << From->getType() << ToType << From->getSourceRange();
2340 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2341 Diag(From->getSourceRange().getBegin(),
2342 diag::err_typecheck_nonviable_condition)
2343 << From->getType() << ToType << From->getSourceRange();
2344 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002345 return false;
John McCall5c32be02010-08-24 20:38:10 +00002346 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002347 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002348}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002349
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002350/// CompareImplicitConversionSequences - Compare two implicit
2351/// conversion sequences to determine whether one is better than the
2352/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002353static ImplicitConversionSequence::CompareKind
2354CompareImplicitConversionSequences(Sema &S,
2355 const ImplicitConversionSequence& ICS1,
2356 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002357{
2358 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2359 // conversion sequences (as defined in 13.3.3.1)
2360 // -- a standard conversion sequence (13.3.3.1.1) is a better
2361 // conversion sequence than a user-defined conversion sequence or
2362 // an ellipsis conversion sequence, and
2363 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2364 // conversion sequence than an ellipsis conversion sequence
2365 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002366 //
John McCall0d1da222010-01-12 00:44:57 +00002367 // C++0x [over.best.ics]p10:
2368 // For the purpose of ranking implicit conversion sequences as
2369 // described in 13.3.3.2, the ambiguous conversion sequence is
2370 // treated as a user-defined sequence that is indistinguishable
2371 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002372 if (ICS1.getKindRank() < ICS2.getKindRank())
2373 return ImplicitConversionSequence::Better;
2374 else if (ICS2.getKindRank() < ICS1.getKindRank())
2375 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002376
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002377 // The following checks require both conversion sequences to be of
2378 // the same kind.
2379 if (ICS1.getKind() != ICS2.getKind())
2380 return ImplicitConversionSequence::Indistinguishable;
2381
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002382 // Two implicit conversion sequences of the same form are
2383 // indistinguishable conversion sequences unless one of the
2384 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002385 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002386 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002387 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002388 // User-defined conversion sequence U1 is a better conversion
2389 // sequence than another user-defined conversion sequence U2 if
2390 // they contain the same user-defined conversion function or
2391 // constructor and if the second standard conversion sequence of
2392 // U1 is better than the second standard conversion sequence of
2393 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002394 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002395 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002396 return CompareStandardConversionSequences(S,
2397 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002398 ICS2.UserDefined.After);
2399 }
2400
2401 return ImplicitConversionSequence::Indistinguishable;
2402}
2403
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002404static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2405 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2406 Qualifiers Quals;
2407 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002408 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002409 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002410
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002411 return Context.hasSameUnqualifiedType(T1, T2);
2412}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002413
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002414// Per 13.3.3.2p3, compare the given standard conversion sequences to
2415// determine if one is a proper subset of the other.
2416static ImplicitConversionSequence::CompareKind
2417compareStandardConversionSubsets(ASTContext &Context,
2418 const StandardConversionSequence& SCS1,
2419 const StandardConversionSequence& SCS2) {
2420 ImplicitConversionSequence::CompareKind Result
2421 = ImplicitConversionSequence::Indistinguishable;
2422
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002423 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002424 // any non-identity conversion sequence
2425 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2426 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2427 return ImplicitConversionSequence::Better;
2428 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2429 return ImplicitConversionSequence::Worse;
2430 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002431
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002432 if (SCS1.Second != SCS2.Second) {
2433 if (SCS1.Second == ICK_Identity)
2434 Result = ImplicitConversionSequence::Better;
2435 else if (SCS2.Second == ICK_Identity)
2436 Result = ImplicitConversionSequence::Worse;
2437 else
2438 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002439 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002440 return ImplicitConversionSequence::Indistinguishable;
2441
2442 if (SCS1.Third == SCS2.Third) {
2443 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2444 : ImplicitConversionSequence::Indistinguishable;
2445 }
2446
2447 if (SCS1.Third == ICK_Identity)
2448 return Result == ImplicitConversionSequence::Worse
2449 ? ImplicitConversionSequence::Indistinguishable
2450 : ImplicitConversionSequence::Better;
2451
2452 if (SCS2.Third == ICK_Identity)
2453 return Result == ImplicitConversionSequence::Better
2454 ? ImplicitConversionSequence::Indistinguishable
2455 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002456
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002457 return ImplicitConversionSequence::Indistinguishable;
2458}
2459
Douglas Gregore696ebb2011-01-26 14:52:12 +00002460/// \brief Determine whether one of the given reference bindings is better
2461/// than the other based on what kind of bindings they are.
2462static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2463 const StandardConversionSequence &SCS2) {
2464 // C++0x [over.ics.rank]p3b4:
2465 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2466 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002467 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002468 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002469 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002470 // reference*.
2471 //
2472 // FIXME: Rvalue references. We're going rogue with the above edits,
2473 // because the semantics in the current C++0x working paper (N3225 at the
2474 // time of this writing) break the standard definition of std::forward
2475 // and std::reference_wrapper when dealing with references to functions.
2476 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002477 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2478 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2479 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002480
Douglas Gregore696ebb2011-01-26 14:52:12 +00002481 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2482 SCS2.IsLvalueReference) ||
2483 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2484 !SCS2.IsLvalueReference);
2485}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002486
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002487/// CompareStandardConversionSequences - Compare two standard
2488/// conversion sequences to determine whether one is better than the
2489/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002490static ImplicitConversionSequence::CompareKind
2491CompareStandardConversionSequences(Sema &S,
2492 const StandardConversionSequence& SCS1,
2493 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002494{
2495 // Standard conversion sequence S1 is a better conversion sequence
2496 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2497
2498 // -- S1 is a proper subsequence of S2 (comparing the conversion
2499 // sequences in the canonical form defined by 13.3.3.1.1,
2500 // excluding any Lvalue Transformation; the identity conversion
2501 // sequence is considered to be a subsequence of any
2502 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002503 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002504 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002505 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002506
2507 // -- the rank of S1 is better than the rank of S2 (by the rules
2508 // defined below), or, if not that,
2509 ImplicitConversionRank Rank1 = SCS1.getRank();
2510 ImplicitConversionRank Rank2 = SCS2.getRank();
2511 if (Rank1 < Rank2)
2512 return ImplicitConversionSequence::Better;
2513 else if (Rank2 < Rank1)
2514 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002515
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002516 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2517 // are indistinguishable unless one of the following rules
2518 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002519
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002520 // A conversion that is not a conversion of a pointer, or
2521 // pointer to member, to bool is better than another conversion
2522 // that is such a conversion.
2523 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2524 return SCS2.isPointerConversionToBool()
2525 ? ImplicitConversionSequence::Better
2526 : ImplicitConversionSequence::Worse;
2527
Douglas Gregor5c407d92008-10-23 00:40:37 +00002528 // C++ [over.ics.rank]p4b2:
2529 //
2530 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002531 // conversion of B* to A* is better than conversion of B* to
2532 // void*, and conversion of A* to void* is better than conversion
2533 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002534 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002535 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002536 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002537 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002538 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2539 // Exactly one of the conversion sequences is a conversion to
2540 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002541 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2542 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002543 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2544 // Neither conversion sequence converts to a void pointer; compare
2545 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002546 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002547 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002548 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002549 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2550 // Both conversion sequences are conversions to void
2551 // pointers. Compare the source types to determine if there's an
2552 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002553 QualType FromType1 = SCS1.getFromType();
2554 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002555
2556 // Adjust the types we're converting from via the array-to-pointer
2557 // conversion, if we need to.
2558 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002559 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002560 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002561 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002562
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002563 QualType FromPointee1
2564 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2565 QualType FromPointee2
2566 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002567
John McCall5c32be02010-08-24 20:38:10 +00002568 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002569 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002570 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002571 return ImplicitConversionSequence::Worse;
2572
2573 // Objective-C++: If one interface is more specific than the
2574 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002575 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2576 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002577 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002578 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002579 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002580 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002581 return ImplicitConversionSequence::Worse;
2582 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002583 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002584
2585 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2586 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002587 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002588 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002589 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002590
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002591 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002592 // Check for a better reference binding based on the kind of bindings.
2593 if (isBetterReferenceBindingKind(SCS1, SCS2))
2594 return ImplicitConversionSequence::Better;
2595 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2596 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002597
Sebastian Redlb28b4072009-03-22 23:49:27 +00002598 // C++ [over.ics.rank]p3b4:
2599 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2600 // which the references refer are the same type except for
2601 // top-level cv-qualifiers, and the type to which the reference
2602 // initialized by S2 refers is more cv-qualified than the type
2603 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002604 QualType T1 = SCS1.getToType(2);
2605 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002606 T1 = S.Context.getCanonicalType(T1);
2607 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002608 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002609 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2610 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002611 if (UnqualT1 == UnqualT2) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00002612 // If the type is an array type, promote the element qualifiers to the
2613 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002614 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002615 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002616 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002617 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002618 if (T2.isMoreQualifiedThan(T1))
2619 return ImplicitConversionSequence::Better;
2620 else if (T1.isMoreQualifiedThan(T2))
2621 return ImplicitConversionSequence::Worse;
2622 }
2623 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002624
2625 return ImplicitConversionSequence::Indistinguishable;
2626}
2627
2628/// CompareQualificationConversions - Compares two standard conversion
2629/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002630/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2631ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002632CompareQualificationConversions(Sema &S,
2633 const StandardConversionSequence& SCS1,
2634 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002635 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002636 // -- S1 and S2 differ only in their qualification conversion and
2637 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2638 // cv-qualification signature of type T1 is a proper subset of
2639 // the cv-qualification signature of type T2, and S1 is not the
2640 // deprecated string literal array-to-pointer conversion (4.2).
2641 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2642 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2643 return ImplicitConversionSequence::Indistinguishable;
2644
2645 // FIXME: the example in the standard doesn't use a qualification
2646 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002647 QualType T1 = SCS1.getToType(2);
2648 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002649 T1 = S.Context.getCanonicalType(T1);
2650 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002651 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002652 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2653 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002654
2655 // If the types are the same, we won't learn anything by unwrapped
2656 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002657 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002658 return ImplicitConversionSequence::Indistinguishable;
2659
Chandler Carruth607f38e2009-12-29 07:16:59 +00002660 // If the type is an array type, promote the element qualifiers to the type
2661 // for comparison.
2662 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002663 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002664 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002665 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002666
Mike Stump11289f42009-09-09 15:08:12 +00002667 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002668 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002669 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002670 // Within each iteration of the loop, we check the qualifiers to
2671 // determine if this still looks like a qualification
2672 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002673 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002674 // until there are no more pointers or pointers-to-members left
2675 // to unwrap. This essentially mimics what
2676 // IsQualificationConversion does, but here we're checking for a
2677 // strict subset of qualifiers.
2678 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2679 // The qualifiers are the same, so this doesn't tell us anything
2680 // about how the sequences rank.
2681 ;
2682 else if (T2.isMoreQualifiedThan(T1)) {
2683 // T1 has fewer qualifiers, so it could be the better sequence.
2684 if (Result == ImplicitConversionSequence::Worse)
2685 // Neither has qualifiers that are a subset of the other's
2686 // qualifiers.
2687 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002688
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002689 Result = ImplicitConversionSequence::Better;
2690 } else if (T1.isMoreQualifiedThan(T2)) {
2691 // T2 has fewer qualifiers, so it could be the better sequence.
2692 if (Result == ImplicitConversionSequence::Better)
2693 // Neither has qualifiers that are a subset of the other's
2694 // qualifiers.
2695 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002696
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002697 Result = ImplicitConversionSequence::Worse;
2698 } else {
2699 // Qualifiers are disjoint.
2700 return ImplicitConversionSequence::Indistinguishable;
2701 }
2702
2703 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002704 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002705 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002706 }
2707
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002708 // Check that the winning standard conversion sequence isn't using
2709 // the deprecated string literal array to pointer conversion.
2710 switch (Result) {
2711 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002712 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002713 Result = ImplicitConversionSequence::Indistinguishable;
2714 break;
2715
2716 case ImplicitConversionSequence::Indistinguishable:
2717 break;
2718
2719 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002720 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002721 Result = ImplicitConversionSequence::Indistinguishable;
2722 break;
2723 }
2724
2725 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002726}
2727
Douglas Gregor5c407d92008-10-23 00:40:37 +00002728/// CompareDerivedToBaseConversions - Compares two standard conversion
2729/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002730/// various kinds of derived-to-base conversions (C++
2731/// [over.ics.rank]p4b3). As part of these checks, we also look at
2732/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002733ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002734CompareDerivedToBaseConversions(Sema &S,
2735 const StandardConversionSequence& SCS1,
2736 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002737 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002738 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002739 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002740 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002741
2742 // Adjust the types we're converting from via the array-to-pointer
2743 // conversion, if we need to.
2744 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002745 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002746 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002747 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002748
2749 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002750 FromType1 = S.Context.getCanonicalType(FromType1);
2751 ToType1 = S.Context.getCanonicalType(ToType1);
2752 FromType2 = S.Context.getCanonicalType(FromType2);
2753 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002754
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002755 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002756 //
2757 // If class B is derived directly or indirectly from class A and
2758 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002759 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002760 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002761 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002762 SCS2.Second == ICK_Pointer_Conversion &&
2763 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2764 FromType1->isPointerType() && FromType2->isPointerType() &&
2765 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002766 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002767 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002768 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002769 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002770 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002771 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002772 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002773 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002774
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002775 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002776 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002777 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002778 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002779 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002780 return ImplicitConversionSequence::Worse;
2781 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002782
2783 // -- conversion of B* to A* is better than conversion of C* to A*,
2784 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002785 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002786 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002787 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002788 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00002789 }
2790 } else if (SCS1.Second == ICK_Pointer_Conversion &&
2791 SCS2.Second == ICK_Pointer_Conversion) {
2792 const ObjCObjectPointerType *FromPtr1
2793 = FromType1->getAs<ObjCObjectPointerType>();
2794 const ObjCObjectPointerType *FromPtr2
2795 = FromType2->getAs<ObjCObjectPointerType>();
2796 const ObjCObjectPointerType *ToPtr1
2797 = ToType1->getAs<ObjCObjectPointerType>();
2798 const ObjCObjectPointerType *ToPtr2
2799 = ToType2->getAs<ObjCObjectPointerType>();
2800
2801 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
2802 // Apply the same conversion ranking rules for Objective-C pointer types
2803 // that we do for C++ pointers to class types. However, we employ the
2804 // Objective-C pseudo-subtyping relationship used for assignment of
2805 // Objective-C pointer types.
2806 bool FromAssignLeft
2807 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
2808 bool FromAssignRight
2809 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
2810 bool ToAssignLeft
2811 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
2812 bool ToAssignRight
2813 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
2814
2815 // A conversion to an a non-id object pointer type or qualified 'id'
2816 // type is better than a conversion to 'id'.
2817 if (ToPtr1->isObjCIdType() &&
2818 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
2819 return ImplicitConversionSequence::Worse;
2820 if (ToPtr2->isObjCIdType() &&
2821 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
2822 return ImplicitConversionSequence::Better;
2823
2824 // A conversion to a non-id object pointer type is better than a
2825 // conversion to a qualified 'id' type
2826 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
2827 return ImplicitConversionSequence::Worse;
2828 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
2829 return ImplicitConversionSequence::Better;
2830
2831 // A conversion to an a non-Class object pointer type or qualified 'Class'
2832 // type is better than a conversion to 'Class'.
2833 if (ToPtr1->isObjCClassType() &&
2834 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
2835 return ImplicitConversionSequence::Worse;
2836 if (ToPtr2->isObjCClassType() &&
2837 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
2838 return ImplicitConversionSequence::Better;
2839
2840 // A conversion to a non-Class object pointer type is better than a
2841 // conversion to a qualified 'Class' type.
2842 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
2843 return ImplicitConversionSequence::Worse;
2844 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
2845 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00002846
Douglas Gregor058d3de2011-01-31 18:51:41 +00002847 // -- "conversion of C* to B* is better than conversion of C* to A*,"
2848 if (S.Context.hasSameType(FromType1, FromType2) &&
2849 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
2850 (ToAssignLeft != ToAssignRight))
2851 return ToAssignLeft? ImplicitConversionSequence::Worse
2852 : ImplicitConversionSequence::Better;
2853
2854 // -- "conversion of B* to A* is better than conversion of C* to A*,"
2855 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
2856 (FromAssignLeft != FromAssignRight))
2857 return FromAssignLeft? ImplicitConversionSequence::Better
2858 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002859 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002860 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00002861
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002862 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002863 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2864 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2865 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002866 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002867 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002868 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002869 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002870 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002871 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002872 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002873 ToType2->getAs<MemberPointerType>();
2874 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2875 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2876 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2877 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2878 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2879 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2880 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2881 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002882 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002883 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002884 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002885 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002886 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002887 return ImplicitConversionSequence::Better;
2888 }
2889 // conversion of B::* to C::* is better than conversion of A::* to C::*
2890 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002891 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002892 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002893 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002894 return ImplicitConversionSequence::Worse;
2895 }
2896 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002897
Douglas Gregor5ab11652010-04-17 22:01:05 +00002898 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002899 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002900 // -- binding of an expression of type C to a reference of type
2901 // B& is better than binding an expression of type C to a
2902 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002903 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2904 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2905 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002906 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002907 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002908 return ImplicitConversionSequence::Worse;
2909 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002910
Douglas Gregor2fe98832008-11-03 19:09:14 +00002911 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002912 // -- binding of an expression of type B to a reference of type
2913 // A& is better than binding an expression of type C to a
2914 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002915 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2916 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2917 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002918 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002919 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002920 return ImplicitConversionSequence::Worse;
2921 }
2922 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002923
Douglas Gregor5c407d92008-10-23 00:40:37 +00002924 return ImplicitConversionSequence::Indistinguishable;
2925}
2926
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002927/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2928/// determine whether they are reference-related,
2929/// reference-compatible, reference-compatible with added
2930/// qualification, or incompatible, for use in C++ initialization by
2931/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2932/// type, and the first type (T1) is the pointee type of the reference
2933/// type being initialized.
2934Sema::ReferenceCompareResult
2935Sema::CompareReferenceRelationship(SourceLocation Loc,
2936 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002937 bool &DerivedToBase,
2938 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002939 assert(!OrigT1->isReferenceType() &&
2940 "T1 must be the pointee type of the reference type");
2941 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2942
2943 QualType T1 = Context.getCanonicalType(OrigT1);
2944 QualType T2 = Context.getCanonicalType(OrigT2);
2945 Qualifiers T1Quals, T2Quals;
2946 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2947 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2948
2949 // C++ [dcl.init.ref]p4:
2950 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2951 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2952 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002953 DerivedToBase = false;
2954 ObjCConversion = false;
2955 if (UnqualT1 == UnqualT2) {
2956 // Nothing to do.
2957 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002958 IsDerivedFrom(UnqualT2, UnqualT1))
2959 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002960 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2961 UnqualT2->isObjCObjectOrInterfaceType() &&
2962 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2963 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002964 else
2965 return Ref_Incompatible;
2966
2967 // At this point, we know that T1 and T2 are reference-related (at
2968 // least).
2969
2970 // If the type is an array type, promote the element qualifiers to the type
2971 // for comparison.
2972 if (isa<ArrayType>(T1) && T1Quals)
2973 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2974 if (isa<ArrayType>(T2) && T2Quals)
2975 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2976
2977 // C++ [dcl.init.ref]p4:
2978 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2979 // reference-related to T2 and cv1 is the same cv-qualification
2980 // as, or greater cv-qualification than, cv2. For purposes of
2981 // overload resolution, cases for which cv1 is greater
2982 // cv-qualification than cv2 are identified as
2983 // reference-compatible with added qualification (see 13.3.3.2).
2984 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2985 return Ref_Compatible;
2986 else if (T1.isMoreQualifiedThan(T2))
2987 return Ref_Compatible_With_Added_Qualification;
2988 else
2989 return Ref_Related;
2990}
2991
Douglas Gregor836a7e82010-08-11 02:15:33 +00002992/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002993/// with DeclType. Return true if something definite is found.
2994static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002995FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2996 QualType DeclType, SourceLocation DeclLoc,
2997 Expr *Init, QualType T2, bool AllowRvalues,
2998 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002999 assert(T2->isRecordType() && "Can only find conversions of record types.");
3000 CXXRecordDecl *T2RecordDecl
3001 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3002
3003 OverloadCandidateSet CandidateSet(DeclLoc);
3004 const UnresolvedSetImpl *Conversions
3005 = T2RecordDecl->getVisibleConversionFunctions();
3006 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3007 E = Conversions->end(); I != E; ++I) {
3008 NamedDecl *D = *I;
3009 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3010 if (isa<UsingShadowDecl>(D))
3011 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3012
3013 FunctionTemplateDecl *ConvTemplate
3014 = dyn_cast<FunctionTemplateDecl>(D);
3015 CXXConversionDecl *Conv;
3016 if (ConvTemplate)
3017 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3018 else
3019 Conv = cast<CXXConversionDecl>(D);
3020
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003021 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003022 // explicit conversions, skip it.
3023 if (!AllowExplicit && Conv->isExplicit())
3024 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003025
Douglas Gregor836a7e82010-08-11 02:15:33 +00003026 if (AllowRvalues) {
3027 bool DerivedToBase = false;
3028 bool ObjCConversion = false;
3029 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003030 S.CompareReferenceRelationship(
3031 DeclLoc,
3032 Conv->getConversionType().getNonReferenceType()
3033 .getUnqualifiedType(),
3034 DeclType.getNonReferenceType().getUnqualifiedType(),
3035 DerivedToBase, ObjCConversion) ==
3036 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003037 continue;
3038 } else {
3039 // If the conversion function doesn't return a reference type,
3040 // it can't be considered for this conversion. An rvalue reference
3041 // is only acceptable if its referencee is a function type.
3042
3043 const ReferenceType *RefType =
3044 Conv->getConversionType()->getAs<ReferenceType>();
3045 if (!RefType ||
3046 (!RefType->isLValueReferenceType() &&
3047 !RefType->getPointeeType()->isFunctionType()))
3048 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003049 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003050
Douglas Gregor836a7e82010-08-11 02:15:33 +00003051 if (ConvTemplate)
3052 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003053 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003054 else
3055 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003056 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003057 }
3058
3059 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003060 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003061 case OR_Success:
3062 // C++ [over.ics.ref]p1:
3063 //
3064 // [...] If the parameter binds directly to the result of
3065 // applying a conversion function to the argument
3066 // expression, the implicit conversion sequence is a
3067 // user-defined conversion sequence (13.3.3.1.2), with the
3068 // second standard conversion sequence either an identity
3069 // conversion or, if the conversion function returns an
3070 // entity of a type that is a derived class of the parameter
3071 // type, a derived-to-base Conversion.
3072 if (!Best->FinalConversion.DirectBinding)
3073 return false;
3074
Chandler Carruth30141632011-02-25 19:41:05 +00003075 if (Best->Function)
3076 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003077 ICS.setUserDefined();
3078 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3079 ICS.UserDefined.After = Best->FinalConversion;
3080 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003081 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redld92badf2010-06-30 18:13:39 +00003082 ICS.UserDefined.EllipsisConversion = false;
3083 assert(ICS.UserDefined.After.ReferenceBinding &&
3084 ICS.UserDefined.After.DirectBinding &&
3085 "Expected a direct reference binding!");
3086 return true;
3087
3088 case OR_Ambiguous:
3089 ICS.setAmbiguous();
3090 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3091 Cand != CandidateSet.end(); ++Cand)
3092 if (Cand->Viable)
3093 ICS.Ambiguous.addConversion(Cand->Function);
3094 return true;
3095
3096 case OR_No_Viable_Function:
3097 case OR_Deleted:
3098 // There was no suitable conversion, or we found a deleted
3099 // conversion; continue with other checks.
3100 return false;
3101 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003102
Eric Christopheraba9fb22010-06-30 18:36:32 +00003103 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003104}
3105
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003106/// \brief Compute an implicit conversion sequence for reference
3107/// initialization.
3108static ImplicitConversionSequence
3109TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3110 SourceLocation DeclLoc,
3111 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003112 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003113 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3114
3115 // Most paths end in a failed conversion.
3116 ImplicitConversionSequence ICS;
3117 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3118
3119 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3120 QualType T2 = Init->getType();
3121
3122 // If the initializer is the address of an overloaded function, try
3123 // to resolve the overloaded function. If all goes well, T2 is the
3124 // type of the resulting function.
3125 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3126 DeclAccessPair Found;
3127 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3128 false, Found))
3129 T2 = Fn->getType();
3130 }
3131
3132 // Compute some basic properties of the types and the initializer.
3133 bool isRValRef = DeclType->isRValueReferenceType();
3134 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003135 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003136 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003137 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003138 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
3139 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003140
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003141
Sebastian Redld92badf2010-06-30 18:13:39 +00003142 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003143 // A reference to type "cv1 T1" is initialized by an expression
3144 // of type "cv2 T2" as follows:
3145
Sebastian Redld92badf2010-06-30 18:13:39 +00003146 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003147 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003148 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3149 // reference-compatible with "cv2 T2," or
3150 //
3151 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3152 if (InitCategory.isLValue() &&
3153 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003154 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003155 // When a parameter of reference type binds directly (8.5.3)
3156 // to an argument expression, the implicit conversion sequence
3157 // is the identity conversion, unless the argument expression
3158 // has a type that is a derived class of the parameter type,
3159 // in which case the implicit conversion sequence is a
3160 // derived-to-base Conversion (13.3.3.1).
3161 ICS.setStandard();
3162 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003163 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3164 : ObjCConversion? ICK_Compatible_Conversion
3165 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003166 ICS.Standard.Third = ICK_Identity;
3167 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3168 ICS.Standard.setToType(0, T2);
3169 ICS.Standard.setToType(1, T1);
3170 ICS.Standard.setToType(2, T1);
3171 ICS.Standard.ReferenceBinding = true;
3172 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003173 ICS.Standard.IsLvalueReference = !isRValRef;
3174 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3175 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003176 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003177 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003178
Sebastian Redld92badf2010-06-30 18:13:39 +00003179 // Nothing more to do: the inaccessibility/ambiguity check for
3180 // derived-to-base conversions is suppressed when we're
3181 // computing the implicit conversion sequence (C++
3182 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003183 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003184 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003185
Sebastian Redld92badf2010-06-30 18:13:39 +00003186 // -- has a class type (i.e., T2 is a class type), where T1 is
3187 // not reference-related to T2, and can be implicitly
3188 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3189 // is reference-compatible with "cv3 T3" 92) (this
3190 // conversion is selected by enumerating the applicable
3191 // conversion functions (13.3.1.6) and choosing the best
3192 // one through overload resolution (13.3)),
3193 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003194 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003195 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003196 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3197 Init, T2, /*AllowRvalues=*/false,
3198 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003199 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003200 }
3201 }
3202
Sebastian Redld92badf2010-06-30 18:13:39 +00003203 // -- Otherwise, the reference shall be an lvalue reference to a
3204 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003205 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003206 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003207 // We actually handle one oddity of C++ [over.ics.ref] at this
3208 // point, which is that, due to p2 (which short-circuits reference
3209 // binding by only attempting a simple conversion for non-direct
3210 // bindings) and p3's strange wording, we allow a const volatile
3211 // reference to bind to an rvalue. Hence the check for the presence
3212 // of "const" rather than checking for "const" being the only
3213 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003214 // This is also the point where rvalue references and lvalue inits no longer
3215 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003216 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003217 return ICS;
3218
Douglas Gregorf143cd52011-01-24 16:14:37 +00003219 // -- If the initializer expression
3220 //
3221 // -- is an xvalue, class prvalue, array prvalue or function
3222 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3223 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3224 (InitCategory.isXValue() ||
3225 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3226 (InitCategory.isLValue() && T2->isFunctionType()))) {
3227 ICS.setStandard();
3228 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003229 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003230 : ObjCConversion? ICK_Compatible_Conversion
3231 : ICK_Identity;
3232 ICS.Standard.Third = ICK_Identity;
3233 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3234 ICS.Standard.setToType(0, T2);
3235 ICS.Standard.setToType(1, T1);
3236 ICS.Standard.setToType(2, T1);
3237 ICS.Standard.ReferenceBinding = true;
3238 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3239 // binding unless we're binding to a class prvalue.
3240 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3241 // allow the use of rvalue references in C++98/03 for the benefit of
3242 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003243 ICS.Standard.DirectBinding =
3244 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003245 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003246 ICS.Standard.IsLvalueReference = !isRValRef;
3247 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003248 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003249 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003250 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003251 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003252 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003253
Douglas Gregorf143cd52011-01-24 16:14:37 +00003254 // -- has a class type (i.e., T2 is a class type), where T1 is not
3255 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003256 // an xvalue, class prvalue, or function lvalue of type
3257 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003258 // "cv3 T3",
3259 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003260 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003261 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003262 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003263 // class subobject).
3264 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003265 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003266 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3267 Init, T2, /*AllowRvalues=*/true,
3268 AllowExplicit)) {
3269 // In the second case, if the reference is an rvalue reference
3270 // and the second standard conversion sequence of the
3271 // user-defined conversion sequence includes an lvalue-to-rvalue
3272 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003273 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003274 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3275 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3276
Douglas Gregor95273c32011-01-21 16:36:05 +00003277 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003278 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003279
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003280 // -- Otherwise, a temporary of type "cv1 T1" is created and
3281 // initialized from the initializer expression using the
3282 // rules for a non-reference copy initialization (8.5). The
3283 // reference is then bound to the temporary. If T1 is
3284 // reference-related to T2, cv1 must be the same
3285 // cv-qualification as, or greater cv-qualification than,
3286 // cv2; otherwise, the program is ill-formed.
3287 if (RefRelationship == Sema::Ref_Related) {
3288 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3289 // we would be reference-compatible or reference-compatible with
3290 // added qualification. But that wasn't the case, so the reference
3291 // initialization fails.
3292 return ICS;
3293 }
3294
3295 // If at least one of the types is a class type, the types are not
3296 // related, and we aren't allowed any user conversions, the
3297 // reference binding fails. This case is important for breaking
3298 // recursion, since TryImplicitConversion below will attempt to
3299 // create a temporary through the use of a copy constructor.
3300 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3301 (T1->isRecordType() || T2->isRecordType()))
3302 return ICS;
3303
Douglas Gregorcba72b12011-01-21 05:18:22 +00003304 // If T1 is reference-related to T2 and the reference is an rvalue
3305 // reference, the initializer expression shall not be an lvalue.
3306 if (RefRelationship >= Sema::Ref_Related &&
3307 isRValRef && Init->Classify(S.Context).isLValue())
3308 return ICS;
3309
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003310 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003311 // When a parameter of reference type is not bound directly to
3312 // an argument expression, the conversion sequence is the one
3313 // required to convert the argument expression to the
3314 // underlying type of the reference according to
3315 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3316 // to copy-initializing a temporary of the underlying type with
3317 // the argument expression. Any difference in top-level
3318 // cv-qualification is subsumed by the initialization itself
3319 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003320 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3321 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003322 /*InOverloadResolution=*/false,
3323 /*CStyle=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003324
3325 // Of course, that's still a reference binding.
3326 if (ICS.isStandard()) {
3327 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003328 ICS.Standard.IsLvalueReference = !isRValRef;
3329 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3330 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003331 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003332 } else if (ICS.isUserDefined()) {
3333 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003334 ICS.Standard.IsLvalueReference = !isRValRef;
3335 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3336 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003337 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003338 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003339
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003340 return ICS;
3341}
3342
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003343/// TryCopyInitialization - Try to copy-initialize a value of type
3344/// ToType from the expression From. Return the implicit conversion
3345/// sequence required to pass this argument, which may be a bad
3346/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003347/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003348/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003349static ImplicitConversionSequence
3350TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003351 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003352 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003353 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003354 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003355 /*FIXME:*/From->getLocStart(),
3356 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003357 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003358
John McCall5c32be02010-08-24 20:38:10 +00003359 return TryImplicitConversion(S, From, ToType,
3360 SuppressUserConversions,
3361 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003362 InOverloadResolution,
3363 /*CStyle=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003364}
3365
Douglas Gregor436424c2008-11-18 23:14:02 +00003366/// TryObjectArgumentInitialization - Try to initialize the object
3367/// parameter of the given member function (@c Method) from the
3368/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003369static ImplicitConversionSequence
3370TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003371 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003372 CXXMethodDecl *Method,
3373 CXXRecordDecl *ActingContext) {
3374 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003375 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3376 // const volatile object.
3377 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3378 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003379 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003380
3381 // Set up the conversion sequence as a "bad" conversion, to allow us
3382 // to exit early.
3383 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003384
3385 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003386 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003387 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003388 FromType = PT->getPointeeType();
3389
Douglas Gregor02824322011-01-26 19:30:28 +00003390 // When we had a pointer, it's implicitly dereferenced, so we
3391 // better have an lvalue.
3392 assert(FromClassification.isLValue());
3393 }
3394
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003395 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003396
Douglas Gregor02824322011-01-26 19:30:28 +00003397 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003398 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003399 // parameter is
3400 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003401 // - "lvalue reference to cv X" for functions declared without a
3402 // ref-qualifier or with the & ref-qualifier
3403 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003404 // ref-qualifier
3405 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003406 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003407 // cv-qualification on the member function declaration.
3408 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003409 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003410 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003411 // (C++ [over.match.funcs]p5). We perform a simplified version of
3412 // reference binding here, that allows class rvalues to bind to
3413 // non-constant references.
3414
Douglas Gregor02824322011-01-26 19:30:28 +00003415 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003416 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003417 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003418 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003419 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003420 ICS.setBad(BadConversionSequence::bad_qualifiers,
3421 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003422 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003423 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003424
3425 // Check that we have either the same type or a derived type. It
3426 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003427 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003428 ImplicitConversionKind SecondKind;
3429 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3430 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003431 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003432 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003433 else {
John McCall65eb8792010-02-25 01:37:24 +00003434 ICS.setBad(BadConversionSequence::unrelated_class,
3435 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003436 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003437 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003438
Douglas Gregor02824322011-01-26 19:30:28 +00003439 // Check the ref-qualifier.
3440 switch (Method->getRefQualifier()) {
3441 case RQ_None:
3442 // Do nothing; we don't care about lvalueness or rvalueness.
3443 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003444
Douglas Gregor02824322011-01-26 19:30:28 +00003445 case RQ_LValue:
3446 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3447 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003448 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003449 ImplicitParamType);
3450 return ICS;
3451 }
3452 break;
3453
3454 case RQ_RValue:
3455 if (!FromClassification.isRValue()) {
3456 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003457 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003458 ImplicitParamType);
3459 return ICS;
3460 }
3461 break;
3462 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003463
Douglas Gregor436424c2008-11-18 23:14:02 +00003464 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003465 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003466 ICS.Standard.setAsIdentityConversion();
3467 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003468 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003469 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003470 ICS.Standard.ReferenceBinding = true;
3471 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003472 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003473 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003474 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3475 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3476 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003477 return ICS;
3478}
3479
3480/// PerformObjectArgumentInitialization - Perform initialization of
3481/// the implicit object parameter for the given Method with the given
3482/// expression.
3483bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003484Sema::PerformObjectArgumentInitialization(Expr *&From,
3485 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003486 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003487 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003488 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003489 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003490 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003491
Douglas Gregor02824322011-01-26 19:30:28 +00003492 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003493 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003494 FromRecordType = PT->getPointeeType();
3495 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003496 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003497 } else {
3498 FromRecordType = From->getType();
3499 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003500 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003501 }
3502
John McCall6e9f8f62009-12-03 04:06:58 +00003503 // Note that we always use the true parent context when performing
3504 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003505 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003506 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3507 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003508 if (ICS.isBad()) {
3509 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3510 Qualifiers FromQs = FromRecordType.getQualifiers();
3511 Qualifiers ToQs = DestType.getQualifiers();
3512 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3513 if (CVR) {
3514 Diag(From->getSourceRange().getBegin(),
3515 diag::err_member_function_call_bad_cvr)
3516 << Method->getDeclName() << FromRecordType << (CVR - 1)
3517 << From->getSourceRange();
3518 Diag(Method->getLocation(), diag::note_previous_decl)
3519 << Method->getDeclName();
3520 return true;
3521 }
3522 }
3523
Douglas Gregor436424c2008-11-18 23:14:02 +00003524 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003525 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003526 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003527 }
Mike Stump11289f42009-09-09 15:08:12 +00003528
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003529 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003530 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003531
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003532 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003533 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003534 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003535 return false;
3536}
3537
Douglas Gregor5fb53972009-01-14 15:45:31 +00003538/// TryContextuallyConvertToBool - Attempt to contextually convert the
3539/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003540static ImplicitConversionSequence
3541TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003542 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003543 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003544 // FIXME: Are these flags correct?
3545 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003546 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003547 /*InOverloadResolution=*/false,
3548 /*CStyle=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003549}
3550
3551/// PerformContextuallyConvertToBool - Perform a contextual conversion
3552/// of the expression From to bool (C++0x [conv]p3).
3553bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003554 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003555 if (!ICS.isBad())
3556 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003557
Fariborz Jahanian76197412009-11-18 18:26:29 +00003558 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003559 return Diag(From->getSourceRange().getBegin(),
3560 diag::err_typecheck_bool_condition)
3561 << From->getType() << From->getSourceRange();
3562 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003563}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003564
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003565/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3566/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003567static ImplicitConversionSequence
3568TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3569 QualType Ty = S.Context.getObjCIdType();
3570 return TryImplicitConversion(S, From, Ty,
3571 // FIXME: Are these flags correct?
3572 /*SuppressUserConversions=*/false,
3573 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003574 /*InOverloadResolution=*/false,
3575 /*CStyle=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003576}
John McCall5c32be02010-08-24 20:38:10 +00003577
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003578/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3579/// of the expression From to 'id'.
3580bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003581 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003582 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003583 if (!ICS.isBad())
3584 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3585 return true;
3586}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003587
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003588/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003589/// enumeration type.
3590///
3591/// This routine will attempt to convert an expression of class type to an
3592/// integral or enumeration type, if that class type only has a single
3593/// conversion to an integral or enumeration type.
3594///
Douglas Gregor4799d032010-06-30 00:20:43 +00003595/// \param Loc The source location of the construct that requires the
3596/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003597///
Douglas Gregor4799d032010-06-30 00:20:43 +00003598/// \param FromE The expression we're converting from.
3599///
3600/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3601/// have integral or enumeration type.
3602///
3603/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3604/// incomplete class type.
3605///
3606/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3607/// explicit conversion function (because no implicit conversion functions
3608/// were available). This is a recovery mode.
3609///
3610/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3611/// showing which conversion was picked.
3612///
3613/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3614/// conversion function that could convert to integral or enumeration type.
3615///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003616/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00003617/// usable conversion function.
3618///
3619/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3620/// function, which may be an extension in this case.
3621///
3622/// \returns The expression, converted to an integral or enumeration type if
3623/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003624ExprResult
John McCallb268a282010-08-23 23:25:46 +00003625Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003626 const PartialDiagnostic &NotIntDiag,
3627 const PartialDiagnostic &IncompleteDiag,
3628 const PartialDiagnostic &ExplicitConvDiag,
3629 const PartialDiagnostic &ExplicitConvNote,
3630 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003631 const PartialDiagnostic &AmbigNote,
3632 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003633 // We can't perform any more checking for type-dependent expressions.
3634 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003635 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003636
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003637 // If the expression already has integral or enumeration type, we're golden.
3638 QualType T = From->getType();
3639 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003640 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003641
3642 // FIXME: Check for missing '()' if T is a function type?
3643
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003644 // 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 +00003645 // expression of integral or enumeration type.
3646 const RecordType *RecordTy = T->getAs<RecordType>();
3647 if (!RecordTy || !getLangOptions().CPlusPlus) {
3648 Diag(Loc, NotIntDiag)
3649 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003650 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003651 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003652
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003653 // We must have a complete class type.
3654 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003655 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003656
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003657 // Look for a conversion to an integral or enumeration type.
3658 UnresolvedSet<4> ViableConversions;
3659 UnresolvedSet<4> ExplicitConversions;
3660 const UnresolvedSetImpl *Conversions
3661 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003662
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003663 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003664 E = Conversions->end();
3665 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003666 ++I) {
3667 if (CXXConversionDecl *Conversion
3668 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3669 if (Conversion->getConversionType().getNonReferenceType()
3670 ->isIntegralOrEnumerationType()) {
3671 if (Conversion->isExplicit())
3672 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3673 else
3674 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3675 }
3676 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003677
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003678 switch (ViableConversions.size()) {
3679 case 0:
3680 if (ExplicitConversions.size() == 1) {
3681 DeclAccessPair Found = ExplicitConversions[0];
3682 CXXConversionDecl *Conversion
3683 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003684
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003685 // The user probably meant to invoke the given explicit
3686 // conversion; use it.
3687 QualType ConvTy
3688 = Conversion->getConversionType().getNonReferenceType();
3689 std::string TypeStr;
3690 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003691
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003692 Diag(Loc, ExplicitConvDiag)
3693 << T << ConvTy
3694 << FixItHint::CreateInsertion(From->getLocStart(),
3695 "static_cast<" + TypeStr + ">(")
3696 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3697 ")");
3698 Diag(Conversion->getLocation(), ExplicitConvNote)
3699 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003700
3701 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003702 // explicit conversion function.
3703 if (isSFINAEContext())
3704 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003705
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003706 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00003707 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3708 if (Result.isInvalid())
3709 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003710
Douglas Gregor668443e2011-01-20 00:18:04 +00003711 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003712 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003713
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003714 // We'll complain below about a non-integral condition type.
3715 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003716
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003717 case 1: {
3718 // Apply this conversion.
3719 DeclAccessPair Found = ViableConversions[0];
3720 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003721
Douglas Gregor4799d032010-06-30 00:20:43 +00003722 CXXConversionDecl *Conversion
3723 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3724 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003725 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00003726 if (ConvDiag.getDiagID()) {
3727 if (isSFINAEContext())
3728 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003729
Douglas Gregor4799d032010-06-30 00:20:43 +00003730 Diag(Loc, ConvDiag)
3731 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3732 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003733
Douglas Gregor668443e2011-01-20 00:18:04 +00003734 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003735 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00003736 if (Result.isInvalid())
3737 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003738
Douglas Gregor668443e2011-01-20 00:18:04 +00003739 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003740 break;
3741 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003742
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003743 default:
3744 Diag(Loc, AmbigDiag)
3745 << T << From->getSourceRange();
3746 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3747 CXXConversionDecl *Conv
3748 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3749 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3750 Diag(Conv->getLocation(), AmbigNote)
3751 << ConvTy->isEnumeralType() << ConvTy;
3752 }
John McCallb268a282010-08-23 23:25:46 +00003753 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003754 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003755
Douglas Gregor5823da32010-06-29 23:25:20 +00003756 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003757 Diag(Loc, NotIntDiag)
3758 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003759
John McCallb268a282010-08-23 23:25:46 +00003760 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003761}
3762
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003763/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003764/// candidate functions, using the given function call arguments. If
3765/// @p SuppressUserConversions, then don't allow user-defined
3766/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003767///
3768/// \para PartialOverloading true if we are performing "partial" overloading
3769/// based on an incomplete set of function arguments. This feature is used by
3770/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003771void
3772Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003773 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003774 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003775 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003776 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003777 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003778 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003779 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003780 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003781 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003782 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003783
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003784 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003785 if (!isa<CXXConstructorDecl>(Method)) {
3786 // If we get here, it's because we're calling a member function
3787 // that is named without a member access expression (e.g.,
3788 // "this->f") that was either written explicitly or created
3789 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003790 // function, e.g., X::f(). We use an empty type for the implied
3791 // object argument (C++ [over.call.func]p3), and the acting context
3792 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003793 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003794 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00003795 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003796 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003797 return;
3798 }
3799 // We treat a constructor like a non-member function, since its object
3800 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003801 }
3802
Douglas Gregorff7028a2009-11-13 23:59:09 +00003803 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003804 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003805
Douglas Gregor27381f32009-11-23 12:27:39 +00003806 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003807 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003808
Douglas Gregorffe14e32009-11-14 01:20:54 +00003809 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3810 // C++ [class.copy]p3:
3811 // A member function template is never instantiated to perform the copy
3812 // of a class object to an object of its class type.
3813 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003814 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003815 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003816 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3817 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003818 return;
3819 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003820
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003821 // Add this candidate
3822 CandidateSet.push_back(OverloadCandidate());
3823 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003824 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003825 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003826 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003827 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003828 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003829 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003830
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003831 unsigned NumArgsInProto = Proto->getNumArgs();
3832
3833 // (C++ 13.3.2p2): A candidate function having fewer than m
3834 // parameters is viable only if it has an ellipsis in its parameter
3835 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003836 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00003837 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003838 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003839 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003840 return;
3841 }
3842
3843 // (C++ 13.3.2p2): A candidate function having more than m parameters
3844 // is viable only if the (m+1)st parameter has a default argument
3845 // (8.3.6). For the purposes of overload resolution, the
3846 // parameter list is truncated on the right, so that there are
3847 // exactly m parameters.
3848 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003849 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003850 // Not enough arguments.
3851 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003852 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003853 return;
3854 }
3855
3856 // Determine the implicit conversion sequences for each of the
3857 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003858 Candidate.Conversions.resize(NumArgs);
3859 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3860 if (ArgIdx < NumArgsInProto) {
3861 // (C++ 13.3.2p3): for F to be a viable function, there shall
3862 // exist for each argument an implicit conversion sequence
3863 // (13.3.3.1) that converts that argument to the corresponding
3864 // parameter of F.
3865 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003866 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003867 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003868 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003869 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003870 if (Candidate.Conversions[ArgIdx].isBad()) {
3871 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003872 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003873 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003874 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003875 } else {
3876 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3877 // argument for which there is no corresponding parameter is
3878 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003879 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003880 }
3881 }
3882}
3883
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003884/// \brief Add all of the function declarations in the given function set to
3885/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003886void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003887 Expr **Args, unsigned NumArgs,
3888 OverloadCandidateSet& CandidateSet,
3889 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003890 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003891 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3892 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003893 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003894 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003895 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00003896 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003897 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003898 CandidateSet, SuppressUserConversions);
3899 else
John McCalla0296f72010-03-19 07:35:19 +00003900 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003901 SuppressUserConversions);
3902 } else {
John McCalla0296f72010-03-19 07:35:19 +00003903 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003904 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3905 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003906 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003907 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003908 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003909 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00003910 Args[0]->Classify(Context),
3911 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003912 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003913 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003914 else
John McCalla0296f72010-03-19 07:35:19 +00003915 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003916 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003917 Args, NumArgs, CandidateSet,
3918 SuppressUserConversions);
3919 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003920 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003921}
3922
John McCallf0f1cf02009-11-17 07:50:12 +00003923/// AddMethodCandidate - Adds a named decl (which is some kind of
3924/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003925void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003926 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00003927 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00003928 Expr **Args, unsigned NumArgs,
3929 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003930 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003931 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003932 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003933
3934 if (isa<UsingShadowDecl>(Decl))
3935 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003936
John McCallf0f1cf02009-11-17 07:50:12 +00003937 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3938 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3939 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003940 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3941 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00003942 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003943 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003944 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003945 } else {
John McCalla0296f72010-03-19 07:35:19 +00003946 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00003947 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003948 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003949 }
3950}
3951
Douglas Gregor436424c2008-11-18 23:14:02 +00003952/// AddMethodCandidate - Adds the given C++ member function to the set
3953/// of candidate functions, using the given function call arguments
3954/// and the object argument (@c Object). For example, in a call
3955/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3956/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3957/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003958/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003959void
John McCalla0296f72010-03-19 07:35:19 +00003960Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003961 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00003962 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00003963 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003964 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003965 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003966 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003967 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003968 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003969 assert(!isa<CXXConstructorDecl>(Method) &&
3970 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003971
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003972 if (!CandidateSet.isNewCandidate(Method))
3973 return;
3974
Douglas Gregor27381f32009-11-23 12:27:39 +00003975 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003976 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003977
Douglas Gregor436424c2008-11-18 23:14:02 +00003978 // Add this candidate
3979 CandidateSet.push_back(OverloadCandidate());
3980 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003981 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003982 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003983 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003984 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003985 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00003986
3987 unsigned NumArgsInProto = Proto->getNumArgs();
3988
3989 // (C++ 13.3.2p2): A candidate function having fewer than m
3990 // parameters is viable only if it has an ellipsis in its parameter
3991 // list (8.3.5).
3992 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3993 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003994 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003995 return;
3996 }
3997
3998 // (C++ 13.3.2p2): A candidate function having more than m parameters
3999 // is viable only if the (m+1)st parameter has a default argument
4000 // (8.3.6). For the purposes of overload resolution, the
4001 // parameter list is truncated on the right, so that there are
4002 // exactly m parameters.
4003 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4004 if (NumArgs < MinRequiredArgs) {
4005 // Not enough arguments.
4006 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004007 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004008 return;
4009 }
4010
4011 Candidate.Viable = true;
4012 Candidate.Conversions.resize(NumArgs + 1);
4013
John McCall6e9f8f62009-12-03 04:06:58 +00004014 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004015 // The implicit object argument is ignored.
4016 Candidate.IgnoreObjectArgument = true;
4017 else {
4018 // Determine the implicit conversion sequence for the object
4019 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004020 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004021 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4022 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004023 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004024 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004025 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004026 return;
4027 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004028 }
4029
4030 // Determine the implicit conversion sequences for each of the
4031 // arguments.
4032 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4033 if (ArgIdx < NumArgsInProto) {
4034 // (C++ 13.3.2p3): for F to be a viable function, there shall
4035 // exist for each argument an implicit conversion sequence
4036 // (13.3.3.1) that converts that argument to the corresponding
4037 // parameter of F.
4038 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004039 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004040 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004041 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00004042 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00004043 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004044 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004045 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004046 break;
4047 }
4048 } else {
4049 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4050 // argument for which there is no corresponding parameter is
4051 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004052 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004053 }
4054 }
4055}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004056
Douglas Gregor97628d62009-08-21 00:16:32 +00004057/// \brief Add a C++ member function template as a candidate to the candidate
4058/// set, using template argument deduction to produce an appropriate member
4059/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004060void
Douglas Gregor97628d62009-08-21 00:16:32 +00004061Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004062 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004063 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00004064 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004065 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004066 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004067 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004068 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004069 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004070 if (!CandidateSet.isNewCandidate(MethodTmpl))
4071 return;
4072
Douglas Gregor97628d62009-08-21 00:16:32 +00004073 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004074 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004075 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004076 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004077 // candidate functions in the usual way.113) A given name can refer to one
4078 // or more function templates and also to a set of overloaded non-template
4079 // functions. In such a case, the candidate functions generated from each
4080 // function template are combined with the set of non-template candidate
4081 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004082 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004083 FunctionDecl *Specialization = 0;
4084 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004085 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004086 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004087 CandidateSet.push_back(OverloadCandidate());
4088 OverloadCandidate &Candidate = CandidateSet.back();
4089 Candidate.FoundDecl = FoundDecl;
4090 Candidate.Function = MethodTmpl->getTemplatedDecl();
4091 Candidate.Viable = false;
4092 Candidate.FailureKind = ovl_fail_bad_deduction;
4093 Candidate.IsSurrogate = false;
4094 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004095 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004096 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004097 Info);
4098 return;
4099 }
Mike Stump11289f42009-09-09 15:08:12 +00004100
Douglas Gregor97628d62009-08-21 00:16:32 +00004101 // Add the function template specialization produced by template argument
4102 // deduction as a candidate.
4103 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004104 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004105 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004106 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004107 ActingContext, ObjectType, ObjectClassification,
4108 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004109}
4110
Douglas Gregor05155d82009-08-21 23:19:43 +00004111/// \brief Add a C++ function template specialization as a candidate
4112/// in the candidate set, using template argument deduction to produce
4113/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004114void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004115Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004116 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00004117 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004118 Expr **Args, unsigned NumArgs,
4119 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004120 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004121 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4122 return;
4123
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004124 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004125 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004126 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004127 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004128 // candidate functions in the usual way.113) A given name can refer to one
4129 // or more function templates and also to a set of overloaded non-template
4130 // functions. In such a case, the candidate functions generated from each
4131 // function template are combined with the set of non-template candidate
4132 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004133 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004134 FunctionDecl *Specialization = 0;
4135 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004136 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004137 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004138 CandidateSet.push_back(OverloadCandidate());
4139 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004140 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004141 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4142 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004143 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004144 Candidate.IsSurrogate = false;
4145 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004146 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004147 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004148 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004149 return;
4150 }
Mike Stump11289f42009-09-09 15:08:12 +00004151
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004152 // Add the function template specialization produced by template argument
4153 // deduction as a candidate.
4154 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004155 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004156 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004157}
Mike Stump11289f42009-09-09 15:08:12 +00004158
Douglas Gregora1f013e2008-11-07 22:36:19 +00004159/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004160/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004161/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004162/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004163/// (which may or may not be the same type as the type that the
4164/// conversion function produces).
4165void
4166Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004167 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004168 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004169 Expr *From, QualType ToType,
4170 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004171 assert(!Conversion->getDescribedFunctionTemplate() &&
4172 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004173 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004174 if (!CandidateSet.isNewCandidate(Conversion))
4175 return;
4176
Douglas Gregor27381f32009-11-23 12:27:39 +00004177 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004178 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004179
Douglas Gregora1f013e2008-11-07 22:36:19 +00004180 // Add this candidate
4181 CandidateSet.push_back(OverloadCandidate());
4182 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004183 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004184 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004185 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004186 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004187 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004188 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004189 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004190 Candidate.Viable = true;
4191 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004192 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004193
Douglas Gregor6affc782010-08-19 15:37:02 +00004194 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004195 // For conversion functions, the function is considered to be a member of
4196 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004197 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004198 //
4199 // Determine the implicit conversion sequence for the implicit
4200 // object parameter.
4201 QualType ImplicitParamType = From->getType();
4202 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4203 ImplicitParamType = FromPtrType->getPointeeType();
4204 CXXRecordDecl *ConversionContext
4205 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004206
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004207 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004208 = TryObjectArgumentInitialization(*this, From->getType(),
4209 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004210 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004211
John McCall0d1da222010-01-12 00:44:57 +00004212 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004213 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004214 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004215 return;
4216 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004217
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004218 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004219 // derived to base as such conversions are given Conversion Rank. They only
4220 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4221 QualType FromCanon
4222 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4223 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4224 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4225 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004226 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004227 return;
4228 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004229
Douglas Gregora1f013e2008-11-07 22:36:19 +00004230 // To determine what the conversion from the result of calling the
4231 // conversion function to the type we're eventually trying to
4232 // convert to (ToType), we need to synthesize a call to the
4233 // conversion function and attempt copy initialization from it. This
4234 // makes sure that we get the right semantics with respect to
4235 // lvalues/rvalues and the type. Fortunately, we can allocate this
4236 // call on the stack and we don't need its arguments to be
4237 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004238 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004239 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004240 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4241 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004242 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004243 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004244
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004245 QualType CallResultType
4246 = Conversion->getConversionType().getNonLValueExprType(Context);
4247 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4248 Candidate.Viable = false;
4249 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4250 return;
4251 }
4252
John McCall7decc9e2010-11-18 06:31:45 +00004253 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4254
Mike Stump11289f42009-09-09 15:08:12 +00004255 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004256 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4257 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00004258 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004259 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004260 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004261 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004262 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00004263 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004264
John McCall0d1da222010-01-12 00:44:57 +00004265 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004266 case ImplicitConversionSequence::StandardConversion:
4267 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004268
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004269 // C++ [over.ics.user]p3:
4270 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004271 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004272 // shall have exact match rank.
4273 if (Conversion->getPrimaryTemplate() &&
4274 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4275 Candidate.Viable = false;
4276 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278
Douglas Gregorcba72b12011-01-21 05:18:22 +00004279 // C++0x [dcl.init.ref]p5:
4280 // In the second case, if the reference is an rvalue reference and
4281 // the second standard conversion sequence of the user-defined
4282 // conversion sequence includes an lvalue-to-rvalue conversion, the
4283 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004284 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004285 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4286 Candidate.Viable = false;
4287 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4288 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004289 break;
4290
4291 case ImplicitConversionSequence::BadConversion:
4292 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004293 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004294 break;
4295
4296 default:
Mike Stump11289f42009-09-09 15:08:12 +00004297 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004298 "Can only end up with a standard conversion sequence or failure");
4299 }
4300}
4301
Douglas Gregor05155d82009-08-21 23:19:43 +00004302/// \brief Adds a conversion function template specialization
4303/// candidate to the overload set, using template argument deduction
4304/// to deduce the template arguments of the conversion function
4305/// template from the type that we are converting to (C++
4306/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004307void
Douglas Gregor05155d82009-08-21 23:19:43 +00004308Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004309 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004310 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004311 Expr *From, QualType ToType,
4312 OverloadCandidateSet &CandidateSet) {
4313 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4314 "Only conversion function templates permitted here");
4315
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004316 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4317 return;
4318
John McCallbc077cf2010-02-08 23:07:23 +00004319 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004320 CXXConversionDecl *Specialization = 0;
4321 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004322 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004323 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004324 CandidateSet.push_back(OverloadCandidate());
4325 OverloadCandidate &Candidate = CandidateSet.back();
4326 Candidate.FoundDecl = FoundDecl;
4327 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4328 Candidate.Viable = false;
4329 Candidate.FailureKind = ovl_fail_bad_deduction;
4330 Candidate.IsSurrogate = false;
4331 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004332 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004333 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004334 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004335 return;
4336 }
Mike Stump11289f42009-09-09 15:08:12 +00004337
Douglas Gregor05155d82009-08-21 23:19:43 +00004338 // Add the conversion function template specialization produced by
4339 // template argument deduction as a candidate.
4340 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004341 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004342 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004343}
4344
Douglas Gregorab7897a2008-11-19 22:57:39 +00004345/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4346/// converts the given @c Object to a function pointer via the
4347/// conversion function @c Conversion, and then attempts to call it
4348/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4349/// the type of function that we'll eventually be calling.
4350void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004351 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004352 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004353 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004354 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004355 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004356 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004357 if (!CandidateSet.isNewCandidate(Conversion))
4358 return;
4359
Douglas Gregor27381f32009-11-23 12:27:39 +00004360 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004361 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004362
Douglas Gregorab7897a2008-11-19 22:57:39 +00004363 CandidateSet.push_back(OverloadCandidate());
4364 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004365 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004366 Candidate.Function = 0;
4367 Candidate.Surrogate = Conversion;
4368 Candidate.Viable = true;
4369 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004370 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004371 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004372 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004373
4374 // Determine the implicit conversion sequence for the implicit
4375 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004376 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004377 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004378 Object->Classify(Context),
4379 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004380 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004381 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004382 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004383 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004384 return;
4385 }
4386
4387 // The first conversion is actually a user-defined conversion whose
4388 // first conversion is ObjectInit's standard conversion (which is
4389 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004390 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004391 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004392 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004393 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004394 Candidate.Conversions[0].UserDefined.FoundConversionFunction
Douglas Gregor2bbfba02011-01-20 01:32:05 +00004395 = FoundDecl.getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004396 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004397 = Candidate.Conversions[0].UserDefined.Before;
4398 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4399
Mike Stump11289f42009-09-09 15:08:12 +00004400 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004401 unsigned NumArgsInProto = Proto->getNumArgs();
4402
4403 // (C++ 13.3.2p2): A candidate function having fewer than m
4404 // parameters is viable only if it has an ellipsis in its parameter
4405 // list (8.3.5).
4406 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4407 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004408 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004409 return;
4410 }
4411
4412 // Function types don't have any default arguments, so just check if
4413 // we have enough arguments.
4414 if (NumArgs < NumArgsInProto) {
4415 // Not enough arguments.
4416 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004417 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004418 return;
4419 }
4420
4421 // Determine the implicit conversion sequences for each of the
4422 // arguments.
4423 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4424 if (ArgIdx < NumArgsInProto) {
4425 // (C++ 13.3.2p3): for F to be a viable function, there shall
4426 // exist for each argument an implicit conversion sequence
4427 // (13.3.3.1) that converts that argument to the corresponding
4428 // parameter of F.
4429 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004430 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004431 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004432 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004433 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004434 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004435 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004436 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004437 break;
4438 }
4439 } else {
4440 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4441 // argument for which there is no corresponding parameter is
4442 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004443 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004444 }
4445 }
4446}
4447
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004448/// \brief Add overload candidates for overloaded operators that are
4449/// member functions.
4450///
4451/// Add the overloaded operator candidates that are member functions
4452/// for the operator Op that was used in an operator expression such
4453/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4454/// CandidateSet will store the added overload candidates. (C++
4455/// [over.match.oper]).
4456void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4457 SourceLocation OpLoc,
4458 Expr **Args, unsigned NumArgs,
4459 OverloadCandidateSet& CandidateSet,
4460 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004461 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4462
4463 // C++ [over.match.oper]p3:
4464 // For a unary operator @ with an operand of a type whose
4465 // cv-unqualified version is T1, and for a binary operator @ with
4466 // a left operand of a type whose cv-unqualified version is T1 and
4467 // a right operand of a type whose cv-unqualified version is T2,
4468 // three sets of candidate functions, designated member
4469 // candidates, non-member candidates and built-in candidates, are
4470 // constructed as follows:
4471 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004472
4473 // -- If T1 is a class type, the set of member candidates is the
4474 // result of the qualified lookup of T1::operator@
4475 // (13.3.1.1.1); otherwise, the set of member candidates is
4476 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004477 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004478 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004479 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004480 return;
Mike Stump11289f42009-09-09 15:08:12 +00004481
John McCall27b18f82009-11-17 02:14:36 +00004482 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4483 LookupQualifiedName(Operators, T1Rec->getDecl());
4484 Operators.suppressDiagnostics();
4485
Mike Stump11289f42009-09-09 15:08:12 +00004486 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004487 OperEnd = Operators.end();
4488 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004489 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004490 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004491 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00004492 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004493 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004494 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004495}
4496
Douglas Gregora11693b2008-11-12 17:17:38 +00004497/// AddBuiltinCandidate - Add a candidate for a built-in
4498/// operator. ResultTy and ParamTys are the result and parameter types
4499/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004500/// arguments being passed to the candidate. IsAssignmentOperator
4501/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004502/// operator. NumContextualBoolArguments is the number of arguments
4503/// (at the beginning of the argument list) that will be contextually
4504/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004505void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004506 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004507 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004508 bool IsAssignmentOperator,
4509 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004510 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004511 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004512
Douglas Gregora11693b2008-11-12 17:17:38 +00004513 // Add this candidate
4514 CandidateSet.push_back(OverloadCandidate());
4515 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004516 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004517 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004518 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004519 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004520 Candidate.BuiltinTypes.ResultTy = ResultTy;
4521 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4522 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4523
4524 // Determine the implicit conversion sequences for each of the
4525 // arguments.
4526 Candidate.Viable = true;
4527 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004528 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004529 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004530 // C++ [over.match.oper]p4:
4531 // For the built-in assignment operators, conversions of the
4532 // left operand are restricted as follows:
4533 // -- no temporaries are introduced to hold the left operand, and
4534 // -- no user-defined conversions are applied to the left
4535 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004536 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004537 //
4538 // We block these conversions by turning off user-defined
4539 // conversions, since that is the only way that initialization of
4540 // a reference to a non-class type can occur from something that
4541 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004542 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004543 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004544 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004545 Candidate.Conversions[ArgIdx]
4546 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004547 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004548 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004549 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004550 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004551 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004552 }
John McCall0d1da222010-01-12 00:44:57 +00004553 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004554 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004555 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004556 break;
4557 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004558 }
4559}
4560
4561/// BuiltinCandidateTypeSet - A set of types that will be used for the
4562/// candidate operator functions for built-in operators (C++
4563/// [over.built]). The types are separated into pointer types and
4564/// enumeration types.
4565class BuiltinCandidateTypeSet {
4566 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004567 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004568
4569 /// PointerTypes - The set of pointer types that will be used in the
4570 /// built-in candidates.
4571 TypeSet PointerTypes;
4572
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004573 /// MemberPointerTypes - The set of member pointer types that will be
4574 /// used in the built-in candidates.
4575 TypeSet MemberPointerTypes;
4576
Douglas Gregora11693b2008-11-12 17:17:38 +00004577 /// EnumerationTypes - The set of enumeration types that will be
4578 /// used in the built-in candidates.
4579 TypeSet EnumerationTypes;
4580
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004581 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004582 /// candidates.
4583 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004584
4585 /// \brief A flag indicating non-record types are viable candidates
4586 bool HasNonRecordTypes;
4587
4588 /// \brief A flag indicating whether either arithmetic or enumeration types
4589 /// were present in the candidate set.
4590 bool HasArithmeticOrEnumeralTypes;
4591
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004592 /// Sema - The semantic analysis instance where we are building the
4593 /// candidate type set.
4594 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004595
Douglas Gregora11693b2008-11-12 17:17:38 +00004596 /// Context - The AST context in which we will build the type sets.
4597 ASTContext &Context;
4598
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004599 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4600 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004601 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004602
4603public:
4604 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004605 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004606
Mike Stump11289f42009-09-09 15:08:12 +00004607 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004608 : HasNonRecordTypes(false),
4609 HasArithmeticOrEnumeralTypes(false),
4610 SemaRef(SemaRef),
4611 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004612
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004613 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004614 SourceLocation Loc,
4615 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004616 bool AllowExplicitConversions,
4617 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004618
4619 /// pointer_begin - First pointer type found;
4620 iterator pointer_begin() { return PointerTypes.begin(); }
4621
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004622 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004623 iterator pointer_end() { return PointerTypes.end(); }
4624
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004625 /// member_pointer_begin - First member pointer type found;
4626 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4627
4628 /// member_pointer_end - Past the last member pointer type found;
4629 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4630
Douglas Gregora11693b2008-11-12 17:17:38 +00004631 /// enumeration_begin - First enumeration type found;
4632 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4633
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004634 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004635 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004636
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004637 iterator vector_begin() { return VectorTypes.begin(); }
4638 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00004639
4640 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4641 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregora11693b2008-11-12 17:17:38 +00004642};
4643
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004644/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004645/// the set of pointer types along with any more-qualified variants of
4646/// that type. For example, if @p Ty is "int const *", this routine
4647/// will add "int const *", "int const volatile *", "int const
4648/// restrict *", and "int const volatile restrict *" to the set of
4649/// pointer types. Returns true if the add of @p Ty itself succeeded,
4650/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004651///
4652/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004653bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004654BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4655 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004656
Douglas Gregora11693b2008-11-12 17:17:38 +00004657 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004658 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004659 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004660
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004661 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004662 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004663 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004664 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004665 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004666 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004667 buildObjCPtr = true;
4668 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004669 else
4670 assert(false && "type was not a pointer type!");
4671 }
4672 else
4673 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004674
Sebastian Redl4990a632009-11-18 20:39:26 +00004675 // Don't add qualified variants of arrays. For one, they're not allowed
4676 // (the qualifier would sink to the element type), and for another, the
4677 // only overload situation where it matters is subscript or pointer +- int,
4678 // and those shouldn't have qualifier variants anyway.
4679 if (PointeeTy->isArrayType())
4680 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004681 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004682 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004683 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004684 bool hasVolatile = VisibleQuals.hasVolatile();
4685 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004686
John McCall8ccfcb52009-09-24 19:53:00 +00004687 // Iterate through all strict supersets of BaseCVR.
4688 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4689 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004690 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4691 // in the types.
4692 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4693 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004694 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004695 if (!buildObjCPtr)
4696 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4697 else
4698 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004699 }
4700
4701 return true;
4702}
4703
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004704/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4705/// to the set of pointer types along with any more-qualified variants of
4706/// that type. For example, if @p Ty is "int const *", this routine
4707/// will add "int const *", "int const volatile *", "int const
4708/// restrict *", and "int const volatile restrict *" to the set of
4709/// pointer types. Returns true if the add of @p Ty itself succeeded,
4710/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004711///
4712/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004713bool
4714BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4715 QualType Ty) {
4716 // Insert this type.
4717 if (!MemberPointerTypes.insert(Ty))
4718 return false;
4719
John McCall8ccfcb52009-09-24 19:53:00 +00004720 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4721 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004722
John McCall8ccfcb52009-09-24 19:53:00 +00004723 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004724 // Don't add qualified variants of arrays. For one, they're not allowed
4725 // (the qualifier would sink to the element type), and for another, the
4726 // only overload situation where it matters is subscript or pointer +- int,
4727 // and those shouldn't have qualifier variants anyway.
4728 if (PointeeTy->isArrayType())
4729 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004730 const Type *ClassTy = PointerTy->getClass();
4731
4732 // Iterate through all strict supersets of the pointee type's CVR
4733 // qualifiers.
4734 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4735 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4736 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004737
John McCall8ccfcb52009-09-24 19:53:00 +00004738 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00004739 MemberPointerTypes.insert(
4740 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004741 }
4742
4743 return true;
4744}
4745
Douglas Gregora11693b2008-11-12 17:17:38 +00004746/// AddTypesConvertedFrom - Add each of the types to which the type @p
4747/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004748/// primarily interested in pointer types and enumeration types. We also
4749/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004750/// AllowUserConversions is true if we should look at the conversion
4751/// functions of a class type, and AllowExplicitConversions if we
4752/// should also include the explicit conversion functions of a class
4753/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004754void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004755BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004756 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004757 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004758 bool AllowExplicitConversions,
4759 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004760 // Only deal with canonical types.
4761 Ty = Context.getCanonicalType(Ty);
4762
4763 // Look through reference types; they aren't part of the type of an
4764 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004765 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004766 Ty = RefTy->getPointeeType();
4767
John McCall33ddac02011-01-19 10:06:00 +00004768 // If we're dealing with an array type, decay to the pointer.
4769 if (Ty->isArrayType())
4770 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4771
4772 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004773 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004774
Chandler Carruth00a38332010-12-13 01:44:01 +00004775 // Flag if we ever add a non-record type.
4776 const RecordType *TyRec = Ty->getAs<RecordType>();
4777 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4778
Chandler Carruth00a38332010-12-13 01:44:01 +00004779 // Flag if we encounter an arithmetic type.
4780 HasArithmeticOrEnumeralTypes =
4781 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4782
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004783 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4784 PointerTypes.insert(Ty);
4785 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004786 // Insert our type, and its more-qualified variants, into the set
4787 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004788 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004789 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004790 } else if (Ty->isMemberPointerType()) {
4791 // Member pointers are far easier, since the pointee can't be converted.
4792 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4793 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004794 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004795 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00004796 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004797 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004798 // We treat vector types as arithmetic types in many contexts as an
4799 // extension.
4800 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004801 VectorTypes.insert(Ty);
Chandler Carruth00a38332010-12-13 01:44:01 +00004802 } else if (AllowUserConversions && TyRec) {
4803 // No conversion functions in incomplete types.
4804 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4805 return;
Mike Stump11289f42009-09-09 15:08:12 +00004806
Chandler Carruth00a38332010-12-13 01:44:01 +00004807 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4808 const UnresolvedSetImpl *Conversions
4809 = ClassDecl->getVisibleConversionFunctions();
4810 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4811 E = Conversions->end(); I != E; ++I) {
4812 NamedDecl *D = I.getDecl();
4813 if (isa<UsingShadowDecl>(D))
4814 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004815
Chandler Carruth00a38332010-12-13 01:44:01 +00004816 // Skip conversion function templates; they don't tell us anything
4817 // about which builtin types we can convert to.
4818 if (isa<FunctionTemplateDecl>(D))
4819 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00004820
Chandler Carruth00a38332010-12-13 01:44:01 +00004821 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4822 if (AllowExplicitConversions || !Conv->isExplicit()) {
4823 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4824 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004825 }
4826 }
4827 }
4828}
4829
Douglas Gregor84605ae2009-08-24 13:43:27 +00004830/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4831/// the volatile- and non-volatile-qualified assignment operators for the
4832/// given type to the candidate set.
4833static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4834 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004835 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004836 unsigned NumArgs,
4837 OverloadCandidateSet &CandidateSet) {
4838 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004839
Douglas Gregor84605ae2009-08-24 13:43:27 +00004840 // T& operator=(T&, T)
4841 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4842 ParamTypes[1] = T;
4843 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4844 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004845
Douglas Gregor84605ae2009-08-24 13:43:27 +00004846 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4847 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004848 ParamTypes[0]
4849 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004850 ParamTypes[1] = T;
4851 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004852 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004853 }
4854}
Mike Stump11289f42009-09-09 15:08:12 +00004855
Sebastian Redl1054fae2009-10-25 17:03:50 +00004856/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4857/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004858static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4859 Qualifiers VRQuals;
4860 const RecordType *TyRec;
4861 if (const MemberPointerType *RHSMPType =
4862 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004863 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004864 else
4865 TyRec = ArgExpr->getType()->getAs<RecordType>();
4866 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004867 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004868 VRQuals.addVolatile();
4869 VRQuals.addRestrict();
4870 return VRQuals;
4871 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004872
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004873 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004874 if (!ClassDecl->hasDefinition())
4875 return VRQuals;
4876
John McCallad371252010-01-20 00:46:10 +00004877 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004878 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004879
John McCallad371252010-01-20 00:46:10 +00004880 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004881 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004882 NamedDecl *D = I.getDecl();
4883 if (isa<UsingShadowDecl>(D))
4884 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4885 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004886 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4887 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4888 CanTy = ResTypeRef->getPointeeType();
4889 // Need to go down the pointer/mempointer chain and add qualifiers
4890 // as see them.
4891 bool done = false;
4892 while (!done) {
4893 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4894 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004895 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004896 CanTy->getAs<MemberPointerType>())
4897 CanTy = ResTypeMPtr->getPointeeType();
4898 else
4899 done = true;
4900 if (CanTy.isVolatileQualified())
4901 VRQuals.addVolatile();
4902 if (CanTy.isRestrictQualified())
4903 VRQuals.addRestrict();
4904 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4905 return VRQuals;
4906 }
4907 }
4908 }
4909 return VRQuals;
4910}
John McCall52872982010-11-13 05:51:15 +00004911
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004912namespace {
John McCall52872982010-11-13 05:51:15 +00004913
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004914/// \brief Helper class to manage the addition of builtin operator overload
4915/// candidates. It provides shared state and utility methods used throughout
4916/// the process, as well as a helper method to add each group of builtin
4917/// operator overloads from the standard to a candidate set.
4918class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004919 // Common instance state available to all overload candidate addition methods.
4920 Sema &S;
4921 Expr **Args;
4922 unsigned NumArgs;
4923 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00004924 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruthc6586e52010-12-12 10:35:00 +00004925 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4926 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004927
Chandler Carruthc6586e52010-12-12 10:35:00 +00004928 // Define some constants used to index and iterate over the arithemetic types
4929 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00004930 // The "promoted arithmetic types" are the arithmetic
4931 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00004932 static const unsigned FirstIntegralType = 3;
4933 static const unsigned LastIntegralType = 18;
4934 static const unsigned FirstPromotedIntegralType = 3,
4935 LastPromotedIntegralType = 9;
4936 static const unsigned FirstPromotedArithmeticType = 0,
4937 LastPromotedArithmeticType = 9;
4938 static const unsigned NumArithmeticTypes = 18;
4939
Chandler Carruthc6586e52010-12-12 10:35:00 +00004940 /// \brief Get the canonical type for a given arithmetic type index.
4941 CanQualType getArithmeticType(unsigned index) {
4942 assert(index < NumArithmeticTypes);
4943 static CanQualType ASTContext::* const
4944 ArithmeticTypes[NumArithmeticTypes] = {
4945 // Start of promoted types.
4946 &ASTContext::FloatTy,
4947 &ASTContext::DoubleTy,
4948 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00004949
Chandler Carruthc6586e52010-12-12 10:35:00 +00004950 // Start of integral types.
4951 &ASTContext::IntTy,
4952 &ASTContext::LongTy,
4953 &ASTContext::LongLongTy,
4954 &ASTContext::UnsignedIntTy,
4955 &ASTContext::UnsignedLongTy,
4956 &ASTContext::UnsignedLongLongTy,
4957 // End of promoted types.
4958
4959 &ASTContext::BoolTy,
4960 &ASTContext::CharTy,
4961 &ASTContext::WCharTy,
4962 &ASTContext::Char16Ty,
4963 &ASTContext::Char32Ty,
4964 &ASTContext::SignedCharTy,
4965 &ASTContext::ShortTy,
4966 &ASTContext::UnsignedCharTy,
4967 &ASTContext::UnsignedShortTy,
4968 // End of integral types.
4969 // FIXME: What about complex?
4970 };
4971 return S.Context.*ArithmeticTypes[index];
4972 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004973
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004974 /// \brief Gets the canonical type resulting from the usual arithemetic
4975 /// converions for the given arithmetic types.
4976 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
4977 // Accelerator table for performing the usual arithmetic conversions.
4978 // The rules are basically:
4979 // - if either is floating-point, use the wider floating-point
4980 // - if same signedness, use the higher rank
4981 // - if same size, use unsigned of the higher rank
4982 // - use the larger type
4983 // These rules, together with the axiom that higher ranks are
4984 // never smaller, are sufficient to precompute all of these results
4985 // *except* when dealing with signed types of higher rank.
4986 // (we could precompute SLL x UI for all known platforms, but it's
4987 // better not to make any assumptions).
4988 enum PromotedType {
4989 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
4990 };
4991 static PromotedType ConversionsTable[LastPromotedArithmeticType]
4992 [LastPromotedArithmeticType] = {
4993 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4994 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4995 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4996 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4997 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4998 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4999 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5000 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5001 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5002 };
5003
5004 assert(L < LastPromotedArithmeticType);
5005 assert(R < LastPromotedArithmeticType);
5006 int Idx = ConversionsTable[L][R];
5007
5008 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005009 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005010
5011 // Slow path: we need to compare widths.
5012 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005013 CanQualType LT = getArithmeticType(L),
5014 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005015 unsigned LW = S.Context.getIntWidth(LT),
5016 RW = S.Context.getIntWidth(RT);
5017
5018 // If they're different widths, use the signed type.
5019 if (LW > RW) return LT;
5020 else if (LW < RW) return RT;
5021
5022 // Otherwise, use the unsigned type of the signed type's rank.
5023 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5024 assert(L == SLL || R == SLL);
5025 return S.Context.UnsignedLongLongTy;
5026 }
5027
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005028 /// \brief Helper method to factor out the common pattern of adding overloads
5029 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005030 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5031 bool HasVolatile) {
5032 QualType ParamTypes[2] = {
5033 S.Context.getLValueReferenceType(CandidateTy),
5034 S.Context.IntTy
5035 };
5036
5037 // Non-volatile version.
5038 if (NumArgs == 1)
5039 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5040 else
5041 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5042
5043 // Use a heuristic to reduce number of builtin candidates in the set:
5044 // add volatile version only if there are conversions to a volatile type.
5045 if (HasVolatile) {
5046 ParamTypes[0] =
5047 S.Context.getLValueReferenceType(
5048 S.Context.getVolatileType(CandidateTy));
5049 if (NumArgs == 1)
5050 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5051 else
5052 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5053 }
5054 }
5055
5056public:
5057 BuiltinOperatorOverloadBuilder(
5058 Sema &S, Expr **Args, unsigned NumArgs,
5059 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005060 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005061 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
5062 OverloadCandidateSet &CandidateSet)
5063 : S(S), Args(Args), NumArgs(NumArgs),
5064 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005065 HasArithmeticOrEnumeralCandidateType(
5066 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005067 CandidateTypes(CandidateTypes),
5068 CandidateSet(CandidateSet) {
5069 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005070 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005071 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005072 assert(getArithmeticType(LastPromotedIntegralType - 1)
5073 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005074 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005075 assert(getArithmeticType(FirstPromotedArithmeticType)
5076 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005077 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005078 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5079 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005080 "Invalid last promoted arithmetic type");
5081 }
5082
5083 // C++ [over.built]p3:
5084 //
5085 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5086 // is either volatile or empty, there exist candidate operator
5087 // functions of the form
5088 //
5089 // VQ T& operator++(VQ T&);
5090 // T operator++(VQ T&, int);
5091 //
5092 // C++ [over.built]p4:
5093 //
5094 // For every pair (T, VQ), where T is an arithmetic type other
5095 // than bool, and VQ is either volatile or empty, there exist
5096 // candidate operator functions of the form
5097 //
5098 // VQ T& operator--(VQ T&);
5099 // T operator--(VQ T&, int);
5100 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005101 if (!HasArithmeticOrEnumeralCandidateType)
5102 return;
5103
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005104 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5105 Arith < NumArithmeticTypes; ++Arith) {
5106 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005107 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005108 VisibleTypeConversionsQuals.hasVolatile());
5109 }
5110 }
5111
5112 // C++ [over.built]p5:
5113 //
5114 // For every pair (T, VQ), where T is a cv-qualified or
5115 // cv-unqualified object type, and VQ is either volatile or
5116 // empty, there exist candidate operator functions of the form
5117 //
5118 // T*VQ& operator++(T*VQ&);
5119 // T*VQ& operator--(T*VQ&);
5120 // T* operator++(T*VQ&, int);
5121 // T* operator--(T*VQ&, int);
5122 void addPlusPlusMinusMinusPointerOverloads() {
5123 for (BuiltinCandidateTypeSet::iterator
5124 Ptr = CandidateTypes[0].pointer_begin(),
5125 PtrEnd = CandidateTypes[0].pointer_end();
5126 Ptr != PtrEnd; ++Ptr) {
5127 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005128 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005129 continue;
5130
5131 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5132 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5133 VisibleTypeConversionsQuals.hasVolatile()));
5134 }
5135 }
5136
5137 // C++ [over.built]p6:
5138 // For every cv-qualified or cv-unqualified object type T, there
5139 // exist candidate operator functions of the form
5140 //
5141 // T& operator*(T*);
5142 //
5143 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005144 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005145 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005146 // T& operator*(T*);
5147 void addUnaryStarPointerOverloads() {
5148 for (BuiltinCandidateTypeSet::iterator
5149 Ptr = CandidateTypes[0].pointer_begin(),
5150 PtrEnd = CandidateTypes[0].pointer_end();
5151 Ptr != PtrEnd; ++Ptr) {
5152 QualType ParamTy = *Ptr;
5153 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005154 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5155 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005156
Douglas Gregor02824322011-01-26 19:30:28 +00005157 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5158 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5159 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005160
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005161 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5162 &ParamTy, Args, 1, CandidateSet);
5163 }
5164 }
5165
5166 // C++ [over.built]p9:
5167 // For every promoted arithmetic type T, there exist candidate
5168 // operator functions of the form
5169 //
5170 // T operator+(T);
5171 // T operator-(T);
5172 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005173 if (!HasArithmeticOrEnumeralCandidateType)
5174 return;
5175
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005176 for (unsigned Arith = FirstPromotedArithmeticType;
5177 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005178 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005179 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5180 }
5181
5182 // Extension: We also add these operators for vector types.
5183 for (BuiltinCandidateTypeSet::iterator
5184 Vec = CandidateTypes[0].vector_begin(),
5185 VecEnd = CandidateTypes[0].vector_end();
5186 Vec != VecEnd; ++Vec) {
5187 QualType VecTy = *Vec;
5188 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5189 }
5190 }
5191
5192 // C++ [over.built]p8:
5193 // For every type T, there exist candidate operator functions of
5194 // the form
5195 //
5196 // T* operator+(T*);
5197 void addUnaryPlusPointerOverloads() {
5198 for (BuiltinCandidateTypeSet::iterator
5199 Ptr = CandidateTypes[0].pointer_begin(),
5200 PtrEnd = CandidateTypes[0].pointer_end();
5201 Ptr != PtrEnd; ++Ptr) {
5202 QualType ParamTy = *Ptr;
5203 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5204 }
5205 }
5206
5207 // C++ [over.built]p10:
5208 // For every promoted integral type T, there exist candidate
5209 // operator functions of the form
5210 //
5211 // T operator~(T);
5212 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005213 if (!HasArithmeticOrEnumeralCandidateType)
5214 return;
5215
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005216 for (unsigned Int = FirstPromotedIntegralType;
5217 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005218 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005219 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5220 }
5221
5222 // Extension: We also add this operator for vector types.
5223 for (BuiltinCandidateTypeSet::iterator
5224 Vec = CandidateTypes[0].vector_begin(),
5225 VecEnd = CandidateTypes[0].vector_end();
5226 Vec != VecEnd; ++Vec) {
5227 QualType VecTy = *Vec;
5228 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5229 }
5230 }
5231
5232 // C++ [over.match.oper]p16:
5233 // For every pointer to member type T, there exist candidate operator
5234 // functions of the form
5235 //
5236 // bool operator==(T,T);
5237 // bool operator!=(T,T);
5238 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5239 /// Set of (canonical) types that we've already handled.
5240 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5241
5242 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5243 for (BuiltinCandidateTypeSet::iterator
5244 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5245 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5246 MemPtr != MemPtrEnd;
5247 ++MemPtr) {
5248 // Don't add the same builtin candidate twice.
5249 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5250 continue;
5251
5252 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5253 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5254 CandidateSet);
5255 }
5256 }
5257 }
5258
5259 // C++ [over.built]p15:
5260 //
5261 // For every pointer or enumeration type T, there exist
5262 // candidate operator functions of the form
5263 //
5264 // bool operator<(T, T);
5265 // bool operator>(T, T);
5266 // bool operator<=(T, T);
5267 // bool operator>=(T, T);
5268 // bool operator==(T, T);
5269 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005270 void addRelationalPointerOrEnumeralOverloads() {
5271 // C++ [over.built]p1:
5272 // If there is a user-written candidate with the same name and parameter
5273 // types as a built-in candidate operator function, the built-in operator
5274 // function is hidden and is not included in the set of candidate
5275 // functions.
5276 //
5277 // The text is actually in a note, but if we don't implement it then we end
5278 // up with ambiguities when the user provides an overloaded operator for
5279 // an enumeration type. Note that only enumeration types have this problem,
5280 // so we track which enumeration types we've seen operators for. Also, the
5281 // only other overloaded operator with enumeration argumenst, operator=,
5282 // cannot be overloaded for enumeration types, so this is the only place
5283 // where we must suppress candidates like this.
5284 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5285 UserDefinedBinaryOperators;
5286
5287 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5288 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5289 CandidateTypes[ArgIdx].enumeration_end()) {
5290 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5291 CEnd = CandidateSet.end();
5292 C != CEnd; ++C) {
5293 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5294 continue;
5295
5296 QualType FirstParamType =
5297 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5298 QualType SecondParamType =
5299 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5300
5301 // Skip if either parameter isn't of enumeral type.
5302 if (!FirstParamType->isEnumeralType() ||
5303 !SecondParamType->isEnumeralType())
5304 continue;
5305
5306 // Add this operator to the set of known user-defined operators.
5307 UserDefinedBinaryOperators.insert(
5308 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5309 S.Context.getCanonicalType(SecondParamType)));
5310 }
5311 }
5312 }
5313
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005314 /// Set of (canonical) types that we've already handled.
5315 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5316
5317 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5318 for (BuiltinCandidateTypeSet::iterator
5319 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5320 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5321 Ptr != PtrEnd; ++Ptr) {
5322 // Don't add the same builtin candidate twice.
5323 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5324 continue;
5325
5326 QualType ParamTypes[2] = { *Ptr, *Ptr };
5327 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5328 CandidateSet);
5329 }
5330 for (BuiltinCandidateTypeSet::iterator
5331 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5332 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5333 Enum != EnumEnd; ++Enum) {
5334 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5335
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005336 // Don't add the same builtin candidate twice, or if a user defined
5337 // candidate exists.
5338 if (!AddedTypes.insert(CanonType) ||
5339 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5340 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005341 continue;
5342
5343 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005344 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5345 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005346 }
5347 }
5348 }
5349
5350 // C++ [over.built]p13:
5351 //
5352 // For every cv-qualified or cv-unqualified object type T
5353 // there exist candidate operator functions of the form
5354 //
5355 // T* operator+(T*, ptrdiff_t);
5356 // T& operator[](T*, ptrdiff_t); [BELOW]
5357 // T* operator-(T*, ptrdiff_t);
5358 // T* operator+(ptrdiff_t, T*);
5359 // T& operator[](ptrdiff_t, T*); [BELOW]
5360 //
5361 // C++ [over.built]p14:
5362 //
5363 // For every T, where T is a pointer to object type, there
5364 // exist candidate operator functions of the form
5365 //
5366 // ptrdiff_t operator-(T, T);
5367 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5368 /// Set of (canonical) types that we've already handled.
5369 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5370
5371 for (int Arg = 0; Arg < 2; ++Arg) {
5372 QualType AsymetricParamTypes[2] = {
5373 S.Context.getPointerDiffType(),
5374 S.Context.getPointerDiffType(),
5375 };
5376 for (BuiltinCandidateTypeSet::iterator
5377 Ptr = CandidateTypes[Arg].pointer_begin(),
5378 PtrEnd = CandidateTypes[Arg].pointer_end();
5379 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005380 QualType PointeeTy = (*Ptr)->getPointeeType();
5381 if (!PointeeTy->isObjectType())
5382 continue;
5383
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005384 AsymetricParamTypes[Arg] = *Ptr;
5385 if (Arg == 0 || Op == OO_Plus) {
5386 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5387 // T* operator+(ptrdiff_t, T*);
5388 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5389 CandidateSet);
5390 }
5391 if (Op == OO_Minus) {
5392 // ptrdiff_t operator-(T, T);
5393 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5394 continue;
5395
5396 QualType ParamTypes[2] = { *Ptr, *Ptr };
5397 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5398 Args, 2, CandidateSet);
5399 }
5400 }
5401 }
5402 }
5403
5404 // C++ [over.built]p12:
5405 //
5406 // For every pair of promoted arithmetic types L and R, there
5407 // exist candidate operator functions of the form
5408 //
5409 // LR operator*(L, R);
5410 // LR operator/(L, R);
5411 // LR operator+(L, R);
5412 // LR operator-(L, R);
5413 // bool operator<(L, R);
5414 // bool operator>(L, R);
5415 // bool operator<=(L, R);
5416 // bool operator>=(L, R);
5417 // bool operator==(L, R);
5418 // bool operator!=(L, R);
5419 //
5420 // where LR is the result of the usual arithmetic conversions
5421 // between types L and R.
5422 //
5423 // C++ [over.built]p24:
5424 //
5425 // For every pair of promoted arithmetic types L and R, there exist
5426 // candidate operator functions of the form
5427 //
5428 // LR operator?(bool, L, R);
5429 //
5430 // where LR is the result of the usual arithmetic conversions
5431 // between types L and R.
5432 // Our candidates ignore the first parameter.
5433 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005434 if (!HasArithmeticOrEnumeralCandidateType)
5435 return;
5436
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005437 for (unsigned Left = FirstPromotedArithmeticType;
5438 Left < LastPromotedArithmeticType; ++Left) {
5439 for (unsigned Right = FirstPromotedArithmeticType;
5440 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005441 QualType LandR[2] = { getArithmeticType(Left),
5442 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005443 QualType Result =
5444 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005445 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005446 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5447 }
5448 }
5449
5450 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5451 // conditional operator for vector types.
5452 for (BuiltinCandidateTypeSet::iterator
5453 Vec1 = CandidateTypes[0].vector_begin(),
5454 Vec1End = CandidateTypes[0].vector_end();
5455 Vec1 != Vec1End; ++Vec1) {
5456 for (BuiltinCandidateTypeSet::iterator
5457 Vec2 = CandidateTypes[1].vector_begin(),
5458 Vec2End = CandidateTypes[1].vector_end();
5459 Vec2 != Vec2End; ++Vec2) {
5460 QualType LandR[2] = { *Vec1, *Vec2 };
5461 QualType Result = S.Context.BoolTy;
5462 if (!isComparison) {
5463 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5464 Result = *Vec1;
5465 else
5466 Result = *Vec2;
5467 }
5468
5469 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5470 }
5471 }
5472 }
5473
5474 // C++ [over.built]p17:
5475 //
5476 // For every pair of promoted integral types L and R, there
5477 // exist candidate operator functions of the form
5478 //
5479 // LR operator%(L, R);
5480 // LR operator&(L, R);
5481 // LR operator^(L, R);
5482 // LR operator|(L, R);
5483 // L operator<<(L, R);
5484 // L operator>>(L, R);
5485 //
5486 // where LR is the result of the usual arithmetic conversions
5487 // between types L and R.
5488 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005489 if (!HasArithmeticOrEnumeralCandidateType)
5490 return;
5491
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005492 for (unsigned Left = FirstPromotedIntegralType;
5493 Left < LastPromotedIntegralType; ++Left) {
5494 for (unsigned Right = FirstPromotedIntegralType;
5495 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005496 QualType LandR[2] = { getArithmeticType(Left),
5497 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005498 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5499 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005500 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005501 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5502 }
5503 }
5504 }
5505
5506 // C++ [over.built]p20:
5507 //
5508 // For every pair (T, VQ), where T is an enumeration or
5509 // pointer to member type and VQ is either volatile or
5510 // empty, there exist candidate operator functions of the form
5511 //
5512 // VQ T& operator=(VQ T&, T);
5513 void addAssignmentMemberPointerOrEnumeralOverloads() {
5514 /// Set of (canonical) types that we've already handled.
5515 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5516
5517 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5518 for (BuiltinCandidateTypeSet::iterator
5519 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5520 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5521 Enum != EnumEnd; ++Enum) {
5522 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5523 continue;
5524
5525 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5526 CandidateSet);
5527 }
5528
5529 for (BuiltinCandidateTypeSet::iterator
5530 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5531 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5532 MemPtr != MemPtrEnd; ++MemPtr) {
5533 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5534 continue;
5535
5536 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5537 CandidateSet);
5538 }
5539 }
5540 }
5541
5542 // C++ [over.built]p19:
5543 //
5544 // For every pair (T, VQ), where T is any type and VQ is either
5545 // volatile or empty, there exist candidate operator functions
5546 // of the form
5547 //
5548 // T*VQ& operator=(T*VQ&, T*);
5549 //
5550 // C++ [over.built]p21:
5551 //
5552 // For every pair (T, VQ), where T is a cv-qualified or
5553 // cv-unqualified object type and VQ is either volatile or
5554 // empty, there exist candidate operator functions of the form
5555 //
5556 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5557 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5558 void addAssignmentPointerOverloads(bool isEqualOp) {
5559 /// Set of (canonical) types that we've already handled.
5560 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5561
5562 for (BuiltinCandidateTypeSet::iterator
5563 Ptr = CandidateTypes[0].pointer_begin(),
5564 PtrEnd = CandidateTypes[0].pointer_end();
5565 Ptr != PtrEnd; ++Ptr) {
5566 // If this is operator=, keep track of the builtin candidates we added.
5567 if (isEqualOp)
5568 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005569 else if (!(*Ptr)->getPointeeType()->isObjectType())
5570 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005571
5572 // non-volatile version
5573 QualType ParamTypes[2] = {
5574 S.Context.getLValueReferenceType(*Ptr),
5575 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5576 };
5577 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5578 /*IsAssigmentOperator=*/ isEqualOp);
5579
5580 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5581 VisibleTypeConversionsQuals.hasVolatile()) {
5582 // volatile version
5583 ParamTypes[0] =
5584 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5585 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5586 /*IsAssigmentOperator=*/isEqualOp);
5587 }
5588 }
5589
5590 if (isEqualOp) {
5591 for (BuiltinCandidateTypeSet::iterator
5592 Ptr = CandidateTypes[1].pointer_begin(),
5593 PtrEnd = CandidateTypes[1].pointer_end();
5594 Ptr != PtrEnd; ++Ptr) {
5595 // Make sure we don't add the same candidate twice.
5596 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5597 continue;
5598
Chandler Carruth8e543b32010-12-12 08:17:55 +00005599 QualType ParamTypes[2] = {
5600 S.Context.getLValueReferenceType(*Ptr),
5601 *Ptr,
5602 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005603
5604 // non-volatile version
5605 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5606 /*IsAssigmentOperator=*/true);
5607
5608 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5609 VisibleTypeConversionsQuals.hasVolatile()) {
5610 // volatile version
5611 ParamTypes[0] =
5612 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00005613 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5614 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005615 }
5616 }
5617 }
5618 }
5619
5620 // C++ [over.built]p18:
5621 //
5622 // For every triple (L, VQ, R), where L is an arithmetic type,
5623 // VQ is either volatile or empty, and R is a promoted
5624 // arithmetic type, there exist candidate operator functions of
5625 // the form
5626 //
5627 // VQ L& operator=(VQ L&, R);
5628 // VQ L& operator*=(VQ L&, R);
5629 // VQ L& operator/=(VQ L&, R);
5630 // VQ L& operator+=(VQ L&, R);
5631 // VQ L& operator-=(VQ L&, R);
5632 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005633 if (!HasArithmeticOrEnumeralCandidateType)
5634 return;
5635
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005636 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5637 for (unsigned Right = FirstPromotedArithmeticType;
5638 Right < LastPromotedArithmeticType; ++Right) {
5639 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005640 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005641
5642 // Add this built-in operator as a candidate (VQ is empty).
5643 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005644 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005645 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5646 /*IsAssigmentOperator=*/isEqualOp);
5647
5648 // Add this built-in operator as a candidate (VQ is 'volatile').
5649 if (VisibleTypeConversionsQuals.hasVolatile()) {
5650 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005651 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005652 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005653 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5654 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005655 /*IsAssigmentOperator=*/isEqualOp);
5656 }
5657 }
5658 }
5659
5660 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5661 for (BuiltinCandidateTypeSet::iterator
5662 Vec1 = CandidateTypes[0].vector_begin(),
5663 Vec1End = CandidateTypes[0].vector_end();
5664 Vec1 != Vec1End; ++Vec1) {
5665 for (BuiltinCandidateTypeSet::iterator
5666 Vec2 = CandidateTypes[1].vector_begin(),
5667 Vec2End = CandidateTypes[1].vector_end();
5668 Vec2 != Vec2End; ++Vec2) {
5669 QualType ParamTypes[2];
5670 ParamTypes[1] = *Vec2;
5671 // Add this built-in operator as a candidate (VQ is empty).
5672 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5673 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5674 /*IsAssigmentOperator=*/isEqualOp);
5675
5676 // Add this built-in operator as a candidate (VQ is 'volatile').
5677 if (VisibleTypeConversionsQuals.hasVolatile()) {
5678 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5679 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005680 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5681 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005682 /*IsAssigmentOperator=*/isEqualOp);
5683 }
5684 }
5685 }
5686 }
5687
5688 // C++ [over.built]p22:
5689 //
5690 // For every triple (L, VQ, R), where L is an integral type, VQ
5691 // is either volatile or empty, and R is a promoted integral
5692 // type, there exist candidate operator functions of the form
5693 //
5694 // VQ L& operator%=(VQ L&, R);
5695 // VQ L& operator<<=(VQ L&, R);
5696 // VQ L& operator>>=(VQ L&, R);
5697 // VQ L& operator&=(VQ L&, R);
5698 // VQ L& operator^=(VQ L&, R);
5699 // VQ L& operator|=(VQ L&, R);
5700 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005701 if (!HasArithmeticOrEnumeralCandidateType)
5702 return;
5703
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005704 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5705 for (unsigned Right = FirstPromotedIntegralType;
5706 Right < LastPromotedIntegralType; ++Right) {
5707 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005708 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005709
5710 // Add this built-in operator as a candidate (VQ is empty).
5711 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005712 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005713 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5714 if (VisibleTypeConversionsQuals.hasVolatile()) {
5715 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00005716 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005717 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5718 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5719 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5720 CandidateSet);
5721 }
5722 }
5723 }
5724 }
5725
5726 // C++ [over.operator]p23:
5727 //
5728 // There also exist candidate operator functions of the form
5729 //
5730 // bool operator!(bool);
5731 // bool operator&&(bool, bool);
5732 // bool operator||(bool, bool);
5733 void addExclaimOverload() {
5734 QualType ParamTy = S.Context.BoolTy;
5735 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5736 /*IsAssignmentOperator=*/false,
5737 /*NumContextualBoolArguments=*/1);
5738 }
5739 void addAmpAmpOrPipePipeOverload() {
5740 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5741 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5742 /*IsAssignmentOperator=*/false,
5743 /*NumContextualBoolArguments=*/2);
5744 }
5745
5746 // C++ [over.built]p13:
5747 //
5748 // For every cv-qualified or cv-unqualified object type T there
5749 // exist candidate operator functions of the form
5750 //
5751 // T* operator+(T*, ptrdiff_t); [ABOVE]
5752 // T& operator[](T*, ptrdiff_t);
5753 // T* operator-(T*, ptrdiff_t); [ABOVE]
5754 // T* operator+(ptrdiff_t, T*); [ABOVE]
5755 // T& operator[](ptrdiff_t, T*);
5756 void addSubscriptOverloads() {
5757 for (BuiltinCandidateTypeSet::iterator
5758 Ptr = CandidateTypes[0].pointer_begin(),
5759 PtrEnd = CandidateTypes[0].pointer_end();
5760 Ptr != PtrEnd; ++Ptr) {
5761 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5762 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005763 if (!PointeeType->isObjectType())
5764 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005765
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005766 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5767
5768 // T& operator[](T*, ptrdiff_t)
5769 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5770 }
5771
5772 for (BuiltinCandidateTypeSet::iterator
5773 Ptr = CandidateTypes[1].pointer_begin(),
5774 PtrEnd = CandidateTypes[1].pointer_end();
5775 Ptr != PtrEnd; ++Ptr) {
5776 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5777 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005778 if (!PointeeType->isObjectType())
5779 continue;
5780
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005781 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5782
5783 // T& operator[](ptrdiff_t, T*)
5784 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5785 }
5786 }
5787
5788 // C++ [over.built]p11:
5789 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5790 // C1 is the same type as C2 or is a derived class of C2, T is an object
5791 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5792 // there exist candidate operator functions of the form
5793 //
5794 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5795 //
5796 // where CV12 is the union of CV1 and CV2.
5797 void addArrowStarOverloads() {
5798 for (BuiltinCandidateTypeSet::iterator
5799 Ptr = CandidateTypes[0].pointer_begin(),
5800 PtrEnd = CandidateTypes[0].pointer_end();
5801 Ptr != PtrEnd; ++Ptr) {
5802 QualType C1Ty = (*Ptr);
5803 QualType C1;
5804 QualifierCollector Q1;
5805 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5806 if (!isa<RecordType>(C1))
5807 continue;
5808 // heuristic to reduce number of builtin candidates in the set.
5809 // Add volatile/restrict version only if there are conversions to a
5810 // volatile/restrict type.
5811 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5812 continue;
5813 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5814 continue;
5815 for (BuiltinCandidateTypeSet::iterator
5816 MemPtr = CandidateTypes[1].member_pointer_begin(),
5817 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5818 MemPtr != MemPtrEnd; ++MemPtr) {
5819 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5820 QualType C2 = QualType(mptr->getClass(), 0);
5821 C2 = C2.getUnqualifiedType();
5822 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5823 break;
5824 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5825 // build CV12 T&
5826 QualType T = mptr->getPointeeType();
5827 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5828 T.isVolatileQualified())
5829 continue;
5830 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5831 T.isRestrictQualified())
5832 continue;
5833 T = Q1.apply(S.Context, T);
5834 QualType ResultTy = S.Context.getLValueReferenceType(T);
5835 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5836 }
5837 }
5838 }
5839
5840 // Note that we don't consider the first argument, since it has been
5841 // contextually converted to bool long ago. The candidates below are
5842 // therefore added as binary.
5843 //
5844 // C++ [over.built]p25:
5845 // For every type T, where T is a pointer, pointer-to-member, or scoped
5846 // enumeration type, there exist candidate operator functions of the form
5847 //
5848 // T operator?(bool, T, T);
5849 //
5850 void addConditionalOperatorOverloads() {
5851 /// Set of (canonical) types that we've already handled.
5852 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5853
5854 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5855 for (BuiltinCandidateTypeSet::iterator
5856 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5857 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5858 Ptr != PtrEnd; ++Ptr) {
5859 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5860 continue;
5861
5862 QualType ParamTypes[2] = { *Ptr, *Ptr };
5863 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5864 }
5865
5866 for (BuiltinCandidateTypeSet::iterator
5867 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5868 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5869 MemPtr != MemPtrEnd; ++MemPtr) {
5870 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5871 continue;
5872
5873 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5874 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5875 }
5876
5877 if (S.getLangOptions().CPlusPlus0x) {
5878 for (BuiltinCandidateTypeSet::iterator
5879 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5880 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5881 Enum != EnumEnd; ++Enum) {
5882 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5883 continue;
5884
5885 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5886 continue;
5887
5888 QualType ParamTypes[2] = { *Enum, *Enum };
5889 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5890 }
5891 }
5892 }
5893 }
5894};
5895
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005896} // end anonymous namespace
5897
5898/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5899/// operator overloads to the candidate set (C++ [over.built]), based
5900/// on the operator @p Op and the arguments given. For example, if the
5901/// operator is a binary '+', this routine might add "int
5902/// operator+(int, int)" to cover integer addition.
5903void
5904Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5905 SourceLocation OpLoc,
5906 Expr **Args, unsigned NumArgs,
5907 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005908 // Find all of the types that the arguments can convert to, but only
5909 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00005910 // that make use of these types. Also record whether we encounter non-record
5911 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005912 Qualifiers VisibleTypeConversionsQuals;
5913 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005914 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5915 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00005916
5917 bool HasNonRecordCandidateType = false;
5918 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005919 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5920 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5921 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5922 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5923 OpLoc,
5924 true,
5925 (Op == OO_Exclaim ||
5926 Op == OO_AmpAmp ||
5927 Op == OO_PipePipe),
5928 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00005929 HasNonRecordCandidateType = HasNonRecordCandidateType ||
5930 CandidateTypes[ArgIdx].hasNonRecordTypes();
5931 HasArithmeticOrEnumeralCandidateType =
5932 HasArithmeticOrEnumeralCandidateType ||
5933 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005934 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005935
Chandler Carruth00a38332010-12-13 01:44:01 +00005936 // Exit early when no non-record types have been added to the candidate set
5937 // for any of the arguments to the operator.
5938 if (!HasNonRecordCandidateType)
5939 return;
5940
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005941 // Setup an object to manage the common state for building overloads.
5942 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
5943 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005944 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005945 CandidateTypes, CandidateSet);
5946
5947 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00005948 switch (Op) {
5949 case OO_None:
5950 case NUM_OVERLOADED_OPERATORS:
5951 assert(false && "Expected an overloaded operator");
5952 break;
5953
Chandler Carruth5184de02010-12-12 08:51:33 +00005954 case OO_New:
5955 case OO_Delete:
5956 case OO_Array_New:
5957 case OO_Array_Delete:
5958 case OO_Call:
5959 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
5960 break;
5961
5962 case OO_Comma:
5963 case OO_Arrow:
5964 // C++ [over.match.oper]p3:
5965 // -- For the operator ',', the unary operator '&', or the
5966 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00005967 break;
5968
5969 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00005970 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005971 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00005972 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00005973
5974 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00005975 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005976 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00005977 } else {
5978 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
5979 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5980 }
Douglas Gregord08452f2008-11-19 15:42:04 +00005981 break;
5982
Chandler Carruth5184de02010-12-12 08:51:33 +00005983 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00005984 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00005985 OpBuilder.addUnaryStarPointerOverloads();
5986 else
5987 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5988 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005989
Chandler Carruth5184de02010-12-12 08:51:33 +00005990 case OO_Slash:
5991 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00005992 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005993
5994 case OO_PlusPlus:
5995 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005996 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
5997 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00005998 break;
5999
Douglas Gregor84605ae2009-08-24 13:43:27 +00006000 case OO_EqualEqual:
6001 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006002 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006003 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006004
Douglas Gregora11693b2008-11-12 17:17:38 +00006005 case OO_Less:
6006 case OO_Greater:
6007 case OO_LessEqual:
6008 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006009 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006010 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6011 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006012
Douglas Gregora11693b2008-11-12 17:17:38 +00006013 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006014 case OO_Caret:
6015 case OO_Pipe:
6016 case OO_LessLess:
6017 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006018 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006019 break;
6020
Chandler Carruth5184de02010-12-12 08:51:33 +00006021 case OO_Amp: // '&' is either unary or binary
6022 if (NumArgs == 1)
6023 // C++ [over.match.oper]p3:
6024 // -- For the operator ',', the unary operator '&', or the
6025 // operator '->', the built-in candidates set is empty.
6026 break;
6027
6028 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6029 break;
6030
6031 case OO_Tilde:
6032 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6033 break;
6034
Douglas Gregora11693b2008-11-12 17:17:38 +00006035 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006036 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006037 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006038
6039 case OO_PlusEqual:
6040 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006041 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006042 // Fall through.
6043
6044 case OO_StarEqual:
6045 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006046 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006047 break;
6048
6049 case OO_PercentEqual:
6050 case OO_LessLessEqual:
6051 case OO_GreaterGreaterEqual:
6052 case OO_AmpEqual:
6053 case OO_CaretEqual:
6054 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006055 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006056 break;
6057
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006058 case OO_Exclaim:
6059 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006060 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006061
Douglas Gregora11693b2008-11-12 17:17:38 +00006062 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006063 case OO_PipePipe:
6064 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006065 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006066
6067 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006068 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006069 break;
6070
6071 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006072 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006073 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006074
6075 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006076 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006077 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6078 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006079 }
6080}
6081
Douglas Gregore254f902009-02-04 00:32:51 +00006082/// \brief Add function candidates found via argument-dependent lookup
6083/// to the set of overloading candidates.
6084///
6085/// This routine performs argument-dependent name lookup based on the
6086/// given function name (which may also be an operator name) and adds
6087/// all of the overload candidates found by ADL to the overload
6088/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006089void
Douglas Gregore254f902009-02-04 00:32:51 +00006090Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006091 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006092 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00006093 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006094 OverloadCandidateSet& CandidateSet,
6095 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00006096 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006097
John McCall91f61fc2010-01-26 06:04:06 +00006098 // FIXME: This approach for uniquing ADL results (and removing
6099 // redundant candidates from the set) relies on pointer-equality,
6100 // which means we need to key off the canonical decl. However,
6101 // always going back to the canonical decl might not get us the
6102 // right set of default arguments. What default arguments are
6103 // we supposed to consider on ADL candidates, anyway?
6104
Douglas Gregorcabea402009-09-22 15:41:20 +00006105 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00006106 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00006107
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006108 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006109 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6110 CandEnd = CandidateSet.end();
6111 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006112 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006113 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006114 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006115 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006116 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006117
6118 // For each of the ADL candidates we found, add it to the overload
6119 // set.
John McCall8fe68082010-01-26 07:16:45 +00006120 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006121 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006122 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006123 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006124 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006125
John McCalla0296f72010-03-19 07:35:19 +00006126 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006127 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006128 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006129 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006130 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006131 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006132 }
Douglas Gregore254f902009-02-04 00:32:51 +00006133}
6134
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006135/// isBetterOverloadCandidate - Determines whether the first overload
6136/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006137bool
John McCall5c32be02010-08-24 20:38:10 +00006138isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006139 const OverloadCandidate &Cand1,
6140 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006141 SourceLocation Loc,
6142 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006143 // Define viable functions to be better candidates than non-viable
6144 // functions.
6145 if (!Cand2.Viable)
6146 return Cand1.Viable;
6147 else if (!Cand1.Viable)
6148 return false;
6149
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006150 // C++ [over.match.best]p1:
6151 //
6152 // -- if F is a static member function, ICS1(F) is defined such
6153 // that ICS1(F) is neither better nor worse than ICS1(G) for
6154 // any function G, and, symmetrically, ICS1(G) is neither
6155 // better nor worse than ICS1(F).
6156 unsigned StartArg = 0;
6157 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6158 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006159
Douglas Gregord3cb3562009-07-07 23:38:56 +00006160 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006161 // A viable function F1 is defined to be a better function than another
6162 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006163 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006164 unsigned NumArgs = Cand1.Conversions.size();
6165 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6166 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006167 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006168 switch (CompareImplicitConversionSequences(S,
6169 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006170 Cand2.Conversions[ArgIdx])) {
6171 case ImplicitConversionSequence::Better:
6172 // Cand1 has a better conversion sequence.
6173 HasBetterConversion = true;
6174 break;
6175
6176 case ImplicitConversionSequence::Worse:
6177 // Cand1 can't be better than Cand2.
6178 return false;
6179
6180 case ImplicitConversionSequence::Indistinguishable:
6181 // Do nothing.
6182 break;
6183 }
6184 }
6185
Mike Stump11289f42009-09-09 15:08:12 +00006186 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006187 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006188 if (HasBetterConversion)
6189 return true;
6190
Mike Stump11289f42009-09-09 15:08:12 +00006191 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006192 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006193 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006194 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6195 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006196
6197 // -- F1 and F2 are function template specializations, and the function
6198 // template for F1 is more specialized than the template for F2
6199 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006200 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006201 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006202 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006203 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006204 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6205 Cand2.Function->getPrimaryTemplate(),
6206 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006207 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006208 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006209 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006210 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006211 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006212
Douglas Gregora1f013e2008-11-07 22:36:19 +00006213 // -- the context is an initialization by user-defined conversion
6214 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6215 // from the return type of F1 to the destination type (i.e.,
6216 // the type of the entity being initialized) is a better
6217 // conversion sequence than the standard conversion sequence
6218 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006219 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006220 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006221 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006222 switch (CompareStandardConversionSequences(S,
6223 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006224 Cand2.FinalConversion)) {
6225 case ImplicitConversionSequence::Better:
6226 // Cand1 has a better conversion sequence.
6227 return true;
6228
6229 case ImplicitConversionSequence::Worse:
6230 // Cand1 can't be better than Cand2.
6231 return false;
6232
6233 case ImplicitConversionSequence::Indistinguishable:
6234 // Do nothing
6235 break;
6236 }
6237 }
6238
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006239 return false;
6240}
6241
Mike Stump11289f42009-09-09 15:08:12 +00006242/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006243/// within an overload candidate set.
6244///
6245/// \param CandidateSet the set of candidate functions.
6246///
6247/// \param Loc the location of the function name (or operator symbol) for
6248/// which overload resolution occurs.
6249///
Mike Stump11289f42009-09-09 15:08:12 +00006250/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006251/// function, Best points to the candidate function found.
6252///
6253/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006254OverloadingResult
6255OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006256 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00006257 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006258 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006259 Best = end();
6260 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6261 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006262 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006263 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006264 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006265 }
6266
6267 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006268 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006269 return OR_No_Viable_Function;
6270
6271 // Make sure that this function is better than every other viable
6272 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006273 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006274 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006275 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006276 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006277 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006278 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006279 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006280 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006281 }
Mike Stump11289f42009-09-09 15:08:12 +00006282
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006283 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006284 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006285 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006286 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006287 return OR_Deleted;
6288
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006289 return OR_Success;
6290}
6291
John McCall53262c92010-01-12 02:15:36 +00006292namespace {
6293
6294enum OverloadCandidateKind {
6295 oc_function,
6296 oc_method,
6297 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006298 oc_function_template,
6299 oc_method_template,
6300 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006301 oc_implicit_default_constructor,
6302 oc_implicit_copy_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006303 oc_implicit_copy_assignment,
6304 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006305};
6306
John McCalle1ac8d12010-01-13 00:25:19 +00006307OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6308 FunctionDecl *Fn,
6309 std::string &Description) {
6310 bool isTemplate = false;
6311
6312 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6313 isTemplate = true;
6314 Description = S.getTemplateArgumentBindingsText(
6315 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6316 }
John McCallfd0b2f82010-01-06 09:43:14 +00006317
6318 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006319 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006320 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006321
Sebastian Redl08905022011-02-05 19:23:19 +00006322 if (Ctor->getInheritedConstructor())
6323 return oc_implicit_inherited_constructor;
6324
John McCall53262c92010-01-12 02:15:36 +00006325 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6326 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006327 }
6328
6329 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6330 // This actually gets spelled 'candidate function' for now, but
6331 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006332 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006333 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006334
Douglas Gregorec3bec02010-09-27 22:37:28 +00006335 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006336 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006337 return oc_implicit_copy_assignment;
6338 }
6339
John McCalle1ac8d12010-01-13 00:25:19 +00006340 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006341}
6342
Sebastian Redl08905022011-02-05 19:23:19 +00006343void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6344 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6345 if (!Ctor) return;
6346
6347 Ctor = Ctor->getInheritedConstructor();
6348 if (!Ctor) return;
6349
6350 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6351}
6352
John McCall53262c92010-01-12 02:15:36 +00006353} // end anonymous namespace
6354
6355// Notes the location of an overload candidate.
6356void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006357 std::string FnDesc;
6358 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6359 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6360 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00006361 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00006362}
6363
Douglas Gregorb491ed32011-02-19 21:32:49 +00006364//Notes the location of all overload candidates designated through
6365// OverloadedExpr
6366void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6367 assert(OverloadedExpr->getType() == Context.OverloadTy);
6368
6369 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6370 OverloadExpr *OvlExpr = Ovl.Expression;
6371
6372 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6373 IEnd = OvlExpr->decls_end();
6374 I != IEnd; ++I) {
6375 if (FunctionTemplateDecl *FunTmpl =
6376 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6377 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6378 } else if (FunctionDecl *Fun
6379 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6380 NoteOverloadCandidate(Fun);
6381 }
6382 }
6383}
6384
John McCall0d1da222010-01-12 00:44:57 +00006385/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6386/// "lead" diagnostic; it will be given two arguments, the source and
6387/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006388void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6389 Sema &S,
6390 SourceLocation CaretLoc,
6391 const PartialDiagnostic &PDiag) const {
6392 S.Diag(CaretLoc, PDiag)
6393 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006394 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006395 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6396 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006397 }
John McCall12f97bc2010-01-08 04:41:39 +00006398}
6399
John McCall0d1da222010-01-12 00:44:57 +00006400namespace {
6401
John McCall6a61b522010-01-13 09:16:55 +00006402void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6403 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6404 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006405 assert(Cand->Function && "for now, candidate must be a function");
6406 FunctionDecl *Fn = Cand->Function;
6407
6408 // There's a conversion slot for the object argument if this is a
6409 // non-constructor method. Note that 'I' corresponds the
6410 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006411 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006412 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006413 if (I == 0)
6414 isObjectArgument = true;
6415 else
6416 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006417 }
6418
John McCalle1ac8d12010-01-13 00:25:19 +00006419 std::string FnDesc;
6420 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6421
John McCall6a61b522010-01-13 09:16:55 +00006422 Expr *FromExpr = Conv.Bad.FromExpr;
6423 QualType FromTy = Conv.Bad.getFromType();
6424 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006425
John McCallfb7ad0f2010-02-02 02:42:52 +00006426 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006427 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006428 Expr *E = FromExpr->IgnoreParens();
6429 if (isa<UnaryOperator>(E))
6430 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006431 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006432
6433 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6434 << (unsigned) FnKind << FnDesc
6435 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6436 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006437 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00006438 return;
6439 }
6440
John McCall6d174642010-01-23 08:10:49 +00006441 // Do some hand-waving analysis to see if the non-viability is due
6442 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006443 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6444 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6445 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6446 CToTy = RT->getPointeeType();
6447 else {
6448 // TODO: detect and diagnose the full richness of const mismatches.
6449 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6450 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6451 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6452 }
6453
6454 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6455 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6456 // It is dumb that we have to do this here.
6457 while (isa<ArrayType>(CFromTy))
6458 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6459 while (isa<ArrayType>(CToTy))
6460 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6461
6462 Qualifiers FromQs = CFromTy.getQualifiers();
6463 Qualifiers ToQs = CToTy.getQualifiers();
6464
6465 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6466 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6467 << (unsigned) FnKind << FnDesc
6468 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6469 << FromTy
6470 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6471 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006472 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006473 return;
6474 }
6475
6476 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6477 assert(CVR && "unexpected qualifiers mismatch");
6478
6479 if (isObjectArgument) {
6480 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6481 << (unsigned) FnKind << FnDesc
6482 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6483 << FromTy << (CVR - 1);
6484 } else {
6485 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6486 << (unsigned) FnKind << FnDesc
6487 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6488 << FromTy << (CVR - 1) << I+1;
6489 }
Sebastian Redl08905022011-02-05 19:23:19 +00006490 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006491 return;
6492 }
6493
John McCall6d174642010-01-23 08:10:49 +00006494 // Diagnose references or pointers to incomplete types differently,
6495 // since it's far from impossible that the incompleteness triggered
6496 // the failure.
6497 QualType TempFromTy = FromTy.getNonReferenceType();
6498 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6499 TempFromTy = PTy->getPointeeType();
6500 if (TempFromTy->isIncompleteType()) {
6501 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6502 << (unsigned) FnKind << FnDesc
6503 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6504 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006505 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00006506 return;
6507 }
6508
Douglas Gregor56f2e342010-06-30 23:01:39 +00006509 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006510 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006511 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6512 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6513 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6514 FromPtrTy->getPointeeType()) &&
6515 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6516 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006517 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00006518 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006519 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006520 }
6521 } else if (const ObjCObjectPointerType *FromPtrTy
6522 = FromTy->getAs<ObjCObjectPointerType>()) {
6523 if (const ObjCObjectPointerType *ToPtrTy
6524 = ToTy->getAs<ObjCObjectPointerType>())
6525 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6526 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6527 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6528 FromPtrTy->getPointeeType()) &&
6529 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006530 BaseToDerivedConversion = 2;
6531 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6532 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6533 !FromTy->isIncompleteType() &&
6534 !ToRefTy->getPointeeType()->isIncompleteType() &&
6535 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6536 BaseToDerivedConversion = 3;
6537 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006538
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006539 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006540 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006541 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006542 << (unsigned) FnKind << FnDesc
6543 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006544 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006545 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006546 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00006547 return;
6548 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006549
John McCall47000992010-01-14 03:28:57 +00006550 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006551 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6552 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006553 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006554 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006555 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00006556}
6557
6558void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6559 unsigned NumFormalArgs) {
6560 // TODO: treat calls to a missing default constructor as a special case
6561
6562 FunctionDecl *Fn = Cand->Function;
6563 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6564
6565 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006566
John McCall6a61b522010-01-13 09:16:55 +00006567 // at least / at most / exactly
6568 unsigned mode, modeCount;
6569 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006570 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6571 (Cand->FailureKind == ovl_fail_bad_deduction &&
6572 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006573 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00006574 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00006575 mode = 0; // "at least"
6576 else
6577 mode = 2; // "exactly"
6578 modeCount = MinParams;
6579 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006580 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6581 (Cand->FailureKind == ovl_fail_bad_deduction &&
6582 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006583 if (MinParams != FnTy->getNumArgs())
6584 mode = 1; // "at most"
6585 else
6586 mode = 2; // "exactly"
6587 modeCount = FnTy->getNumArgs();
6588 }
6589
6590 std::string Description;
6591 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6592
6593 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006594 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00006595 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00006596 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006597}
6598
John McCall8b9ed552010-02-01 18:53:26 +00006599/// Diagnose a failed template-argument deduction.
6600void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6601 Expr **Args, unsigned NumArgs) {
6602 FunctionDecl *Fn = Cand->Function; // pattern
6603
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006604 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006605 NamedDecl *ParamD;
6606 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6607 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6608 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006609 switch (Cand->DeductionFailure.Result) {
6610 case Sema::TDK_Success:
6611 llvm_unreachable("TDK_success while diagnosing bad deduction");
6612
6613 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006614 assert(ParamD && "no parameter found for incomplete deduction result");
6615 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6616 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00006617 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00006618 return;
6619 }
6620
John McCall42d7d192010-08-05 09:05:08 +00006621 case Sema::TDK_Underqualified: {
6622 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6623 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6624
6625 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6626
6627 // Param will have been canonicalized, but it should just be a
6628 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00006629 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00006630 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00006631 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00006632 assert(S.Context.hasSameType(Param, NonCanonParam));
6633
6634 // Arg has also been canonicalized, but there's nothing we can do
6635 // about that. It also doesn't matter as much, because it won't
6636 // have any template parameters in it (because deduction isn't
6637 // done on dependent types).
6638 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6639
6640 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6641 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00006642 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00006643 return;
6644 }
6645
6646 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00006647 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006648 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006649 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006650 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006651 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006652 which = 1;
6653 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006654 which = 2;
6655 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006656
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006657 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006658 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006659 << *Cand->DeductionFailure.getFirstArg()
6660 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00006661 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006662 return;
6663 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006664
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006665 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006666 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006667 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006668 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006669 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6670 << ParamD->getDeclName();
6671 else {
6672 int index = 0;
6673 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6674 index = TTP->getIndex();
6675 else if (NonTypeTemplateParmDecl *NTTP
6676 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6677 index = NTTP->getIndex();
6678 else
6679 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006680 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006681 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6682 << (index + 1);
6683 }
Sebastian Redl08905022011-02-05 19:23:19 +00006684 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006685 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006686
Douglas Gregor02eb4832010-05-08 18:13:28 +00006687 case Sema::TDK_TooManyArguments:
6688 case Sema::TDK_TooFewArguments:
6689 DiagnoseArityMismatch(S, Cand, NumArgs);
6690 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006691
6692 case Sema::TDK_InstantiationDepth:
6693 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00006694 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00006695 return;
6696
6697 case Sema::TDK_SubstitutionFailure: {
6698 std::string ArgString;
6699 if (TemplateArgumentList *Args
6700 = Cand->DeductionFailure.getTemplateArgumentList())
6701 ArgString = S.getTemplateArgumentBindingsText(
6702 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6703 *Args);
6704 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6705 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00006706 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00006707 return;
6708 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006709
John McCall8b9ed552010-02-01 18:53:26 +00006710 // TODO: diagnose these individually, then kill off
6711 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006712 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006713 case Sema::TDK_FailedOverloadResolution:
6714 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00006715 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00006716 return;
6717 }
6718}
6719
6720/// Generates a 'note' diagnostic for an overload candidate. We've
6721/// already generated a primary error at the call site.
6722///
6723/// It really does need to be a single diagnostic with its caret
6724/// pointed at the candidate declaration. Yes, this creates some
6725/// major challenges of technical writing. Yes, this makes pointing
6726/// out problems with specific arguments quite awkward. It's still
6727/// better than generating twenty screens of text for every failed
6728/// overload.
6729///
6730/// It would be great to be able to express per-candidate problems
6731/// more richly for those diagnostic clients that cared, but we'd
6732/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006733void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6734 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006735 FunctionDecl *Fn = Cand->Function;
6736
John McCall12f97bc2010-01-08 04:41:39 +00006737 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00006738 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006739 std::string FnDesc;
6740 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006741
6742 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006743 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00006744 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00006745 return;
John McCall12f97bc2010-01-08 04:41:39 +00006746 }
6747
John McCalle1ac8d12010-01-13 00:25:19 +00006748 // We don't really have anything else to say about viable candidates.
6749 if (Cand->Viable) {
6750 S.NoteOverloadCandidate(Fn);
6751 return;
6752 }
John McCall0d1da222010-01-12 00:44:57 +00006753
John McCall6a61b522010-01-13 09:16:55 +00006754 switch (Cand->FailureKind) {
6755 case ovl_fail_too_many_arguments:
6756 case ovl_fail_too_few_arguments:
6757 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006758
John McCall6a61b522010-01-13 09:16:55 +00006759 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006760 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6761
John McCallfe796dd2010-01-23 05:17:32 +00006762 case ovl_fail_trivial_conversion:
6763 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006764 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006765 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006766
John McCall65eb8792010-02-25 01:37:24 +00006767 case ovl_fail_bad_conversion: {
6768 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6769 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006770 if (Cand->Conversions[I].isBad())
6771 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006772
John McCall6a61b522010-01-13 09:16:55 +00006773 // FIXME: this currently happens when we're called from SemaInit
6774 // when user-conversion overload fails. Figure out how to handle
6775 // those conditions and diagnose them well.
6776 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006777 }
John McCall65eb8792010-02-25 01:37:24 +00006778 }
John McCalld3224162010-01-08 00:58:21 +00006779}
6780
6781void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6782 // Desugar the type of the surrogate down to a function type,
6783 // retaining as many typedefs as possible while still showing
6784 // the function type (and, therefore, its parameter types).
6785 QualType FnType = Cand->Surrogate->getConversionType();
6786 bool isLValueReference = false;
6787 bool isRValueReference = false;
6788 bool isPointer = false;
6789 if (const LValueReferenceType *FnTypeRef =
6790 FnType->getAs<LValueReferenceType>()) {
6791 FnType = FnTypeRef->getPointeeType();
6792 isLValueReference = true;
6793 } else if (const RValueReferenceType *FnTypeRef =
6794 FnType->getAs<RValueReferenceType>()) {
6795 FnType = FnTypeRef->getPointeeType();
6796 isRValueReference = true;
6797 }
6798 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6799 FnType = FnTypePtr->getPointeeType();
6800 isPointer = true;
6801 }
6802 // Desugar down to a function type.
6803 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6804 // Reconstruct the pointer/reference as appropriate.
6805 if (isPointer) FnType = S.Context.getPointerType(FnType);
6806 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6807 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6808
6809 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6810 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00006811 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00006812}
6813
6814void NoteBuiltinOperatorCandidate(Sema &S,
6815 const char *Opc,
6816 SourceLocation OpLoc,
6817 OverloadCandidate *Cand) {
6818 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6819 std::string TypeStr("operator");
6820 TypeStr += Opc;
6821 TypeStr += "(";
6822 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6823 if (Cand->Conversions.size() == 1) {
6824 TypeStr += ")";
6825 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6826 } else {
6827 TypeStr += ", ";
6828 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6829 TypeStr += ")";
6830 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6831 }
6832}
6833
6834void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6835 OverloadCandidate *Cand) {
6836 unsigned NoOperands = Cand->Conversions.size();
6837 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6838 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006839 if (ICS.isBad()) break; // all meaningless after first invalid
6840 if (!ICS.isAmbiguous()) continue;
6841
John McCall5c32be02010-08-24 20:38:10 +00006842 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006843 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006844 }
6845}
6846
John McCall3712d9e2010-01-15 23:32:50 +00006847SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6848 if (Cand->Function)
6849 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006850 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006851 return Cand->Surrogate->getLocation();
6852 return SourceLocation();
6853}
6854
John McCallad2587a2010-01-12 00:48:53 +00006855struct CompareOverloadCandidatesForDisplay {
6856 Sema &S;
6857 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006858
6859 bool operator()(const OverloadCandidate *L,
6860 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006861 // Fast-path this check.
6862 if (L == R) return false;
6863
John McCall12f97bc2010-01-08 04:41:39 +00006864 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006865 if (L->Viable) {
6866 if (!R->Viable) return true;
6867
6868 // TODO: introduce a tri-valued comparison for overload
6869 // candidates. Would be more worthwhile if we had a sort
6870 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006871 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6872 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006873 } else if (R->Viable)
6874 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006875
John McCall3712d9e2010-01-15 23:32:50 +00006876 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006877
John McCall3712d9e2010-01-15 23:32:50 +00006878 // Criteria by which we can sort non-viable candidates:
6879 if (!L->Viable) {
6880 // 1. Arity mismatches come after other candidates.
6881 if (L->FailureKind == ovl_fail_too_many_arguments ||
6882 L->FailureKind == ovl_fail_too_few_arguments)
6883 return false;
6884 if (R->FailureKind == ovl_fail_too_many_arguments ||
6885 R->FailureKind == ovl_fail_too_few_arguments)
6886 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006887
John McCallfe796dd2010-01-23 05:17:32 +00006888 // 2. Bad conversions come first and are ordered by the number
6889 // of bad conversions and quality of good conversions.
6890 if (L->FailureKind == ovl_fail_bad_conversion) {
6891 if (R->FailureKind != ovl_fail_bad_conversion)
6892 return true;
6893
6894 // If there's any ordering between the defined conversions...
6895 // FIXME: this might not be transitive.
6896 assert(L->Conversions.size() == R->Conversions.size());
6897
6898 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006899 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6900 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006901 switch (CompareImplicitConversionSequences(S,
6902 L->Conversions[I],
6903 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006904 case ImplicitConversionSequence::Better:
6905 leftBetter++;
6906 break;
6907
6908 case ImplicitConversionSequence::Worse:
6909 leftBetter--;
6910 break;
6911
6912 case ImplicitConversionSequence::Indistinguishable:
6913 break;
6914 }
6915 }
6916 if (leftBetter > 0) return true;
6917 if (leftBetter < 0) return false;
6918
6919 } else if (R->FailureKind == ovl_fail_bad_conversion)
6920 return false;
6921
John McCall3712d9e2010-01-15 23:32:50 +00006922 // TODO: others?
6923 }
6924
6925 // Sort everything else by location.
6926 SourceLocation LLoc = GetLocationForCandidate(L);
6927 SourceLocation RLoc = GetLocationForCandidate(R);
6928
6929 // Put candidates without locations (e.g. builtins) at the end.
6930 if (LLoc.isInvalid()) return false;
6931 if (RLoc.isInvalid()) return true;
6932
6933 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006934 }
6935};
6936
John McCallfe796dd2010-01-23 05:17:32 +00006937/// CompleteNonViableCandidate - Normally, overload resolution only
6938/// computes up to the first
6939void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6940 Expr **Args, unsigned NumArgs) {
6941 assert(!Cand->Viable);
6942
6943 // Don't do anything on failures other than bad conversion.
6944 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6945
6946 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006947 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006948 unsigned ConvCount = Cand->Conversions.size();
6949 while (true) {
6950 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6951 ConvIdx++;
6952 if (Cand->Conversions[ConvIdx - 1].isBad())
6953 break;
6954 }
6955
6956 if (ConvIdx == ConvCount)
6957 return;
6958
John McCall65eb8792010-02-25 01:37:24 +00006959 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6960 "remaining conversion is initialized?");
6961
Douglas Gregoradc7a702010-04-16 17:45:54 +00006962 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006963 // operation somehow.
6964 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006965
6966 const FunctionProtoType* Proto;
6967 unsigned ArgIdx = ConvIdx;
6968
6969 if (Cand->IsSurrogate) {
6970 QualType ConvType
6971 = Cand->Surrogate->getConversionType().getNonReferenceType();
6972 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6973 ConvType = ConvPtrType->getPointeeType();
6974 Proto = ConvType->getAs<FunctionProtoType>();
6975 ArgIdx--;
6976 } else if (Cand->Function) {
6977 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6978 if (isa<CXXMethodDecl>(Cand->Function) &&
6979 !isa<CXXConstructorDecl>(Cand->Function))
6980 ArgIdx--;
6981 } else {
6982 // Builtin binary operator with a bad first conversion.
6983 assert(ConvCount <= 3);
6984 for (; ConvIdx != ConvCount; ++ConvIdx)
6985 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006986 = TryCopyInitialization(S, Args[ConvIdx],
6987 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006988 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006989 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006990 return;
6991 }
6992
6993 // Fill in the rest of the conversions.
6994 unsigned NumArgsInProto = Proto->getNumArgs();
6995 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6996 if (ArgIdx < NumArgsInProto)
6997 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006998 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006999 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007000 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00007001 else
7002 Cand->Conversions[ConvIdx].setEllipsis();
7003 }
7004}
7005
John McCalld3224162010-01-08 00:58:21 +00007006} // end anonymous namespace
7007
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007008/// PrintOverloadCandidates - When overload resolution fails, prints
7009/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007010/// set.
John McCall5c32be02010-08-24 20:38:10 +00007011void OverloadCandidateSet::NoteCandidates(Sema &S,
7012 OverloadCandidateDisplayKind OCD,
7013 Expr **Args, unsigned NumArgs,
7014 const char *Opc,
7015 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007016 // Sort the candidates by viability and position. Sorting directly would
7017 // be prohibitive, so we make a set of pointers and sort those.
7018 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007019 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7020 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007021 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007022 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007023 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007024 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007025 if (Cand->Function || Cand->IsSurrogate)
7026 Cands.push_back(Cand);
7027 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7028 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007029 }
7030 }
7031
John McCallad2587a2010-01-12 00:48:53 +00007032 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007033 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007034
John McCall0d1da222010-01-12 00:44:57 +00007035 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007036
John McCall12f97bc2010-01-08 04:41:39 +00007037 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00007038 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007039 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007040 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7041 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007042
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007043 // Set an arbitrary limit on the number of candidate functions we'll spam
7044 // the user with. FIXME: This limit should depend on details of the
7045 // candidate list.
7046 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7047 break;
7048 }
7049 ++CandsShown;
7050
John McCalld3224162010-01-08 00:58:21 +00007051 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007052 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007053 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007054 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007055 else {
7056 assert(Cand->Viable &&
7057 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007058 // Generally we only see ambiguities including viable builtin
7059 // operators if overload resolution got screwed up by an
7060 // ambiguous user-defined conversion.
7061 //
7062 // FIXME: It's quite possible for different conversions to see
7063 // different ambiguities, though.
7064 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007065 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007066 ReportedAmbiguousConversions = true;
7067 }
John McCalld3224162010-01-08 00:58:21 +00007068
John McCall0d1da222010-01-12 00:44:57 +00007069 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007070 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007071 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007072 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007073
7074 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007075 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007076}
7077
Douglas Gregorb491ed32011-02-19 21:32:49 +00007078// [PossiblyAFunctionType] --> [Return]
7079// NonFunctionType --> NonFunctionType
7080// R (A) --> R(A)
7081// R (*)(A) --> R (A)
7082// R (&)(A) --> R (A)
7083// R (S::*)(A) --> R (A)
7084QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7085 QualType Ret = PossiblyAFunctionType;
7086 if (const PointerType *ToTypePtr =
7087 PossiblyAFunctionType->getAs<PointerType>())
7088 Ret = ToTypePtr->getPointeeType();
7089 else if (const ReferenceType *ToTypeRef =
7090 PossiblyAFunctionType->getAs<ReferenceType>())
7091 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007092 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007093 PossiblyAFunctionType->getAs<MemberPointerType>())
7094 Ret = MemTypePtr->getPointeeType();
7095 Ret =
7096 Context.getCanonicalType(Ret).getUnqualifiedType();
7097 return Ret;
7098}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007099
Douglas Gregorb491ed32011-02-19 21:32:49 +00007100// A helper class to help with address of function resolution
7101// - allows us to avoid passing around all those ugly parameters
7102class AddressOfFunctionResolver
7103{
7104 Sema& S;
7105 Expr* SourceExpr;
7106 const QualType& TargetType;
7107 QualType TargetFunctionType; // Extracted function type from target type
7108
7109 bool Complain;
7110 //DeclAccessPair& ResultFunctionAccessPair;
7111 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007112
Douglas Gregorb491ed32011-02-19 21:32:49 +00007113 bool TargetTypeIsNonStaticMemberFunction;
7114 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007115
Douglas Gregorb491ed32011-02-19 21:32:49 +00007116 OverloadExpr::FindResult OvlExprInfo;
7117 OverloadExpr *OvlExpr;
7118 TemplateArgumentListInfo OvlExplicitTemplateArgs;
John McCalla0296f72010-03-19 07:35:19 +00007119 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007120
Douglas Gregorb491ed32011-02-19 21:32:49 +00007121public:
7122 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7123 const QualType& TargetType, bool Complain)
7124 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7125 Complain(Complain), Context(S.getASTContext()),
7126 TargetTypeIsNonStaticMemberFunction(
7127 !!TargetType->getAs<MemberPointerType>()),
7128 FoundNonTemplateFunction(false),
7129 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7130 OvlExpr(OvlExprInfo.Expression)
7131 {
7132 ExtractUnqualifiedFunctionTypeFromTargetType();
7133
7134 if (!TargetFunctionType->isFunctionType()) {
7135 if (OvlExpr->hasExplicitTemplateArgs()) {
7136 DeclAccessPair dap;
7137 if( FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
7138 OvlExpr, false, &dap) ) {
7139 Matches.push_back(std::make_pair(dap,Fn));
7140 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007141 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007142 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007143 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007144
7145 if (OvlExpr->hasExplicitTemplateArgs())
7146 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007147
Douglas Gregorb491ed32011-02-19 21:32:49 +00007148 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7149 // C++ [over.over]p4:
7150 // If more than one function is selected, [...]
7151 if (Matches.size() > 1) {
7152 if (FoundNonTemplateFunction)
7153 EliminateAllTemplateMatches();
7154 else
7155 EliminateAllExceptMostSpecializedTemplate();
7156 }
7157 }
7158 }
7159
7160private:
7161 bool isTargetTypeAFunction() const {
7162 return TargetFunctionType->isFunctionType();
7163 }
7164
7165 // [ToType] [Return]
7166
7167 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7168 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7169 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7170 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7171 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7172 }
7173
7174 // return true if any matching specializations were found
7175 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7176 const DeclAccessPair& CurAccessFunPair) {
7177 if (CXXMethodDecl *Method
7178 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7179 // Skip non-static function templates when converting to pointer, and
7180 // static when converting to member pointer.
7181 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7182 return false;
7183 }
7184 else if (TargetTypeIsNonStaticMemberFunction)
7185 return false;
7186
7187 // C++ [over.over]p2:
7188 // If the name is a function template, template argument deduction is
7189 // done (14.8.2.2), and if the argument deduction succeeds, the
7190 // resulting template argument list is used to generate a single
7191 // function template specialization, which is added to the set of
7192 // overloaded functions considered.
7193 FunctionDecl *Specialization = 0;
7194 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7195 if (Sema::TemplateDeductionResult Result
7196 = S.DeduceTemplateArguments(FunctionTemplate,
7197 &OvlExplicitTemplateArgs,
7198 TargetFunctionType, Specialization,
7199 Info)) {
7200 // FIXME: make a note of the failed deduction for diagnostics.
7201 (void)Result;
7202 return false;
7203 }
7204
7205 // Template argument deduction ensures that we have an exact match.
7206 // This function template specicalization works.
7207 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7208 assert(TargetFunctionType
7209 == Context.getCanonicalType(Specialization->getType()));
7210 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7211 return true;
7212 }
7213
7214 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7215 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007216 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007217 // Skip non-static functions when converting to pointer, and static
7218 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007219 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7220 return false;
7221 }
7222 else if (TargetTypeIsNonStaticMemberFunction)
7223 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007224
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007225 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007226 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007227 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7228 FunDecl->getType()) ||
7229 IsNoReturnConversion(Context, FunDecl->getType(), TargetFunctionType,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007230 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007231 Matches.push_back(std::make_pair(CurAccessFunPair,
7232 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007233 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007234 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007235 }
Mike Stump11289f42009-09-09 15:08:12 +00007236 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007237
7238 return false;
7239 }
7240
7241 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7242 bool Ret = false;
7243
7244 // If the overload expression doesn't have the form of a pointer to
7245 // member, don't try to convert it to a pointer-to-member type.
7246 if (IsInvalidFormOfPointerToMemberFunction())
7247 return false;
7248
7249 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7250 E = OvlExpr->decls_end();
7251 I != E; ++I) {
7252 // Look through any using declarations to find the underlying function.
7253 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7254
7255 // C++ [over.over]p3:
7256 // Non-member functions and static member functions match
7257 // targets of type "pointer-to-function" or "reference-to-function."
7258 // Nonstatic member functions match targets of
7259 // type "pointer-to-member-function."
7260 // Note that according to DR 247, the containing class does not matter.
7261 if (FunctionTemplateDecl *FunctionTemplate
7262 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7263 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7264 Ret = true;
7265 }
7266 // If we have explicit template arguments supplied, skip non-templates.
7267 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7268 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7269 Ret = true;
7270 }
7271 assert(Ret || Matches.empty());
7272 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007273 }
7274
Douglas Gregorb491ed32011-02-19 21:32:49 +00007275 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00007276 // [...] and any given function template specialization F1 is
7277 // eliminated if the set contains a second function template
7278 // specialization whose function template is more specialized
7279 // than the function template of F1 according to the partial
7280 // ordering rules of 14.5.5.2.
7281
7282 // The algorithm specified above is quadratic. We instead use a
7283 // two-pass algorithm (similar to the one used to identify the
7284 // best viable function in an overload set) that identifies the
7285 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007286
7287 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7288 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7289 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007290
John McCall58cc69d2010-01-27 01:50:18 +00007291 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007292 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7293 TPOC_Other, 0, SourceExpr->getLocStart(),
7294 S.PDiag(),
7295 S.PDiag(diag::err_addr_ovl_ambiguous)
7296 << Matches[0].second->getDeclName(),
7297 S.PDiag(diag::note_ovl_candidate)
7298 << (unsigned) oc_function_template,
7299 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007300
Douglas Gregorb491ed32011-02-19 21:32:49 +00007301 if (Result != MatchesCopy.end()) {
7302 // Make it the first and only element
7303 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7304 Matches[0].second = cast<FunctionDecl>(*Result);
7305 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00007306 }
7307 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007308
Douglas Gregorb491ed32011-02-19 21:32:49 +00007309 void EliminateAllTemplateMatches() {
7310 // [...] any function template specializations in the set are
7311 // eliminated if the set also contains a non-template function, [...]
7312 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7313 if (Matches[I].second->getPrimaryTemplate() == 0)
7314 ++I;
7315 else {
7316 Matches[I] = Matches[--N];
7317 Matches.set_size(N);
7318 }
7319 }
7320 }
7321
7322public:
7323 void ComplainNoMatchesFound() const {
7324 assert(Matches.empty());
7325 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7326 << OvlExpr->getName() << TargetFunctionType
7327 << OvlExpr->getSourceRange();
7328 S.NoteAllOverloadCandidates(OvlExpr);
7329 }
7330
7331 bool IsInvalidFormOfPointerToMemberFunction() const {
7332 return TargetTypeIsNonStaticMemberFunction &&
7333 !OvlExprInfo.HasFormOfMemberPointer;
7334 }
7335
7336 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7337 // TODO: Should we condition this on whether any functions might
7338 // have matched, or is it more appropriate to do that in callers?
7339 // TODO: a fixit wouldn't hurt.
7340 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7341 << TargetType << OvlExpr->getSourceRange();
7342 }
7343
7344 void ComplainOfInvalidConversion() const {
7345 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7346 << OvlExpr->getName() << TargetType;
7347 }
7348
7349 void ComplainMultipleMatchesFound() const {
7350 assert(Matches.size() > 1);
7351 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7352 << OvlExpr->getName()
7353 << OvlExpr->getSourceRange();
7354 S.NoteAllOverloadCandidates(OvlExpr);
7355 }
7356
7357 int getNumMatches() const { return Matches.size(); }
7358
7359 FunctionDecl* getMatchingFunctionDecl() const {
7360 if (Matches.size() != 1) return 0;
7361 return Matches[0].second;
7362 }
7363
7364 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7365 if (Matches.size() != 1) return 0;
7366 return &Matches[0].first;
7367 }
7368};
7369
7370/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7371/// an overloaded function (C++ [over.over]), where @p From is an
7372/// expression with overloaded function type and @p ToType is the type
7373/// we're trying to resolve to. For example:
7374///
7375/// @code
7376/// int f(double);
7377/// int f(int);
7378///
7379/// int (*pfd)(double) = f; // selects f(double)
7380/// @endcode
7381///
7382/// This routine returns the resulting FunctionDecl if it could be
7383/// resolved, and NULL otherwise. When @p Complain is true, this
7384/// routine will emit diagnostics if there is an error.
7385FunctionDecl *
7386Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7387 bool Complain,
7388 DeclAccessPair &FoundResult) {
7389
7390 assert(AddressOfExpr->getType() == Context.OverloadTy);
7391
7392 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7393 int NumMatches = Resolver.getNumMatches();
7394 FunctionDecl* Fn = 0;
7395 if ( NumMatches == 0 && Complain) {
7396 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7397 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7398 else
7399 Resolver.ComplainNoMatchesFound();
7400 }
7401 else if (NumMatches > 1 && Complain)
7402 Resolver.ComplainMultipleMatchesFound();
7403 else if (NumMatches == 1) {
7404 Fn = Resolver.getMatchingFunctionDecl();
7405 assert(Fn);
7406 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7407 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007408 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00007409 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007410 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007411
7412 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007413}
7414
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007415/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007416/// resolve that overloaded function expression down to a single function.
7417///
7418/// This routine can only resolve template-ids that refer to a single function
7419/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007420/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007421/// as described in C++0x [temp.arg.explicit]p3.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007422FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From,
7423 bool Complain,
7424 DeclAccessPair* FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007425 // C++ [over.over]p1:
7426 // [...] [Note: any redundant set of parentheses surrounding the
7427 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007428 // C++ [over.over]p1:
7429 // [...] The overloaded function name can be preceded by the &
7430 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00007431 if (From->getType() != Context.OverloadTy)
7432 return 0;
7433
John McCall8d08b9b2010-08-27 09:08:28 +00007434 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007435
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007436 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00007437 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007438 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007439
7440 TemplateArgumentListInfo ExplicitTemplateArgs;
7441 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007442
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007443 // Look through all of the overloaded functions, searching for one
7444 // whose type matches exactly.
7445 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00007446 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7447 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007448 // C++0x [temp.arg.explicit]p3:
7449 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007450 // where deduction is not done, if a template argument list is
7451 // specified and it, along with any default template arguments,
7452 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007453 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00007454 FunctionTemplateDecl *FunctionTemplate
7455 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007456
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007457 // C++ [over.over]p2:
7458 // If the name is a function template, template argument deduction is
7459 // done (14.8.2.2), and if the argument deduction succeeds, the
7460 // resulting template argument list is used to generate a single
7461 // function template specialization, which is added to the set of
7462 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007463 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00007464 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007465 if (TemplateDeductionResult Result
7466 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7467 Specialization, Info)) {
7468 // FIXME: make a note of the failed deduction for diagnostics.
7469 (void)Result;
7470 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007471 }
7472
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007473 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007474 if (Matched) {
7475 if (FoundResult)
7476 *FoundResult = DeclAccessPair();
7477
7478 if (Complain) {
7479 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
7480 << OvlExpr->getName();
7481 NoteAllOverloadCandidates(OvlExpr);
7482 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007483 return 0;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007484 }
7485
7486 if ((Matched = Specialization) && FoundResult)
7487 *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007488 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007489
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007490 return Matched;
7491}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007492
Douglas Gregorcabea402009-09-22 15:41:20 +00007493/// \brief Add a single candidate to the overload set.
7494static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00007495 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00007496 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007497 Expr **Args, unsigned NumArgs,
7498 OverloadCandidateSet &CandidateSet,
7499 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00007500 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00007501 if (isa<UsingShadowDecl>(Callee))
7502 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7503
Douglas Gregorcabea402009-09-22 15:41:20 +00007504 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00007505 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00007506 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007507 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007508 return;
John McCalld14a8642009-11-21 08:51:07 +00007509 }
7510
7511 if (FunctionTemplateDecl *FuncTemplate
7512 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00007513 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7514 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007515 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00007516 return;
7517 }
7518
7519 assert(false && "unhandled case in overloaded call candidate");
7520
7521 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00007522}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007523
Douglas Gregorcabea402009-09-22 15:41:20 +00007524/// \brief Add the overload candidates named by callee and/or found by argument
7525/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00007526void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00007527 Expr **Args, unsigned NumArgs,
7528 OverloadCandidateSet &CandidateSet,
7529 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00007530
7531#ifndef NDEBUG
7532 // Verify that ArgumentDependentLookup is consistent with the rules
7533 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00007534 //
Douglas Gregorcabea402009-09-22 15:41:20 +00007535 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7536 // and let Y be the lookup set produced by argument dependent
7537 // lookup (defined as follows). If X contains
7538 //
7539 // -- a declaration of a class member, or
7540 //
7541 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00007542 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00007543 //
7544 // -- a declaration that is neither a function or a function
7545 // template
7546 //
7547 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00007548
John McCall57500772009-12-16 12:17:52 +00007549 if (ULE->requiresADL()) {
7550 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7551 E = ULE->decls_end(); I != E; ++I) {
7552 assert(!(*I)->getDeclContext()->isRecord());
7553 assert(isa<UsingShadowDecl>(*I) ||
7554 !(*I)->getDeclContext()->isFunctionOrMethod());
7555 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00007556 }
7557 }
7558#endif
7559
John McCall57500772009-12-16 12:17:52 +00007560 // It would be nice to avoid this copy.
7561 TemplateArgumentListInfo TABuffer;
7562 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7563 if (ULE->hasExplicitTemplateArgs()) {
7564 ULE->copyTemplateArgumentsInto(TABuffer);
7565 ExplicitTemplateArgs = &TABuffer;
7566 }
7567
7568 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7569 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00007570 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007571 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00007572 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00007573
John McCall57500772009-12-16 12:17:52 +00007574 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00007575 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7576 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007577 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007578 CandidateSet,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007579 PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007580}
John McCalld681c392009-12-16 08:11:27 +00007581
7582/// Attempts to recover from a call where no functions were found.
7583///
7584/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00007585static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007586BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00007587 UnresolvedLookupExpr *ULE,
7588 SourceLocation LParenLoc,
7589 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007590 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00007591
7592 CXXScopeSpec SS;
Douglas Gregor2ab3fee2011-02-24 00:49:34 +00007593 if (ULE->getQualifier())
Douglas Gregor869ad452011-02-24 17:54:50 +00007594 SS.MakeTrivial(SemaRef.Context,
7595 ULE->getQualifier(), ULE->getQualifierRange());
John McCalld681c392009-12-16 08:11:27 +00007596
John McCall57500772009-12-16 12:17:52 +00007597 TemplateArgumentListInfo TABuffer;
7598 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7599 if (ULE->hasExplicitTemplateArgs()) {
7600 ULE->copyTemplateArgumentsInto(TABuffer);
7601 ExplicitTemplateArgs = &TABuffer;
7602 }
7603
John McCalld681c392009-12-16 08:11:27 +00007604 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7605 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00007606 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00007607 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00007608
John McCall57500772009-12-16 12:17:52 +00007609 assert(!R.empty() && "lookup results empty despite recovery");
7610
7611 // Build an implicit member call if appropriate. Just drop the
7612 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00007613 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00007614 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00007615 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7616 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00007617 else if (ExplicitTemplateArgs)
7618 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7619 else
7620 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7621
7622 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007623 return ExprError();
John McCall57500772009-12-16 12:17:52 +00007624
7625 // This shouldn't cause an infinite loop because we're giving it
7626 // an expression with non-empty lookup results, which should never
7627 // end up here.
John McCallb268a282010-08-23 23:25:46 +00007628 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007629 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007630}
Douglas Gregor4038cf42010-06-08 17:35:15 +00007631
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007632/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00007633/// (which eventually refers to the declaration Func) and the call
7634/// arguments Args/NumArgs, attempt to resolve the function call down
7635/// to a specific function. If overload resolution succeeds, returns
7636/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00007637/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007638/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00007639ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007640Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00007641 SourceLocation LParenLoc,
7642 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00007643 SourceLocation RParenLoc,
7644 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00007645#ifndef NDEBUG
7646 if (ULE->requiresADL()) {
7647 // To do ADL, we must have found an unqualified name.
7648 assert(!ULE->getQualifier() && "qualified name with ADL");
7649
7650 // We don't perform ADL for implicit declarations of builtins.
7651 // Verify that this was correctly set up.
7652 FunctionDecl *F;
7653 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7654 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7655 F->getBuiltinID() && F->isImplicit())
7656 assert(0 && "performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007657
John McCall57500772009-12-16 12:17:52 +00007658 // We don't perform ADL in C.
7659 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7660 }
7661#endif
7662
John McCallbc077cf2010-02-08 23:07:23 +00007663 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007664
John McCall57500772009-12-16 12:17:52 +00007665 // Add the functions denoted by the callee to the set of candidate
7666 // functions, including those from argument-dependent lookup.
7667 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007668
7669 // If we found nothing, try to recover.
7670 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7671 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007672 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007673 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007674 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007675
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007676 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007677 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007678 case OR_Success: {
7679 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00007680 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00007681 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007682 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7683 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007684 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00007685 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
7686 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00007687 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007688
7689 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007690 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007691 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007692 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007693 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007694 break;
7695
7696 case OR_Ambiguous:
7697 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007698 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007699 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007700 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007701
7702 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00007703 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00007704 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7705 << Best->Function->isDeleted()
7706 << ULE->getName()
7707 << Best->Function->getMessageUnavailableAttr(
7708 !Best->Function->isDeleted())
7709 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00007710 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7711 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00007712 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007713 }
7714
Douglas Gregorb412e172010-07-25 18:17:45 +00007715 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007716 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007717}
7718
John McCall4c4c1df2010-01-26 03:27:55 +00007719static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007720 return Functions.size() > 1 ||
7721 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7722}
7723
Douglas Gregor084d8552009-03-13 23:49:33 +00007724/// \brief Create a unary operation that may resolve to an overloaded
7725/// operator.
7726///
7727/// \param OpLoc The location of the operator itself (e.g., '*').
7728///
7729/// \param OpcIn The UnaryOperator::Opcode that describes this
7730/// operator.
7731///
7732/// \param Functions The set of non-member functions that will be
7733/// considered by overload resolution. The caller needs to build this
7734/// set based on the context using, e.g.,
7735/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7736/// set should not contain any member functions; those will be added
7737/// by CreateOverloadedUnaryOp().
7738///
7739/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007740ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007741Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7742 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007743 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007744 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007745
7746 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7747 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7748 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007749 // TODO: provide better source location info.
7750 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007751
John McCalle26a8722010-12-04 08:14:53 +00007752 if (Input->getObjectKind() == OK_ObjCProperty)
7753 ConvertPropertyForRValue(Input);
7754
Douglas Gregor084d8552009-03-13 23:49:33 +00007755 Expr *Args[2] = { Input, 0 };
7756 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007757
Douglas Gregor084d8552009-03-13 23:49:33 +00007758 // For post-increment and post-decrement, add the implicit '0' as
7759 // the second argument, so that we know this is a post-increment or
7760 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007761 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007762 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007763 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7764 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007765 NumArgs = 2;
7766 }
7767
7768 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007769 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007770 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007771 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00007772 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007773 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00007774 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007775
John McCall58cc69d2010-01-27 01:50:18 +00007776 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007777 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007778 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007779 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007780 /*ADL*/ true, IsOverloaded(Fns),
7781 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007782 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7783 &Args[0], NumArgs,
7784 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007785 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00007786 OpLoc));
7787 }
7788
7789 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007790 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007791
7792 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007793 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007794
7795 // Add operator candidates that are member functions.
7796 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7797
John McCall4c4c1df2010-01-26 03:27:55 +00007798 // Add candidates from ADL.
7799 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007800 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007801 /*ExplicitTemplateArgs*/ 0,
7802 CandidateSet);
7803
Douglas Gregor084d8552009-03-13 23:49:33 +00007804 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007805 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007806
7807 // Perform overload resolution.
7808 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007809 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007810 case OR_Success: {
7811 // We found a built-in operator or an overloaded operator.
7812 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007813
Douglas Gregor084d8552009-03-13 23:49:33 +00007814 if (FnDecl) {
7815 // We matched an overloaded operator. Build a call to that
7816 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007817
Chandler Carruth30141632011-02-25 19:41:05 +00007818 MarkDeclarationReferenced(OpLoc, FnDecl);
7819
Douglas Gregor084d8552009-03-13 23:49:33 +00007820 // Convert the arguments.
7821 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007822 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007823
John McCall16df1e52010-03-30 21:47:33 +00007824 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7825 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007826 return ExprError();
7827 } else {
7828 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007829 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007830 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007831 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007832 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007833 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007834 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007835 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007836 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007837 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007838 }
7839
John McCall4fa0d5f2010-05-06 18:15:07 +00007840 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7841
John McCall7decc9e2010-11-18 06:31:45 +00007842 // Determine the result type.
7843 QualType ResultTy = FnDecl->getResultType();
7844 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7845 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00007846
Douglas Gregor084d8552009-03-13 23:49:33 +00007847 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007848 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007849
Eli Friedman030eee42009-11-18 03:58:17 +00007850 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007851 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007852 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007853 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007854
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007855 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007856 FnDecl))
7857 return ExprError();
7858
John McCallb268a282010-08-23 23:25:46 +00007859 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007860 } else {
7861 // We matched a built-in operator. Convert the arguments, then
7862 // break out so that we will build the appropriate built-in
7863 // operator node.
7864 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007865 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007866 return ExprError();
7867
7868 break;
7869 }
7870 }
7871
7872 case OR_No_Viable_Function:
7873 // No viable function; fall through to handling this as a
7874 // built-in operator, which will produce an error message for us.
7875 break;
7876
7877 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007878 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregor084d8552009-03-13 23:49:33 +00007879 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007880 << Input->getType()
Douglas Gregor084d8552009-03-13 23:49:33 +00007881 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007882 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7883 Args, NumArgs,
7884 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007885 return ExprError();
7886
7887 case OR_Deleted:
7888 Diag(OpLoc, diag::err_ovl_deleted_oper)
7889 << Best->Function->isDeleted()
7890 << UnaryOperator::getOpcodeStr(Opc)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00007891 << Best->Function->getMessageUnavailableAttr(
7892 !Best->Function->isDeleted())
Douglas Gregor084d8552009-03-13 23:49:33 +00007893 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007894 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007895 return ExprError();
7896 }
7897
7898 // Either we found no viable overloaded operator or we matched a
7899 // built-in operator. In either case, fall through to trying to
7900 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007901 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007902}
7903
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007904/// \brief Create a binary operation that may resolve to an overloaded
7905/// operator.
7906///
7907/// \param OpLoc The location of the operator itself (e.g., '+').
7908///
7909/// \param OpcIn The BinaryOperator::Opcode that describes this
7910/// operator.
7911///
7912/// \param Functions The set of non-member functions that will be
7913/// considered by overload resolution. The caller needs to build this
7914/// set based on the context using, e.g.,
7915/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7916/// set should not contain any member functions; those will be added
7917/// by CreateOverloadedBinOp().
7918///
7919/// \param LHS Left-hand argument.
7920/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00007921ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007922Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007923 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00007924 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007925 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007926 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00007927 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007928
7929 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7930 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7931 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7932
7933 // If either side is type-dependent, create an appropriate dependent
7934 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00007935 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00007936 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007937 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00007938 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00007939 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00007940 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00007941 Context.DependentTy,
7942 VK_RValue, OK_Ordinary,
7943 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007944
Douglas Gregor5287f092009-11-05 00:51:44 +00007945 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7946 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007947 VK_LValue,
7948 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00007949 Context.DependentTy,
7950 Context.DependentTy,
7951 OpLoc));
7952 }
John McCall4c4c1df2010-01-26 03:27:55 +00007953
7954 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00007955 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007956 // TODO: provide better source location info in DNLoc component.
7957 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00007958 UnresolvedLookupExpr *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007959 = UnresolvedLookupExpr::Create(Context, NamingClass, 0, SourceRange(),
Douglas Gregora6e053e2010-12-15 01:34:56 +00007960 OpNameInfo, /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007961 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007962 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00007963 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007964 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007965 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007966 OpLoc));
7967 }
7968
John McCalle26a8722010-12-04 08:14:53 +00007969 // Always do property rvalue conversions on the RHS.
7970 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7971 ConvertPropertyForRValue(Args[1]);
7972
7973 // The LHS is more complicated.
7974 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
7975
7976 // There's a tension for assignment operators between primitive
7977 // property assignment and the overloaded operators.
7978 if (BinaryOperator::isAssignmentOp(Opc)) {
7979 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7980
7981 // Is the property "logically" settable?
7982 bool Settable = (PRE->isExplicitProperty() ||
7983 PRE->getImplicitPropertySetter());
7984
7985 // To avoid gratuitously inventing semantics, use the primitive
7986 // unless it isn't. Thoughts in case we ever really care:
7987 // - If the property isn't logically settable, we have to
7988 // load and hope.
7989 // - If the property is settable and this is simple assignment,
7990 // we really should use the primitive.
7991 // - If the property is settable, then we could try overloading
7992 // on a generic lvalue of the appropriate type; if it works
7993 // out to a builtin candidate, we would do that same operation
7994 // on the property, and otherwise just error.
7995 if (Settable)
7996 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7997 }
7998
7999 ConvertPropertyForRValue(Args[0]);
8000 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008001
Sebastian Redl6a96bf72009-11-18 23:10:33 +00008002 // If this is the assignment operator, we only perform overload resolution
8003 // if the left-hand side is a class or enumeration type. This is actually
8004 // a hack. The standard requires that we do overload resolution between the
8005 // various built-in candidates, but as DR507 points out, this can lead to
8006 // problems. So we do it this way, which pretty much follows what GCC does.
8007 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00008008 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00008009 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008010
John McCalle26a8722010-12-04 08:14:53 +00008011 // If this is the .* operator, which is not overloadable, just
8012 // create a built-in binary operator.
8013 if (Opc == BO_PtrMemD)
8014 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8015
Douglas Gregor084d8552009-03-13 23:49:33 +00008016 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008017 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008018
8019 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008020 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008021
8022 // Add operator candidates that are member functions.
8023 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8024
John McCall4c4c1df2010-01-26 03:27:55 +00008025 // Add candidates from ADL.
8026 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8027 Args, 2,
8028 /*ExplicitTemplateArgs*/ 0,
8029 CandidateSet);
8030
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008031 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008032 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008033
8034 // Perform overload resolution.
8035 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008036 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00008037 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008038 // We found a built-in operator or an overloaded operator.
8039 FunctionDecl *FnDecl = Best->Function;
8040
8041 if (FnDecl) {
8042 // We matched an overloaded operator. Build a call to that
8043 // operator.
8044
Chandler Carruth30141632011-02-25 19:41:05 +00008045 MarkDeclarationReferenced(OpLoc, FnDecl);
8046
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008047 // Convert the arguments.
8048 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00008049 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00008050 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008051
Chandler Carruth8e543b32010-12-12 08:17:55 +00008052 ExprResult Arg1 =
8053 PerformCopyInitialization(
8054 InitializedEntity::InitializeParameter(Context,
8055 FnDecl->getParamDecl(0)),
8056 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008057 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008058 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008059
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008060 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008061 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008062 return ExprError();
8063
8064 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008065 } else {
8066 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00008067 ExprResult Arg0 = PerformCopyInitialization(
8068 InitializedEntity::InitializeParameter(Context,
8069 FnDecl->getParamDecl(0)),
8070 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008071 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008072 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008073
Chandler Carruth8e543b32010-12-12 08:17:55 +00008074 ExprResult Arg1 =
8075 PerformCopyInitialization(
8076 InitializedEntity::InitializeParameter(Context,
8077 FnDecl->getParamDecl(1)),
8078 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008079 if (Arg1.isInvalid())
8080 return ExprError();
8081 Args[0] = LHS = Arg0.takeAs<Expr>();
8082 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008083 }
8084
John McCall4fa0d5f2010-05-06 18:15:07 +00008085 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8086
John McCall7decc9e2010-11-18 06:31:45 +00008087 // Determine the result type.
8088 QualType ResultTy = FnDecl->getResultType();
8089 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8090 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008091
8092 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00008093 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008094
John McCallb268a282010-08-23 23:25:46 +00008095 CXXOperatorCallExpr *TheCall =
8096 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008097 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008098
8099 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008100 FnDecl))
8101 return ExprError();
8102
John McCallb268a282010-08-23 23:25:46 +00008103 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008104 } else {
8105 // We matched a built-in operator. Convert the arguments, then
8106 // break out so that we will build the appropriate built-in
8107 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00008108 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008109 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00008110 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008111 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008112 return ExprError();
8113
8114 break;
8115 }
8116 }
8117
Douglas Gregor66950a32009-09-30 21:46:01 +00008118 case OR_No_Viable_Function: {
8119 // C++ [over.match.oper]p9:
8120 // If the operator is the operator , [...] and there are no
8121 // viable functions, then the operator is assumed to be the
8122 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00008123 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00008124 break;
8125
Chandler Carruth8e543b32010-12-12 08:17:55 +00008126 // For class as left operand for assignment or compound assigment
8127 // operator do not fall through to handling in built-in, but report that
8128 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00008129 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008130 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00008131 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00008132 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8133 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00008134 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00008135 } else {
8136 // No viable function; try to create a built-in operation, which will
8137 // produce an error. Then, show the non-viable candidates.
8138 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00008139 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008140 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00008141 "C++ binary operator overloading is missing candidates!");
8142 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00008143 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8144 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00008145 return move(Result);
8146 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008147
8148 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008149 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008150 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00008151 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00008152 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008153 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8154 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008155 return ExprError();
8156
8157 case OR_Deleted:
8158 Diag(OpLoc, diag::err_ovl_deleted_oper)
8159 << Best->Function->isDeleted()
8160 << BinaryOperator::getOpcodeStr(Opc)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008161 << Best->Function->getMessageUnavailableAttr(
8162 !Best->Function->isDeleted())
Douglas Gregore9899d92009-08-26 17:08:25 +00008163 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008164 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008165 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00008166 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008167
Douglas Gregor66950a32009-09-30 21:46:01 +00008168 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00008169 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008170}
8171
John McCalldadc5752010-08-24 06:29:42 +00008172ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00008173Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8174 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00008175 Expr *Base, Expr *Idx) {
8176 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00008177 DeclarationName OpName =
8178 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8179
8180 // If either side is type-dependent, create an appropriate dependent
8181 // expression.
8182 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8183
John McCall58cc69d2010-01-27 01:50:18 +00008184 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008185 // CHECKME: no 'operator' keyword?
8186 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8187 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00008188 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008189 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008190 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008191 /*ADL*/ true, /*Overloaded*/ false,
8192 UnresolvedSetIterator(),
8193 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00008194 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00008195
Sebastian Redladba46e2009-10-29 20:17:01 +00008196 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8197 Args, 2,
8198 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008199 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00008200 RLoc));
8201 }
8202
John McCalle26a8722010-12-04 08:14:53 +00008203 if (Args[0]->getObjectKind() == OK_ObjCProperty)
8204 ConvertPropertyForRValue(Args[0]);
8205 if (Args[1]->getObjectKind() == OK_ObjCProperty)
8206 ConvertPropertyForRValue(Args[1]);
8207
Sebastian Redladba46e2009-10-29 20:17:01 +00008208 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008209 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008210
8211 // Subscript can only be overloaded as a member function.
8212
8213 // Add operator candidates that are member functions.
8214 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8215
8216 // Add builtin operator candidates.
8217 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8218
8219 // Perform overload resolution.
8220 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008221 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00008222 case OR_Success: {
8223 // We found a built-in operator or an overloaded operator.
8224 FunctionDecl *FnDecl = Best->Function;
8225
8226 if (FnDecl) {
8227 // We matched an overloaded operator. Build a call to that
8228 // operator.
8229
Chandler Carruth30141632011-02-25 19:41:05 +00008230 MarkDeclarationReferenced(LLoc, FnDecl);
8231
John McCalla0296f72010-03-19 07:35:19 +00008232 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008233 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00008234
Sebastian Redladba46e2009-10-29 20:17:01 +00008235 // Convert the arguments.
8236 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008237 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008238 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00008239 return ExprError();
8240
Anders Carlssona68e51e2010-01-29 18:37:50 +00008241 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008242 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00008243 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008244 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00008245 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008246 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00008247 Owned(Args[1]));
8248 if (InputInit.isInvalid())
8249 return ExprError();
8250
8251 Args[1] = InputInit.takeAs<Expr>();
8252
Sebastian Redladba46e2009-10-29 20:17:01 +00008253 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00008254 QualType ResultTy = FnDecl->getResultType();
8255 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8256 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00008257
8258 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00008259 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008260
John McCallb268a282010-08-23 23:25:46 +00008261 CXXOperatorCallExpr *TheCall =
8262 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
8263 FnExpr, Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00008264 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008265
John McCallb268a282010-08-23 23:25:46 +00008266 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00008267 FnDecl))
8268 return ExprError();
8269
John McCallb268a282010-08-23 23:25:46 +00008270 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00008271 } else {
8272 // We matched a built-in operator. Convert the arguments, then
8273 // break out so that we will build the appropriate built-in
8274 // operator node.
8275 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008276 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00008277 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00008278 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00008279 return ExprError();
8280
8281 break;
8282 }
8283 }
8284
8285 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00008286 if (CandidateSet.empty())
8287 Diag(LLoc, diag::err_ovl_no_oper)
8288 << Args[0]->getType() << /*subscript*/ 0
8289 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8290 else
8291 Diag(LLoc, diag::err_ovl_no_viable_subscript)
8292 << Args[0]->getType()
8293 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008294 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8295 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00008296 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00008297 }
8298
8299 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008300 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008301 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00008302 << Args[0]->getType() << Args[1]->getType()
8303 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008304 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8305 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008306 return ExprError();
8307
8308 case OR_Deleted:
8309 Diag(LLoc, diag::err_ovl_deleted_oper)
8310 << Best->Function->isDeleted() << "[]"
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008311 << Best->Function->getMessageUnavailableAttr(
8312 !Best->Function->isDeleted())
Sebastian Redladba46e2009-10-29 20:17:01 +00008313 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008314 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8315 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008316 return ExprError();
8317 }
8318
8319 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00008320 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008321}
8322
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008323/// BuildCallToMemberFunction - Build a call to a member
8324/// function. MemExpr is the expression that refers to the member
8325/// function (and includes the object parameter), Args/NumArgs are the
8326/// arguments to the function call (not including the object
8327/// parameter). The caller needs to validate that the member
8328/// expression refers to a member function or an overloaded member
8329/// function.
John McCalldadc5752010-08-24 06:29:42 +00008330ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008331Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8332 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008333 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008334 // Dig out the member expression. This holds both the object
8335 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00008336 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008337
John McCall10eae182009-11-30 22:42:35 +00008338 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008339 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00008340 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008341 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00008342 if (isa<MemberExpr>(NakedMemExpr)) {
8343 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00008344 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00008345 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008346 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00008347 } else {
8348 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008349 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008350
John McCall6e9f8f62009-12-03 04:06:58 +00008351 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00008352 Expr::Classification ObjectClassification
8353 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
8354 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00008355
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008356 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00008357 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00008358
John McCall2d74de92009-12-01 22:10:20 +00008359 // FIXME: avoid copy.
8360 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8361 if (UnresExpr->hasExplicitTemplateArgs()) {
8362 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8363 TemplateArgs = &TemplateArgsBuffer;
8364 }
8365
John McCall10eae182009-11-30 22:42:35 +00008366 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
8367 E = UnresExpr->decls_end(); I != E; ++I) {
8368
John McCall6e9f8f62009-12-03 04:06:58 +00008369 NamedDecl *Func = *I;
8370 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
8371 if (isa<UsingShadowDecl>(Func))
8372 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
8373
Douglas Gregor02824322011-01-26 19:30:28 +00008374
Francois Pichet64225792011-01-18 05:04:39 +00008375 // Microsoft supports direct constructor calls.
8376 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
8377 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
8378 CandidateSet);
8379 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00008380 // If explicit template arguments were provided, we can't call a
8381 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00008382 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00008383 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008384
John McCalla0296f72010-03-19 07:35:19 +00008385 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008386 ObjectClassification,
8387 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00008388 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008389 } else {
John McCall10eae182009-11-30 22:42:35 +00008390 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00008391 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008392 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00008393 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008394 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008395 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008396 }
Mike Stump11289f42009-09-09 15:08:12 +00008397
John McCall10eae182009-11-30 22:42:35 +00008398 DeclarationName DeclName = UnresExpr->getMemberName();
8399
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008400 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008401 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00008402 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008403 case OR_Success:
8404 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00008405 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00008406 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00008407 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008408 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008409 break;
8410
8411 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00008412 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008413 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008414 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008415 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008416 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008417 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008418
8419 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00008420 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008421 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008422 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008423 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008424 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008425
8426 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00008427 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00008428 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008429 << DeclName
8430 << Best->Function->getMessageUnavailableAttr(
8431 !Best->Function->isDeleted())
8432 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008433 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008434 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008435 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008436 }
8437
John McCall16df1e52010-03-30 21:47:33 +00008438 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00008439
John McCall2d74de92009-12-01 22:10:20 +00008440 // If overload resolution picked a static member, build a
8441 // non-member call based on that function.
8442 if (Method->isStatic()) {
8443 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8444 Args, NumArgs, RParenLoc);
8445 }
8446
John McCall10eae182009-11-30 22:42:35 +00008447 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008448 }
8449
John McCall7decc9e2010-11-18 06:31:45 +00008450 QualType ResultType = Method->getResultType();
8451 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8452 ResultType = ResultType.getNonLValueExprType(Context);
8453
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008454 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008455 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00008456 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008457 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008458
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008459 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008460 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00008461 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00008462 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008463
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008464 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00008465 // We only need to do this if there was actually an overload; otherwise
8466 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00008467 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00008468 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00008469 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
8470 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00008471 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008472 MemExpr->setBase(ObjectArg);
8473
8474 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00008475 const FunctionProtoType *Proto =
8476 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00008477 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008478 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00008479 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008480
John McCallb268a282010-08-23 23:25:46 +00008481 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00008482 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00008483
John McCallb268a282010-08-23 23:25:46 +00008484 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008485}
8486
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008487/// BuildCallToObjectOfClassType - Build a call to an object of class
8488/// type (C++ [over.call.object]), which can end up invoking an
8489/// overloaded function call operator (@c operator()) or performing a
8490/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00008491ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008492Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00008493 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008494 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008495 SourceLocation RParenLoc) {
John McCalle26a8722010-12-04 08:14:53 +00008496 if (Object->getObjectKind() == OK_ObjCProperty)
8497 ConvertPropertyForRValue(Object);
8498
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008499 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008500 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00008501
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008502 // C++ [over.call.object]p1:
8503 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00008504 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008505 // candidate functions includes at least the function call
8506 // operators of T. The function call operators of T are obtained by
8507 // ordinary lookup of the name operator() in the context of
8508 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00008509 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00008510 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008511
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008512 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00008513 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008514 << Object->getSourceRange()))
8515 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008516
John McCall27b18f82009-11-17 02:14:36 +00008517 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8518 LookupQualifiedName(R, Record->getDecl());
8519 R.suppressDiagnostics();
8520
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008521 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00008522 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008523 AddMethodCandidate(Oper.getPair(), Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00008524 Object->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00008525 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00008526 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008527
Douglas Gregorab7897a2008-11-19 22:57:39 +00008528 // C++ [over.call.object]p2:
8529 // In addition, for each conversion function declared in T of the
8530 // form
8531 //
8532 // operator conversion-type-id () cv-qualifier;
8533 //
8534 // where cv-qualifier is the same cv-qualification as, or a
8535 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00008536 // denotes the type "pointer to function of (P1,...,Pn) returning
8537 // R", or the type "reference to pointer to function of
8538 // (P1,...,Pn) returning R", or the type "reference to function
8539 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00008540 // is also considered as a candidate function. Similarly,
8541 // surrogate call functions are added to the set of candidate
8542 // functions for each conversion function declared in an
8543 // accessible base class provided the function is not hidden
8544 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00008545 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00008546 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00008547 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00008548 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00008549 NamedDecl *D = *I;
8550 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8551 if (isa<UsingShadowDecl>(D))
8552 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008553
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008554 // Skip over templated conversion functions; they aren't
8555 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00008556 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008557 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00008558
John McCall6e9f8f62009-12-03 04:06:58 +00008559 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00008560
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008561 // Strip the reference type (if any) and then the pointer type (if
8562 // any) to get down to what might be a function type.
8563 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8564 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8565 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00008566
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008567 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00008568 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00008569 Object, Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008570 }
Mike Stump11289f42009-09-09 15:08:12 +00008571
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008572 // Perform overload resolution.
8573 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008574 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
8575 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008576 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00008577 // Overload resolution succeeded; we'll build the appropriate call
8578 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008579 break;
8580
8581 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00008582 if (CandidateSet.empty())
8583 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8584 << Object->getType() << /*call*/ 1
8585 << Object->getSourceRange();
8586 else
8587 Diag(Object->getSourceRange().getBegin(),
8588 diag::err_ovl_no_viable_object_call)
8589 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008590 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008591 break;
8592
8593 case OR_Ambiguous:
8594 Diag(Object->getSourceRange().getBegin(),
8595 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008596 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008597 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008598 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008599
8600 case OR_Deleted:
8601 Diag(Object->getSourceRange().getBegin(),
8602 diag::err_ovl_deleted_object_call)
8603 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008604 << Object->getType()
8605 << Best->Function->getMessageUnavailableAttr(
8606 !Best->Function->isDeleted())
8607 << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008608 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008609 break;
Mike Stump11289f42009-09-09 15:08:12 +00008610 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008611
Douglas Gregorb412e172010-07-25 18:17:45 +00008612 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008613 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008614
Douglas Gregorab7897a2008-11-19 22:57:39 +00008615 if (Best->Function == 0) {
8616 // Since there is no function declaration, this is one of the
8617 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00008618 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00008619 = cast<CXXConversionDecl>(
8620 Best->Conversions[0].UserDefined.ConversionFunction);
8621
John McCalla0296f72010-03-19 07:35:19 +00008622 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008623 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008624
Douglas Gregorab7897a2008-11-19 22:57:39 +00008625 // We selected one of the surrogate functions that converts the
8626 // object parameter to a function pointer. Perform the conversion
8627 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008628
Fariborz Jahanian774cf792009-09-28 18:35:46 +00008629 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00008630 // and then call it.
Douglas Gregor668443e2011-01-20 00:18:04 +00008631 ExprResult Call = BuildCXXMemberCallExpr(Object, Best->FoundDecl, Conv);
8632 if (Call.isInvalid())
8633 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008634
Douglas Gregor668443e2011-01-20 00:18:04 +00008635 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008636 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008637 }
8638
Chandler Carruth30141632011-02-25 19:41:05 +00008639 MarkDeclarationReferenced(LParenLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00008640 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008641 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008642
Douglas Gregorab7897a2008-11-19 22:57:39 +00008643 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8644 // that calls this method, using Object for the implicit object
8645 // parameter and passing along the remaining arguments.
8646 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008647 const FunctionProtoType *Proto =
8648 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008649
8650 unsigned NumArgsInProto = Proto->getNumArgs();
8651 unsigned NumArgsToCheck = NumArgs;
8652
8653 // Build the full argument list for the method call (the
8654 // implicit object parameter is placed at the beginning of the
8655 // list).
8656 Expr **MethodArgs;
8657 if (NumArgs < NumArgsInProto) {
8658 NumArgsToCheck = NumArgsInProto;
8659 MethodArgs = new Expr*[NumArgsInProto + 1];
8660 } else {
8661 MethodArgs = new Expr*[NumArgs + 1];
8662 }
8663 MethodArgs[0] = Object;
8664 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8665 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00008666
John McCall7decc9e2010-11-18 06:31:45 +00008667 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008668
8669 // Once we've built TheCall, all of the expressions are properly
8670 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00008671 QualType ResultTy = Method->getResultType();
8672 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8673 ResultTy = ResultTy.getNonLValueExprType(Context);
8674
John McCallb268a282010-08-23 23:25:46 +00008675 CXXOperatorCallExpr *TheCall =
8676 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
8677 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00008678 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008679 delete [] MethodArgs;
8680
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008681 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00008682 Method))
8683 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008684
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008685 // We may have default arguments. If so, we need to allocate more
8686 // slots in the call for them.
8687 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00008688 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008689 else if (NumArgs > NumArgsInProto)
8690 NumArgsToCheck = NumArgsInProto;
8691
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008692 bool IsError = false;
8693
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008694 // Initialize the implicit object parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008695 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008696 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008697 TheCall->setArg(0, Object);
8698
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008699
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008700 // Check the argument types.
8701 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008702 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008703 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008704 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00008705
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008706 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008707
John McCalldadc5752010-08-24 06:29:42 +00008708 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008709 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008710 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008711 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00008712 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008713
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008714 IsError |= InputInit.isInvalid();
8715 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008716 } else {
John McCalldadc5752010-08-24 06:29:42 +00008717 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008718 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8719 if (DefArg.isInvalid()) {
8720 IsError = true;
8721 break;
8722 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008723
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008724 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008725 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008726
8727 TheCall->setArg(i + 1, Arg);
8728 }
8729
8730 // If this is a variadic call, handle args passed through "...".
8731 if (Proto->isVariadic()) {
8732 // Promote the arguments (C99 6.5.2.2p7).
8733 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8734 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00008735 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008736 TheCall->setArg(i + 1, Arg);
8737 }
8738 }
8739
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008740 if (IsError) return true;
8741
John McCallb268a282010-08-23 23:25:46 +00008742 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00008743 return true;
8744
John McCalle172be52010-08-24 06:09:16 +00008745 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008746}
8747
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008748/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00008749/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008750/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00008751ExprResult
John McCallb268a282010-08-23 23:25:46 +00008752Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008753 assert(Base->getType()->isRecordType() &&
8754 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00008755
John McCalle26a8722010-12-04 08:14:53 +00008756 if (Base->getObjectKind() == OK_ObjCProperty)
8757 ConvertPropertyForRValue(Base);
8758
John McCallbc077cf2010-02-08 23:07:23 +00008759 SourceLocation Loc = Base->getExprLoc();
8760
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008761 // C++ [over.ref]p1:
8762 //
8763 // [...] An expression x->m is interpreted as (x.operator->())->m
8764 // for a class object x of type T if T::operator->() exists and if
8765 // the operator is selected as the best match function by the
8766 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00008767 DeclarationName OpName =
8768 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00008769 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008770 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00008771
John McCallbc077cf2010-02-08 23:07:23 +00008772 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00008773 PDiag(diag::err_typecheck_incomplete_tag)
8774 << Base->getSourceRange()))
8775 return ExprError();
8776
John McCall27b18f82009-11-17 02:14:36 +00008777 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8778 LookupQualifiedName(R, BaseRecord->getDecl());
8779 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00008780
8781 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00008782 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00008783 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
8784 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00008785 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008786
8787 // Perform overload resolution.
8788 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008789 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008790 case OR_Success:
8791 // Overload resolution succeeded; we'll build the call below.
8792 break;
8793
8794 case OR_No_Viable_Function:
8795 if (CandidateSet.empty())
8796 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008797 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008798 else
8799 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008800 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008801 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008802 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008803
8804 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008805 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8806 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008807 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008808 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008809
8810 case OR_Deleted:
8811 Diag(OpLoc, diag::err_ovl_deleted_oper)
8812 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008813 << "->"
8814 << Best->Function->getMessageUnavailableAttr(
8815 !Best->Function->isDeleted())
8816 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008817 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008818 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008819 }
8820
Chandler Carruth30141632011-02-25 19:41:05 +00008821 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00008822 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008823 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00008824
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008825 // Convert the object parameter.
8826 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008827 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8828 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00008829 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00008830
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008831 // Build the operator call.
John McCall7decc9e2010-11-18 06:31:45 +00008832 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008833
John McCall7decc9e2010-11-18 06:31:45 +00008834 QualType ResultTy = Method->getResultType();
8835 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8836 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00008837 CXXOperatorCallExpr *TheCall =
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008838 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008839 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008840
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008841 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008842 Method))
8843 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008844 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008845}
8846
Douglas Gregorcd695e52008-11-10 20:40:00 +00008847/// FixOverloadedFunctionReference - E is an expression that refers to
8848/// a C++ overloaded function (possibly with some parentheses and
8849/// perhaps a '&' around it). We have resolved the overloaded function
8850/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008851/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00008852Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00008853 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00008854 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008855 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8856 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008857 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008858 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008859
Douglas Gregor51c538b2009-11-20 19:42:02 +00008860 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008861 }
8862
Douglas Gregor51c538b2009-11-20 19:42:02 +00008863 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008864 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8865 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008866 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008867 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00008868 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00008869 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00008870 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008871 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008872
8873 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +00008874 ICE->getCastKind(),
8875 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00008876 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008877 }
8878
Douglas Gregor51c538b2009-11-20 19:42:02 +00008879 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00008880 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008881 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008882 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8883 if (Method->isStatic()) {
8884 // Do nothing: static member functions aren't any different
8885 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008886 } else {
John McCalle66edc12009-11-24 19:00:30 +00008887 // Fix the sub expression, which really has to be an
8888 // UnresolvedLookupExpr holding an overloaded member function
8889 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008890 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8891 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008892 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008893 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008894
John McCalld14a8642009-11-21 08:51:07 +00008895 assert(isa<DeclRefExpr>(SubExpr)
8896 && "fixed to something other than a decl ref");
8897 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8898 && "fixed to a member ref with no nested name qualifier");
8899
8900 // We have taken the address of a pointer to member
8901 // function. Perform the computation here so that we get the
8902 // appropriate pointer to member type.
8903 QualType ClassType
8904 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8905 QualType MemPtrType
8906 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8907
John McCall7decc9e2010-11-18 06:31:45 +00008908 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8909 VK_RValue, OK_Ordinary,
8910 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008911 }
8912 }
John McCall16df1e52010-03-30 21:47:33 +00008913 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8914 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008915 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008916 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008917
John McCalle3027922010-08-25 11:45:40 +00008918 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008919 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00008920 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008921 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008922 }
John McCalld14a8642009-11-21 08:51:07 +00008923
8924 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00008925 // FIXME: avoid copy.
8926 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00008927 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00008928 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8929 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00008930 }
8931
John McCalld14a8642009-11-21 08:51:07 +00008932 return DeclRefExpr::Create(Context,
8933 ULE->getQualifier(),
8934 ULE->getQualifierRange(),
8935 Fn,
8936 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00008937 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008938 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008939 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00008940 }
8941
John McCall10eae182009-11-30 22:42:35 +00008942 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00008943 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00008944 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8945 if (MemExpr->hasExplicitTemplateArgs()) {
8946 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8947 TemplateArgs = &TemplateArgsBuffer;
8948 }
John McCall6b51f282009-11-23 01:53:49 +00008949
John McCall2d74de92009-12-01 22:10:20 +00008950 Expr *Base;
8951
John McCall7decc9e2010-11-18 06:31:45 +00008952 // If we're filling in a static method where we used to have an
8953 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00008954 if (MemExpr->isImplicitAccess()) {
8955 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8956 return DeclRefExpr::Create(Context,
8957 MemExpr->getQualifier(),
8958 MemExpr->getQualifierRange(),
8959 Fn,
8960 MemExpr->getMemberLoc(),
8961 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008962 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008963 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00008964 } else {
8965 SourceLocation Loc = MemExpr->getMemberLoc();
8966 if (MemExpr->getQualifier())
8967 Loc = MemExpr->getQualifierRange().getBegin();
8968 Base = new (Context) CXXThisExpr(Loc,
8969 MemExpr->getBaseType(),
8970 /*isImplicit=*/true);
8971 }
John McCall2d74de92009-12-01 22:10:20 +00008972 } else
John McCallc3007a22010-10-26 07:05:15 +00008973 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00008974
8975 return MemberExpr::Create(Context, Base,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008976 MemExpr->isArrow(),
8977 MemExpr->getQualifier(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008978 MemExpr->getQualifierRange(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008979 Fn,
John McCall16df1e52010-03-30 21:47:33 +00008980 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008981 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00008982 TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008983 Fn->getType(),
8984 cast<CXXMethodDecl>(Fn)->isStatic()
8985 ? VK_LValue : VK_RValue,
8986 OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008987 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008988
John McCallc3007a22010-10-26 07:05:15 +00008989 llvm_unreachable("Invalid reference to overloaded function");
8990 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008991}
8992
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008993ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +00008994 DeclAccessPair Found,
8995 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00008996 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008997}
8998
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008999} // end namespace clang