blob: 1e8f315c95c78a756be850cbf9d693fc35ba3fa8 [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}
343
344/// \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;
359
360 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;
364
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 }
375
376 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000377 Result.Data = Info.take();
378 break;
379
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000380 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000381 case Sema::TDK_FailedOverloadResolution:
382 break;
383 }
384
385 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;
397
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;
Douglas Gregor3626a5c2010-05-08 17:41:32 +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}
415
416TemplateParameter
417OverloadCandidate::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();
425
426 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000427 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000428 return TemplateParameter::getFromOpaqueValue(Data);
429
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;
433
434 // 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 }
439
440 return TemplateParameter();
441}
Douglas Gregord09efd42010-05-08 20:07:26 +0000442
443TemplateArgumentList *
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);
458
459 // 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:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000481 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
482
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 }
488
489 return 0;
490}
491
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 }
513
514 return 0;
515}
516
517void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000518 inherited::clear();
519 Functions.clear();
520}
521
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:
704 // - 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
708 // 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 }
713
John McCall1f82f242009-11-18 22:49:29 +0000714 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000715 }
John McCall1f82f242009-11-18 22:49:29 +0000716
717 // 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,
747 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);
777
778 // 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;
Douglas Gregor836a7e82010-08-11 02:15:33 +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;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000787
788 return ICS;
789 }
790
791 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,
868 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}
902
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000903/// \brief Determine whether the conversion from FromType to ToType is a valid
904/// conversion that strips "noreturn" off the nested function type.
905static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
906 QualType ToType, QualType &ResultTy) {
907 if (Context.hasSameUnqualifiedType(FromType, ToType))
908 return false;
909
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}
Douglas Gregor46188682010-05-18 22:42:18 +0000950
951/// \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.
956static bool IsVectorConversion(ASTContext &Context, QualType FromType,
957 QualType ToType, ImplicitConversionKind &ICK) {
958 // 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;
973
974 // 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}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +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();
John McCall5c32be02010-08-24 20:38:10 +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
John McCall5c32be02010-08-24 20:38:10 +00001034 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1035 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001036 // We were able to resolve the address of the overloaded function,
1037 // so we can convert to the type of that function.
1038 FromType = Fn->getType();
1039 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
1040 if (!Method->isStatic()) {
John McCall424cec92011-01-19 06:33:43 +00001041 const Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +00001042 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1043 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +00001044 }
1045 }
1046
1047 // If the "from" expression takes the address of the overloaded
1048 // function, update the type of the resulting expression accordingly.
1049 if (FromType->getAs<FunctionType>())
1050 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +00001051 if (UnOp->getOpcode() == UO_AddrOf)
John McCall5c32be02010-08-24 20:38:10 +00001052 FromType = S.Context.getPointerType(FromType);
Douglas Gregor980fb162010-04-29 18:24:40 +00001053
1054 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00001055 assert(S.Context.hasSameType(FromType,
1056 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001057 } else {
1058 return false;
1059 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001060 }
Mike Stump11289f42009-09-09 15:08:12 +00001061 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001062 // An lvalue (3.10) of a non-function, non-array type T can be
1063 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001064 bool argIsLValue = From->isLValue();
1065 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001066 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001067 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001068 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001069
1070 // If T is a non-class type, the type of the rvalue is the
1071 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001072 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1073 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001074 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001075 } else if (FromType->isArrayType()) {
1076 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001077 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001078
1079 // An lvalue or rvalue of type "array of N T" or "array of unknown
1080 // bound of T" can be converted to an rvalue of type "pointer to
1081 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001082 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001083
John McCall5c32be02010-08-24 20:38:10 +00001084 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001085 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001086 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001087
1088 // For the purpose of ranking in overload resolution
1089 // (13.3.3.1.1), this conversion is considered an
1090 // array-to-pointer conversion followed by a qualification
1091 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001092 SCS.Second = ICK_Identity;
1093 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001094 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001095 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001096 }
John McCall086a4642010-11-24 05:12:34 +00001097 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001098 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001099 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001100
1101 // An lvalue of function type T can be converted to an rvalue of
1102 // type "pointer to T." The result is a pointer to the
1103 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001104 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001105 } else {
1106 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001107 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001108 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001109 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001110
1111 // The second conversion can be an integral promotion, floating
1112 // point promotion, integral conversion, floating point conversion,
1113 // floating-integral conversion, pointer conversion,
1114 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001115 // For overloading in C, this can also be a "compatible-type"
1116 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001117 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001118 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001119 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001120 // The unqualified versions of the types are the same: there's no
1121 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001122 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001123 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001124 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001125 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001126 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001127 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001128 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001129 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001130 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001131 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001132 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001133 SCS.Second = ICK_Complex_Promotion;
1134 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001135 } else if (ToType->isBooleanType() &&
1136 (FromType->isArithmeticType() ||
1137 FromType->isAnyPointerType() ||
1138 FromType->isBlockPointerType() ||
1139 FromType->isMemberPointerType() ||
1140 FromType->isNullPtrType())) {
1141 // Boolean conversions (C++ 4.12).
1142 SCS.Second = ICK_Boolean_Conversion;
1143 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001144 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001145 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001146 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001147 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001148 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001149 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001150 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001151 SCS.Second = ICK_Complex_Conversion;
1152 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001153 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1154 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001155 // Complex-real conversions (C99 6.3.1.7)
1156 SCS.Second = ICK_Complex_Real;
1157 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001158 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001159 // Floating point conversions (C++ 4.8).
1160 SCS.Second = ICK_Floating_Conversion;
1161 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001162 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001163 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001164 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001165 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001166 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001167 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001168 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001169 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1170 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001171 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001172 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001173 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall5c32be02010-08-24 20:38:10 +00001174 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1175 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001176 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001177 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001178 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001179 SCS.Second = SecondICK;
1180 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001181 } else if (!S.getLangOptions().CPlusPlus &&
1182 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001183 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001184 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001185 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001186 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001187 // Treat a conversion that strips "noreturn" as an identity conversion.
1188 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001189 } else {
1190 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001191 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001192 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001193 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001194
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001195 QualType CanonFrom;
1196 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001197 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor58281352011-01-27 00:58:17 +00001198 if (S.IsQualificationConversion(FromType, ToType, CStyle)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001199 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001200 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001201 CanonFrom = S.Context.getCanonicalType(FromType);
1202 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001203 } else {
1204 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001205 SCS.Third = ICK_Identity;
1206
Mike Stump11289f42009-09-09 15:08:12 +00001207 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001208 // [...] Any difference in top-level cv-qualification is
1209 // subsumed by the initialization itself and does not constitute
1210 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001211 CanonFrom = S.Context.getCanonicalType(FromType);
1212 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001213 if (CanonFrom.getLocalUnqualifiedType()
1214 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001215 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1216 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001217 FromType = ToType;
1218 CanonFrom = CanonTo;
1219 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001220 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001221 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001222
1223 // If we have not converted the argument type to the parameter type,
1224 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001225 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001226 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001227
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001228 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001229}
1230
1231/// IsIntegralPromotion - Determines whether the conversion from the
1232/// expression From (whose potentially-adjusted type is FromType) to
1233/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1234/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001235bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001236 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001237 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001238 if (!To) {
1239 return false;
1240 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001241
1242 // An rvalue of type char, signed char, unsigned char, short int, or
1243 // unsigned short int can be converted to an rvalue of type int if
1244 // int can represent all the values of the source type; otherwise,
1245 // the source rvalue can be converted to an rvalue of type unsigned
1246 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001247 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1248 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001249 if (// We can promote any signed, promotable integer type to an int
1250 (FromType->isSignedIntegerType() ||
1251 // We can promote any unsigned integer type whose size is
1252 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001253 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001254 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001255 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001256 }
1257
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001258 return To->getKind() == BuiltinType::UInt;
1259 }
1260
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001261 // C++0x [conv.prom]p3:
1262 // A prvalue of an unscoped enumeration type whose underlying type is not
1263 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1264 // following types that can represent all the values of the enumeration
1265 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1266 // unsigned int, long int, unsigned long int, long long int, or unsigned
1267 // long long int. If none of the types in that list can represent all the
1268 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1269 // type can be converted to an rvalue a prvalue of the extended integer type
1270 // with lowest integer conversion rank (4.13) greater than the rank of long
1271 // long in which all the values of the enumeration can be represented. If
1272 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001273 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1274 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1275 // provided for a scoped enumeration.
1276 if (FromEnumType->getDecl()->isScoped())
1277 return false;
1278
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001279 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001280 if (ToType->isIntegerType() &&
1281 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001282 return Context.hasSameUnqualifiedType(ToType,
1283 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001284 }
John McCall56774992009-12-09 09:09:27 +00001285
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001286 // C++0x [conv.prom]p2:
1287 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1288 // to an rvalue a prvalue of the first of the following types that can
1289 // represent all the values of its underlying type: int, unsigned int,
1290 // long int, unsigned long int, long long int, or unsigned long long int.
1291 // If none of the types in that list can represent all the values of its
1292 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1293 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1294 // type.
1295 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1296 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001297 // Determine whether the type we're converting from is signed or
1298 // unsigned.
1299 bool FromIsSigned;
1300 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001301
1302 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1303 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001304
1305 // The types we'll try to promote to, in the appropriate
1306 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001307 QualType PromoteTypes[6] = {
1308 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001309 Context.LongTy, Context.UnsignedLongTy ,
1310 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001311 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001312 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001313 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1314 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001315 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001316 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1317 // We found the type that we can promote to. If this is the
1318 // type we wanted, we have a promotion. Otherwise, no
1319 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001320 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001321 }
1322 }
1323 }
1324
1325 // An rvalue for an integral bit-field (9.6) can be converted to an
1326 // rvalue of type int if int can represent all the values of the
1327 // bit-field; otherwise, it can be converted to unsigned int if
1328 // unsigned int can represent all the values of the bit-field. If
1329 // the bit-field is larger yet, no integral promotion applies to
1330 // it. If the bit-field has an enumerated type, it is treated as any
1331 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001332 // FIXME: We should delay checking of bit-fields until we actually perform the
1333 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001334 using llvm::APSInt;
1335 if (From)
1336 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001337 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001338 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001339 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1340 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1341 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001342
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001343 // Are we promoting to an int from a bitfield that fits in an int?
1344 if (BitWidth < ToSize ||
1345 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1346 return To->getKind() == BuiltinType::Int;
1347 }
Mike Stump11289f42009-09-09 15:08:12 +00001348
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001349 // Are we promoting to an unsigned int from an unsigned bitfield
1350 // that fits into an unsigned int?
1351 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1352 return To->getKind() == BuiltinType::UInt;
1353 }
Mike Stump11289f42009-09-09 15:08:12 +00001354
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001355 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001356 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001357 }
Mike Stump11289f42009-09-09 15:08:12 +00001358
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001359 // An rvalue of type bool can be converted to an rvalue of type int,
1360 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001361 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001362 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001363 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001364
1365 return false;
1366}
1367
1368/// IsFloatingPointPromotion - Determines whether the conversion from
1369/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1370/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001371bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001372 /// An rvalue of type float can be converted to an rvalue of type
1373 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001374 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1375 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001376 if (FromBuiltin->getKind() == BuiltinType::Float &&
1377 ToBuiltin->getKind() == BuiltinType::Double)
1378 return true;
1379
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001380 // C99 6.3.1.5p1:
1381 // When a float is promoted to double or long double, or a
1382 // double is promoted to long double [...].
1383 if (!getLangOptions().CPlusPlus &&
1384 (FromBuiltin->getKind() == BuiltinType::Float ||
1385 FromBuiltin->getKind() == BuiltinType::Double) &&
1386 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1387 return true;
1388 }
1389
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001390 return false;
1391}
1392
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001393/// \brief Determine if a conversion is a complex promotion.
1394///
1395/// A complex promotion is defined as a complex -> complex conversion
1396/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001397/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001398bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001399 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001400 if (!FromComplex)
1401 return false;
1402
John McCall9dd450b2009-09-21 23:43:11 +00001403 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001404 if (!ToComplex)
1405 return false;
1406
1407 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001408 ToComplex->getElementType()) ||
1409 IsIntegralPromotion(0, FromComplex->getElementType(),
1410 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001411}
1412
Douglas Gregor237f96c2008-11-26 23:31:11 +00001413/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1414/// the pointer type FromPtr to a pointer to type ToPointee, with the
1415/// same type qualifiers as FromPtr has on its pointee type. ToType,
1416/// if non-empty, will be a pointer to ToType that may or may not have
1417/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001418static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001419BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001420 QualType ToPointee, QualType ToType,
1421 ASTContext &Context) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001422 assert((FromPtr->getTypeClass() == Type::Pointer ||
1423 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1424 "Invalid similarly-qualified pointer type");
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001425
1426 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1427 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1428 return ToType.getUnqualifiedType();
1429
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001430 QualType CanonFromPointee
1431 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001432 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001433 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001434
1435 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001436 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001437 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001438 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001439 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001440
1441 // Build a pointer to ToPointee. It has the right qualifiers
1442 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001443 if (isa<ObjCObjectPointerType>(ToType))
1444 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001445 return Context.getPointerType(ToPointee);
1446 }
1447
1448 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001449 QualType QualifiedCanonToPointee
1450 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001451
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001452 if (isa<ObjCObjectPointerType>(ToType))
1453 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1454 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001455}
1456
Mike Stump11289f42009-09-09 15:08:12 +00001457static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001458 bool InOverloadResolution,
1459 ASTContext &Context) {
1460 // Handle value-dependent integral null pointer constants correctly.
1461 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1462 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001463 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001464 return !InOverloadResolution;
1465
Douglas Gregor56751b52009-09-25 04:25:58 +00001466 return Expr->isNullPointerConstant(Context,
1467 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1468 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001469}
Mike Stump11289f42009-09-09 15:08:12 +00001470
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001471/// IsPointerConversion - Determines whether the conversion of the
1472/// expression From, which has the (possibly adjusted) type FromType,
1473/// can be converted to the type ToType via a pointer conversion (C++
1474/// 4.10). If so, returns true and places the converted type (that
1475/// might differ from ToType in its cv-qualifiers at some level) into
1476/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001477///
Douglas Gregora29dc052008-11-27 01:19:21 +00001478/// This routine also supports conversions to and from block pointers
1479/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1480/// pointers to interfaces. FIXME: Once we've determined the
1481/// appropriate overloading rules for Objective-C, we may want to
1482/// split the Objective-C checks into a different routine; however,
1483/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001484/// conversions, so for now they live here. IncompatibleObjC will be
1485/// set if the conversion is an allowed Objective-C conversion that
1486/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001487bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001488 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001489 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001490 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001491 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001492 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1493 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001494 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001495
Mike Stump11289f42009-09-09 15:08:12 +00001496 // Conversion from a null pointer constant to any Objective-C pointer type.
1497 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001498 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001499 ConvertedType = ToType;
1500 return true;
1501 }
1502
Douglas Gregor231d1c62008-11-27 00:15:41 +00001503 // Blocks: Block pointers can be converted to void*.
1504 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001505 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001506 ConvertedType = ToType;
1507 return true;
1508 }
1509 // Blocks: A null pointer constant can be converted to a block
1510 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001511 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001512 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001513 ConvertedType = ToType;
1514 return true;
1515 }
1516
Sebastian Redl576fd422009-05-10 18:38:11 +00001517 // If the left-hand-side is nullptr_t, the right side can be a null
1518 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001519 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001520 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001521 ConvertedType = ToType;
1522 return true;
1523 }
1524
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001525 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001526 if (!ToTypePtr)
1527 return false;
1528
1529 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001530 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001531 ConvertedType = ToType;
1532 return true;
1533 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001534
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001535 // Beyond this point, both types need to be pointers
1536 // , including objective-c pointers.
1537 QualType ToPointeeType = ToTypePtr->getPointeeType();
1538 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001539 ConvertedType = BuildSimilarlyQualifiedPointerType(
1540 FromType->getAs<ObjCObjectPointerType>(),
1541 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001542 ToType, Context);
1543 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001544 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001545 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001546 if (!FromTypePtr)
1547 return false;
1548
1549 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001550
Douglas Gregorfb640862010-08-18 21:25:30 +00001551 // If the unqualified pointee types are the same, this can't be a
1552 // pointer conversion, so don't do all of the work below.
1553 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1554 return false;
1555
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001556 // An rvalue of type "pointer to cv T," where T is an object type,
1557 // can be converted to an rvalue of type "pointer to cv void" (C++
1558 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001559 if (FromPointeeType->isIncompleteOrObjectType() &&
1560 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001561 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001562 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001563 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001564 return true;
1565 }
1566
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001567 // When we're overloading in C, we allow a special kind of pointer
1568 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001569 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001570 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001571 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001572 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001573 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001574 return true;
1575 }
1576
Douglas Gregor5c407d92008-10-23 00:40:37 +00001577 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001578 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001579 // An rvalue of type "pointer to cv D," where D is a class type,
1580 // can be converted to an rvalue of type "pointer to cv B," where
1581 // B is a base class (clause 10) of D. If B is an inaccessible
1582 // (clause 11) or ambiguous (10.2) base class of D, a program that
1583 // necessitates this conversion is ill-formed. The result of the
1584 // conversion is a pointer to the base class sub-object of the
1585 // derived class object. The null pointer value is converted to
1586 // the null pointer value of the destination type.
1587 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001588 // Note that we do not check for ambiguity or inaccessibility
1589 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001590 if (getLangOptions().CPlusPlus &&
1591 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001592 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001593 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001594 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001595 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001596 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001597 ToType, Context);
1598 return true;
1599 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001600
Douglas Gregora119f102008-12-19 19:13:09 +00001601 return false;
1602}
1603
1604/// isObjCPointerConversion - Determines whether this is an
1605/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1606/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001607bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001608 QualType& ConvertedType,
1609 bool &IncompatibleObjC) {
1610 if (!getLangOptions().ObjC1)
1611 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001612
Steve Naroff7cae42b2009-07-10 23:34:53 +00001613 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001614 const ObjCObjectPointerType* ToObjCPtr =
1615 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001616 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001617 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001618
Steve Naroff7cae42b2009-07-10 23:34:53 +00001619 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001620 // If the pointee types are the same (ignoring qualifications),
1621 // then this is not a pointer conversion.
1622 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1623 FromObjCPtr->getPointeeType()))
1624 return false;
1625
Steve Naroff1329fa02009-07-15 18:40:39 +00001626 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001627 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001628 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001629 ConvertedType = ToType;
1630 return true;
1631 }
1632 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001633 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001634 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001635 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001636 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001637 ConvertedType = ToType;
1638 return true;
1639 }
1640 // Objective C++: We're able to convert from a pointer to an
1641 // interface to a pointer to a different interface.
1642 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001643 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1644 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1645 if (getLangOptions().CPlusPlus && LHS && RHS &&
1646 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1647 FromObjCPtr->getPointeeType()))
1648 return false;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001649 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1650 ToObjCPtr->getPointeeType(),
1651 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001652 return true;
1653 }
1654
1655 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1656 // Okay: this is some kind of implicit downcast of Objective-C
1657 // interfaces, which is permitted. However, we're going to
1658 // complain about it.
1659 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001660 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1661 ToObjCPtr->getPointeeType(),
1662 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001663 return true;
1664 }
Mike Stump11289f42009-09-09 15:08:12 +00001665 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001666 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001667 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001668 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001669 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001670 else if (const BlockPointerType *ToBlockPtr =
1671 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001672 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001673 // to a block pointer type.
1674 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1675 ConvertedType = ToType;
1676 return true;
1677 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001678 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001679 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001680 else if (FromType->getAs<BlockPointerType>() &&
1681 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1682 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001683 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001684 ConvertedType = ToType;
1685 return true;
1686 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001687 else
Douglas Gregora119f102008-12-19 19:13:09 +00001688 return false;
1689
Douglas Gregor033f56d2008-12-23 00:53:59 +00001690 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001691 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001692 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001693 else if (const BlockPointerType *FromBlockPtr =
1694 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001695 FromPointeeType = FromBlockPtr->getPointeeType();
1696 else
Douglas Gregora119f102008-12-19 19:13:09 +00001697 return false;
1698
Douglas Gregora119f102008-12-19 19:13:09 +00001699 // If we have pointers to pointers, recursively check whether this
1700 // is an Objective-C conversion.
1701 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1702 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1703 IncompatibleObjC)) {
1704 // We always complain about this conversion.
1705 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001706 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregora119f102008-12-19 19:13:09 +00001707 return true;
1708 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001709 // Allow conversion of pointee being objective-c pointer to another one;
1710 // as in I* to id.
1711 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1712 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1713 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1714 IncompatibleObjC)) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001715 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001716 return true;
1717 }
1718
Douglas Gregor033f56d2008-12-23 00:53:59 +00001719 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001720 // differences in the argument and result types are in Objective-C
1721 // pointer conversions. If so, we permit the conversion (but
1722 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001723 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001724 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001725 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001726 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001727 if (FromFunctionType && ToFunctionType) {
1728 // If the function types are exactly the same, this isn't an
1729 // Objective-C pointer conversion.
1730 if (Context.getCanonicalType(FromPointeeType)
1731 == Context.getCanonicalType(ToPointeeType))
1732 return false;
1733
1734 // Perform the quick checks that will tell us whether these
1735 // function types are obviously different.
1736 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1737 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1738 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1739 return false;
1740
1741 bool HasObjCConversion = false;
1742 if (Context.getCanonicalType(FromFunctionType->getResultType())
1743 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1744 // Okay, the types match exactly. Nothing to do.
1745 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1746 ToFunctionType->getResultType(),
1747 ConvertedType, IncompatibleObjC)) {
1748 // Okay, we have an Objective-C pointer conversion.
1749 HasObjCConversion = true;
1750 } else {
1751 // Function types are too different. Abort.
1752 return false;
1753 }
Mike Stump11289f42009-09-09 15:08:12 +00001754
Douglas Gregora119f102008-12-19 19:13:09 +00001755 // Check argument types.
1756 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1757 ArgIdx != NumArgs; ++ArgIdx) {
1758 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1759 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1760 if (Context.getCanonicalType(FromArgType)
1761 == Context.getCanonicalType(ToArgType)) {
1762 // Okay, the types match exactly. Nothing to do.
1763 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1764 ConvertedType, IncompatibleObjC)) {
1765 // Okay, we have an Objective-C pointer conversion.
1766 HasObjCConversion = true;
1767 } else {
1768 // Argument types are too different. Abort.
1769 return false;
1770 }
1771 }
1772
1773 if (HasObjCConversion) {
1774 // We had an Objective-C conversion. Allow this pointer
1775 // conversion, but complain about it.
1776 ConvertedType = ToType;
1777 IncompatibleObjC = true;
1778 return true;
1779 }
1780 }
1781
Sebastian Redl72b597d2009-01-25 19:43:20 +00001782 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001783}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001784
1785/// FunctionArgTypesAreEqual - This routine checks two function proto types
1786/// for equlity of their argument types. Caller has already checked that
1787/// they have same number of arguments. This routine assumes that Objective-C
1788/// pointer types which only differ in their protocol qualifiers are equal.
John McCall424cec92011-01-19 06:33:43 +00001789bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
1790 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001791 if (!getLangOptions().ObjC1)
1792 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1793 NewType->arg_type_begin());
1794
1795 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1796 N = NewType->arg_type_begin(),
1797 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1798 QualType ToType = (*O);
1799 QualType FromType = (*N);
1800 if (ToType != FromType) {
1801 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1802 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001803 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1804 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1805 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1806 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001807 continue;
1808 }
John McCall8b07ec22010-05-15 11:32:37 +00001809 else if (const ObjCObjectPointerType *PTTo =
1810 ToType->getAs<ObjCObjectPointerType>()) {
1811 if (const ObjCObjectPointerType *PTFr =
1812 FromType->getAs<ObjCObjectPointerType>())
1813 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1814 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001815 }
1816 return false;
1817 }
1818 }
1819 return true;
1820}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001821
Douglas Gregor39c16d42008-10-24 04:54:22 +00001822/// CheckPointerConversion - Check the pointer conversion from the
1823/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001824/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001825/// conversions for which IsPointerConversion has already returned
1826/// true. It returns true and produces a diagnostic if there was an
1827/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001828bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001829 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001830 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001831 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001832 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001833 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001834
John McCall8cb679e2010-11-15 09:13:47 +00001835 Kind = CK_BitCast;
1836
Douglas Gregor4038cf42010-06-08 17:35:15 +00001837 if (CXXBoolLiteralExpr* LitBool
1838 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001839 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregor4038cf42010-06-08 17:35:15 +00001840 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1841 << ToType;
1842
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001843 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1844 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001845 QualType FromPointeeType = FromPtrType->getPointeeType(),
1846 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001847
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001848 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1849 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001850 // We must have a derived-to-base conversion. Check an
1851 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001852 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1853 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001854 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001855 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001856 return true;
1857
1858 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00001859 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001860 }
1861 }
Mike Stump11289f42009-09-09 15:08:12 +00001862 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00001863 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001864 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001865 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001866 // Objective-C++ conversions are always okay.
1867 // FIXME: We should have a different class of conversions for the
1868 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001869 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001870 return false;
John McCall8cb679e2010-11-15 09:13:47 +00001871 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001872 }
John McCall8cb679e2010-11-15 09:13:47 +00001873
1874 // We shouldn't fall into this case unless it's valid for other
1875 // reasons.
1876 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1877 Kind = CK_NullToPointer;
1878
Douglas Gregor39c16d42008-10-24 04:54:22 +00001879 return false;
1880}
1881
Sebastian Redl72b597d2009-01-25 19:43:20 +00001882/// IsMemberPointerConversion - Determines whether the conversion of the
1883/// expression From, which has the (possibly adjusted) type FromType, can be
1884/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1885/// If so, returns true and places the converted type (that might differ from
1886/// ToType in its cv-qualifiers at some level) into ConvertedType.
1887bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001888 QualType ToType,
1889 bool InOverloadResolution,
1890 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001891 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001892 if (!ToTypePtr)
1893 return false;
1894
1895 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001896 if (From->isNullPointerConstant(Context,
1897 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1898 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001899 ConvertedType = ToType;
1900 return true;
1901 }
1902
1903 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001904 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001905 if (!FromTypePtr)
1906 return false;
1907
1908 // A pointer to member of B can be converted to a pointer to member of D,
1909 // where D is derived from B (C++ 4.11p2).
1910 QualType FromClass(FromTypePtr->getClass(), 0);
1911 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001912
Douglas Gregor7f6ae692010-12-21 21:40:41 +00001913 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
1914 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
1915 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001916 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1917 ToClass.getTypePtr());
1918 return true;
1919 }
1920
1921 return false;
1922}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001923
Sebastian Redl72b597d2009-01-25 19:43:20 +00001924/// CheckMemberPointerConversion - Check the member pointer conversion from the
1925/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001926/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001927/// for which IsMemberPointerConversion has already returned true. It returns
1928/// true and produces a diagnostic if there was an error, or returns false
1929/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001930bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001931 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001932 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001933 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001934 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001935 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001936 if (!FromPtrType) {
1937 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001938 assert(From->isNullPointerConstant(Context,
1939 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001940 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00001941 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001942 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001943 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001944
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001945 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001946 assert(ToPtrType && "No member pointer cast has a target type "
1947 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001948
Sebastian Redled8f2002009-01-28 18:33:18 +00001949 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1950 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001951
Sebastian Redled8f2002009-01-28 18:33:18 +00001952 // FIXME: What about dependent types?
1953 assert(FromClass->isRecordType() && "Pointer into non-class.");
1954 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001955
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001956 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001957 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001958 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1959 assert(DerivationOkay &&
1960 "Should not have been called if derivation isn't OK.");
1961 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001962
Sebastian Redled8f2002009-01-28 18:33:18 +00001963 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1964 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001965 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1966 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1967 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1968 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001969 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001970
Douglas Gregor89ee6822009-02-28 01:32:25 +00001971 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001972 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1973 << FromClass << ToClass << QualType(VBase, 0)
1974 << From->getSourceRange();
1975 return true;
1976 }
1977
John McCall5b0829a2010-02-10 09:31:12 +00001978 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001979 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1980 Paths.front(),
1981 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001982
Anders Carlssond7923c62009-08-22 23:33:40 +00001983 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001984 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001985 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001986 return false;
1987}
1988
Douglas Gregor9a657932008-10-21 23:43:52 +00001989/// IsQualificationConversion - Determines whether the conversion from
1990/// an rvalue of type FromType to ToType is a qualification conversion
1991/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001992bool
Douglas Gregor58281352011-01-27 00:58:17 +00001993Sema::IsQualificationConversion(QualType FromType, QualType ToType,
1994 bool CStyle) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001995 FromType = Context.getCanonicalType(FromType);
1996 ToType = Context.getCanonicalType(ToType);
1997
1998 // If FromType and ToType are the same type, this is not a
1999 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002000 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002001 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002002
Douglas Gregor9a657932008-10-21 23:43:52 +00002003 // (C++ 4.4p4):
2004 // A conversion can add cv-qualifiers at levels other than the first
2005 // in multi-level pointers, subject to the following rules: [...]
2006 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002007 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002008 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002009 // Within each iteration of the loop, we check the qualifiers to
2010 // determine if this still looks like a qualification
2011 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002012 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002013 // until there are no more pointers or pointers-to-members left to
2014 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002015 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002016
2017 // -- for every j > 0, if const is in cv 1,j then const is in cv
2018 // 2,j, and similarly for volatile.
Douglas Gregor58281352011-01-27 00:58:17 +00002019 if (!CStyle && !ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00002020 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002021
Douglas Gregor9a657932008-10-21 23:43:52 +00002022 // -- if the cv 1,j and cv 2,j are different, then const is in
2023 // every cv for 0 < k < j.
Douglas Gregor58281352011-01-27 00:58:17 +00002024 if (!CStyle && FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002025 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002026 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002027
Douglas Gregor9a657932008-10-21 23:43:52 +00002028 // Keep track of whether all prior cv-qualifiers in the "to" type
2029 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002030 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00002031 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002032 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002033
2034 // We are left with FromType and ToType being the pointee types
2035 // after unwrapping the original FromType and ToType the same number
2036 // of types. If we unwrapped any pointers, and if FromType and
2037 // ToType have the same unqualified type (since we checked
2038 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002039 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002040}
2041
Douglas Gregor576e98c2009-01-30 23:27:23 +00002042/// Determines whether there is a user-defined conversion sequence
2043/// (C++ [over.ics.user]) that converts expression From to the type
2044/// ToType. If such a conversion exists, User will contain the
2045/// user-defined conversion sequence that performs such a conversion
2046/// and this routine will return true. Otherwise, this routine returns
2047/// false and User is unspecified.
2048///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002049/// \param AllowExplicit true if the conversion should consider C++0x
2050/// "explicit" conversion functions as well as non-explicit conversion
2051/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002052static OverloadingResult
2053IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2054 UserDefinedConversionSequence& User,
2055 OverloadCandidateSet& CandidateSet,
2056 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002057 // Whether we will only visit constructors.
2058 bool ConstructorsOnly = false;
2059
2060 // If the type we are conversion to is a class type, enumerate its
2061 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002062 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002063 // C++ [over.match.ctor]p1:
2064 // When objects of class type are direct-initialized (8.5), or
2065 // copy-initialized from an expression of the same or a
2066 // derived class type (8.5), overload resolution selects the
2067 // constructor. [...] For copy-initialization, the candidate
2068 // functions are all the converting constructors (12.3.1) of
2069 // that class. The argument list is the expression-list within
2070 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002071 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002072 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002073 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002074 ConstructorsOnly = true;
2075
John McCall5c32be02010-08-24 20:38:10 +00002076 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002077 // We're not going to find any constructors.
2078 } else if (CXXRecordDecl *ToRecordDecl
2079 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002080 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002081 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002082 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002083 NamedDecl *D = *Con;
2084 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2085
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002086 // Find the constructor (which may be a template).
2087 CXXConstructorDecl *Constructor = 0;
2088 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002089 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002090 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002091 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002092 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2093 else
John McCalla0296f72010-03-19 07:35:19 +00002094 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002095
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002096 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002097 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002098 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002099 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2100 /*ExplicitArgs*/ 0,
2101 &From, 1, CandidateSet,
2102 /*SuppressUserConversions=*/
2103 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002104 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002105 // Allow one user-defined conversion when user specifies a
2106 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002107 S.AddOverloadCandidate(Constructor, FoundDecl,
2108 &From, 1, CandidateSet,
2109 /*SuppressUserConversions=*/
2110 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002111 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002112 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002113 }
2114 }
2115
Douglas Gregor5ab11652010-04-17 22:01:05 +00002116 // Enumerate conversion functions, if we're allowed to.
2117 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002118 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2119 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002120 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002121 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002122 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002123 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002124 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2125 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002126 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002127 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002128 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002129 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002130 DeclAccessPair FoundDecl = I.getPair();
2131 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002132 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2133 if (isa<UsingShadowDecl>(D))
2134 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2135
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002136 CXXConversionDecl *Conv;
2137 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002138 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2139 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002140 else
John McCallda4458e2010-03-31 01:36:47 +00002141 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002142
2143 if (AllowExplicit || !Conv->isExplicit()) {
2144 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002145 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2146 ActingContext, From, ToType,
2147 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002148 else
John McCall5c32be02010-08-24 20:38:10 +00002149 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2150 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002151 }
2152 }
2153 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002154 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002155
2156 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002157 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002158 case OR_Success:
2159 // Record the standard conversion we used and the conversion function.
2160 if (CXXConstructorDecl *Constructor
2161 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2162 // C++ [over.ics.user]p1:
2163 // If the user-defined conversion is specified by a
2164 // constructor (12.3.1), the initial standard conversion
2165 // sequence converts the source type to the type required by
2166 // the argument of the constructor.
2167 //
2168 QualType ThisType = Constructor->getThisType(S.Context);
2169 if (Best->Conversions[0].isEllipsis())
2170 User.EllipsisConversion = true;
2171 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002172 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002173 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002174 }
John McCall5c32be02010-08-24 20:38:10 +00002175 User.ConversionFunction = Constructor;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002176 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002177 User.After.setAsIdentityConversion();
2178 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2179 User.After.setAllToTypes(ToType);
2180 return OR_Success;
2181 } else if (CXXConversionDecl *Conversion
2182 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2183 // C++ [over.ics.user]p1:
2184 //
2185 // [...] If the user-defined conversion is specified by a
2186 // conversion function (12.3.2), the initial standard
2187 // conversion sequence converts the source type to the
2188 // implicit object parameter of the conversion function.
2189 User.Before = Best->Conversions[0].Standard;
2190 User.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002191 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002192 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002193
John McCall5c32be02010-08-24 20:38:10 +00002194 // C++ [over.ics.user]p2:
2195 // The second standard conversion sequence converts the
2196 // result of the user-defined conversion to the target type
2197 // for the sequence. Since an implicit conversion sequence
2198 // is an initialization, the special rules for
2199 // initialization by user-defined conversion apply when
2200 // selecting the best user-defined conversion for a
2201 // user-defined conversion sequence (see 13.3.3 and
2202 // 13.3.3.1).
2203 User.After = Best->FinalConversion;
2204 return OR_Success;
2205 } else {
2206 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002207 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002208 }
2209
John McCall5c32be02010-08-24 20:38:10 +00002210 case OR_No_Viable_Function:
2211 return OR_No_Viable_Function;
2212 case OR_Deleted:
2213 // No conversion here! We're done.
2214 return OR_Deleted;
2215
2216 case OR_Ambiguous:
2217 return OR_Ambiguous;
2218 }
2219
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002220 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002221}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002222
2223bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002224Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002225 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002226 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002227 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002228 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002229 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002230 if (OvResult == OR_Ambiguous)
2231 Diag(From->getSourceRange().getBegin(),
2232 diag::err_typecheck_ambiguous_condition)
2233 << From->getType() << ToType << From->getSourceRange();
2234 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2235 Diag(From->getSourceRange().getBegin(),
2236 diag::err_typecheck_nonviable_condition)
2237 << From->getType() << ToType << From->getSourceRange();
2238 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002239 return false;
John McCall5c32be02010-08-24 20:38:10 +00002240 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002241 return true;
2242}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002243
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002244/// CompareImplicitConversionSequences - Compare two implicit
2245/// conversion sequences to determine whether one is better than the
2246/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002247static ImplicitConversionSequence::CompareKind
2248CompareImplicitConversionSequences(Sema &S,
2249 const ImplicitConversionSequence& ICS1,
2250 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002251{
2252 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2253 // conversion sequences (as defined in 13.3.3.1)
2254 // -- a standard conversion sequence (13.3.3.1.1) is a better
2255 // conversion sequence than a user-defined conversion sequence or
2256 // an ellipsis conversion sequence, and
2257 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2258 // conversion sequence than an ellipsis conversion sequence
2259 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002260 //
John McCall0d1da222010-01-12 00:44:57 +00002261 // C++0x [over.best.ics]p10:
2262 // For the purpose of ranking implicit conversion sequences as
2263 // described in 13.3.3.2, the ambiguous conversion sequence is
2264 // treated as a user-defined sequence that is indistinguishable
2265 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002266 if (ICS1.getKindRank() < ICS2.getKindRank())
2267 return ImplicitConversionSequence::Better;
2268 else if (ICS2.getKindRank() < ICS1.getKindRank())
2269 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002270
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002271 // The following checks require both conversion sequences to be of
2272 // the same kind.
2273 if (ICS1.getKind() != ICS2.getKind())
2274 return ImplicitConversionSequence::Indistinguishable;
2275
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002276 // Two implicit conversion sequences of the same form are
2277 // indistinguishable conversion sequences unless one of the
2278 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002279 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002280 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002281 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002282 // User-defined conversion sequence U1 is a better conversion
2283 // sequence than another user-defined conversion sequence U2 if
2284 // they contain the same user-defined conversion function or
2285 // constructor and if the second standard conversion sequence of
2286 // U1 is better than the second standard conversion sequence of
2287 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002288 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002289 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002290 return CompareStandardConversionSequences(S,
2291 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002292 ICS2.UserDefined.After);
2293 }
2294
2295 return ImplicitConversionSequence::Indistinguishable;
2296}
2297
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002298static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2299 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2300 Qualifiers Quals;
2301 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2302 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2303 }
2304
2305 return Context.hasSameUnqualifiedType(T1, T2);
2306}
2307
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002308// Per 13.3.3.2p3, compare the given standard conversion sequences to
2309// determine if one is a proper subset of the other.
2310static ImplicitConversionSequence::CompareKind
2311compareStandardConversionSubsets(ASTContext &Context,
2312 const StandardConversionSequence& SCS1,
2313 const StandardConversionSequence& SCS2) {
2314 ImplicitConversionSequence::CompareKind Result
2315 = ImplicitConversionSequence::Indistinguishable;
2316
Douglas Gregore87561a2010-05-23 22:10:15 +00002317 // the identity conversion sequence is considered to be a subsequence of
2318 // any non-identity conversion sequence
2319 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2320 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2321 return ImplicitConversionSequence::Better;
2322 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2323 return ImplicitConversionSequence::Worse;
2324 }
2325
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002326 if (SCS1.Second != SCS2.Second) {
2327 if (SCS1.Second == ICK_Identity)
2328 Result = ImplicitConversionSequence::Better;
2329 else if (SCS2.Second == ICK_Identity)
2330 Result = ImplicitConversionSequence::Worse;
2331 else
2332 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002333 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002334 return ImplicitConversionSequence::Indistinguishable;
2335
2336 if (SCS1.Third == SCS2.Third) {
2337 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2338 : ImplicitConversionSequence::Indistinguishable;
2339 }
2340
2341 if (SCS1.Third == ICK_Identity)
2342 return Result == ImplicitConversionSequence::Worse
2343 ? ImplicitConversionSequence::Indistinguishable
2344 : ImplicitConversionSequence::Better;
2345
2346 if (SCS2.Third == ICK_Identity)
2347 return Result == ImplicitConversionSequence::Better
2348 ? ImplicitConversionSequence::Indistinguishable
2349 : ImplicitConversionSequence::Worse;
2350
2351 return ImplicitConversionSequence::Indistinguishable;
2352}
2353
Douglas Gregore696ebb2011-01-26 14:52:12 +00002354/// \brief Determine whether one of the given reference bindings is better
2355/// than the other based on what kind of bindings they are.
2356static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2357 const StandardConversionSequence &SCS2) {
2358 // C++0x [over.ics.rank]p3b4:
2359 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2360 // implicit object parameter of a non-static member function declared
2361 // without a ref-qualifier, and *either* S1 binds an rvalue reference
2362 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
2363 // lvalue reference to a function lvalue and S2 binds an rvalue
2364 // reference*.
2365 //
2366 // FIXME: Rvalue references. We're going rogue with the above edits,
2367 // because the semantics in the current C++0x working paper (N3225 at the
2368 // time of this writing) break the standard definition of std::forward
2369 // and std::reference_wrapper when dealing with references to functions.
2370 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002371 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2372 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2373 return false;
2374
Douglas Gregore696ebb2011-01-26 14:52:12 +00002375 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2376 SCS2.IsLvalueReference) ||
2377 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2378 !SCS2.IsLvalueReference);
2379}
2380
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002381/// CompareStandardConversionSequences - Compare two standard
2382/// conversion sequences to determine whether one is better than the
2383/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002384static ImplicitConversionSequence::CompareKind
2385CompareStandardConversionSequences(Sema &S,
2386 const StandardConversionSequence& SCS1,
2387 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002388{
2389 // Standard conversion sequence S1 is a better conversion sequence
2390 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2391
2392 // -- S1 is a proper subsequence of S2 (comparing the conversion
2393 // sequences in the canonical form defined by 13.3.3.1.1,
2394 // excluding any Lvalue Transformation; the identity conversion
2395 // sequence is considered to be a subsequence of any
2396 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002397 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002398 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002399 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002400
2401 // -- the rank of S1 is better than the rank of S2 (by the rules
2402 // defined below), or, if not that,
2403 ImplicitConversionRank Rank1 = SCS1.getRank();
2404 ImplicitConversionRank Rank2 = SCS2.getRank();
2405 if (Rank1 < Rank2)
2406 return ImplicitConversionSequence::Better;
2407 else if (Rank2 < Rank1)
2408 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002409
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002410 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2411 // are indistinguishable unless one of the following rules
2412 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002413
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002414 // A conversion that is not a conversion of a pointer, or
2415 // pointer to member, to bool is better than another conversion
2416 // that is such a conversion.
2417 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2418 return SCS2.isPointerConversionToBool()
2419 ? ImplicitConversionSequence::Better
2420 : ImplicitConversionSequence::Worse;
2421
Douglas Gregor5c407d92008-10-23 00:40:37 +00002422 // C++ [over.ics.rank]p4b2:
2423 //
2424 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002425 // conversion of B* to A* is better than conversion of B* to
2426 // void*, and conversion of A* to void* is better than conversion
2427 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002428 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002429 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002430 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002431 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002432 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2433 // Exactly one of the conversion sequences is a conversion to
2434 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002435 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2436 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002437 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2438 // Neither conversion sequence converts to a void pointer; compare
2439 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002440 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002441 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002442 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002443 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2444 // Both conversion sequences are conversions to void
2445 // pointers. Compare the source types to determine if there's an
2446 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002447 QualType FromType1 = SCS1.getFromType();
2448 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002449
2450 // Adjust the types we're converting from via the array-to-pointer
2451 // conversion, if we need to.
2452 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002453 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002454 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002455 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002456
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002457 QualType FromPointee1
2458 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2459 QualType FromPointee2
2460 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002461
John McCall5c32be02010-08-24 20:38:10 +00002462 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002463 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002464 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002465 return ImplicitConversionSequence::Worse;
2466
2467 // Objective-C++: If one interface is more specific than the
2468 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002469 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2470 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002471 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002472 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002473 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002474 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002475 return ImplicitConversionSequence::Worse;
2476 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002477 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002478
2479 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2480 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002481 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002482 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002483 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002484
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002485 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002486 // Check for a better reference binding based on the kind of bindings.
2487 if (isBetterReferenceBindingKind(SCS1, SCS2))
2488 return ImplicitConversionSequence::Better;
2489 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2490 return ImplicitConversionSequence::Worse;
2491
Sebastian Redlb28b4072009-03-22 23:49:27 +00002492 // C++ [over.ics.rank]p3b4:
2493 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2494 // which the references refer are the same type except for
2495 // top-level cv-qualifiers, and the type to which the reference
2496 // initialized by S2 refers is more cv-qualified than the type
2497 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002498 QualType T1 = SCS1.getToType(2);
2499 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002500 T1 = S.Context.getCanonicalType(T1);
2501 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002502 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002503 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2504 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002505 if (UnqualT1 == UnqualT2) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00002506 // If the type is an array type, promote the element qualifiers to the
2507 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002508 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002509 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002510 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002511 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002512 if (T2.isMoreQualifiedThan(T1))
2513 return ImplicitConversionSequence::Better;
2514 else if (T1.isMoreQualifiedThan(T2))
2515 return ImplicitConversionSequence::Worse;
2516 }
2517 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002518
2519 return ImplicitConversionSequence::Indistinguishable;
2520}
2521
2522/// CompareQualificationConversions - Compares two standard conversion
2523/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002524/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2525ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002526CompareQualificationConversions(Sema &S,
2527 const StandardConversionSequence& SCS1,
2528 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002529 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002530 // -- S1 and S2 differ only in their qualification conversion and
2531 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2532 // cv-qualification signature of type T1 is a proper subset of
2533 // the cv-qualification signature of type T2, and S1 is not the
2534 // deprecated string literal array-to-pointer conversion (4.2).
2535 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2536 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2537 return ImplicitConversionSequence::Indistinguishable;
2538
2539 // FIXME: the example in the standard doesn't use a qualification
2540 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002541 QualType T1 = SCS1.getToType(2);
2542 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002543 T1 = S.Context.getCanonicalType(T1);
2544 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002545 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002546 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2547 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002548
2549 // If the types are the same, we won't learn anything by unwrapped
2550 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002551 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002552 return ImplicitConversionSequence::Indistinguishable;
2553
Chandler Carruth607f38e2009-12-29 07:16:59 +00002554 // If the type is an array type, promote the element qualifiers to the type
2555 // for comparison.
2556 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002557 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002558 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002559 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002560
Mike Stump11289f42009-09-09 15:08:12 +00002561 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002562 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002563 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002564 // Within each iteration of the loop, we check the qualifiers to
2565 // determine if this still looks like a qualification
2566 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002567 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002568 // until there are no more pointers or pointers-to-members left
2569 // to unwrap. This essentially mimics what
2570 // IsQualificationConversion does, but here we're checking for a
2571 // strict subset of qualifiers.
2572 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2573 // The qualifiers are the same, so this doesn't tell us anything
2574 // about how the sequences rank.
2575 ;
2576 else if (T2.isMoreQualifiedThan(T1)) {
2577 // T1 has fewer qualifiers, so it could be the better sequence.
2578 if (Result == ImplicitConversionSequence::Worse)
2579 // Neither has qualifiers that are a subset of the other's
2580 // qualifiers.
2581 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002582
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002583 Result = ImplicitConversionSequence::Better;
2584 } else if (T1.isMoreQualifiedThan(T2)) {
2585 // T2 has fewer qualifiers, so it could be the better sequence.
2586 if (Result == ImplicitConversionSequence::Better)
2587 // Neither has qualifiers that are a subset of the other's
2588 // qualifiers.
2589 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002590
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002591 Result = ImplicitConversionSequence::Worse;
2592 } else {
2593 // Qualifiers are disjoint.
2594 return ImplicitConversionSequence::Indistinguishable;
2595 }
2596
2597 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002598 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002599 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002600 }
2601
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002602 // Check that the winning standard conversion sequence isn't using
2603 // the deprecated string literal array to pointer conversion.
2604 switch (Result) {
2605 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002606 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002607 Result = ImplicitConversionSequence::Indistinguishable;
2608 break;
2609
2610 case ImplicitConversionSequence::Indistinguishable:
2611 break;
2612
2613 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002614 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002615 Result = ImplicitConversionSequence::Indistinguishable;
2616 break;
2617 }
2618
2619 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002620}
2621
Douglas Gregor5c407d92008-10-23 00:40:37 +00002622/// CompareDerivedToBaseConversions - Compares two standard conversion
2623/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002624/// various kinds of derived-to-base conversions (C++
2625/// [over.ics.rank]p4b3). As part of these checks, we also look at
2626/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002627ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002628CompareDerivedToBaseConversions(Sema &S,
2629 const StandardConversionSequence& SCS1,
2630 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002631 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002632 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002633 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002634 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002635
2636 // Adjust the types we're converting from via the array-to-pointer
2637 // conversion, if we need to.
2638 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002639 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002640 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002641 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002642
2643 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002644 FromType1 = S.Context.getCanonicalType(FromType1);
2645 ToType1 = S.Context.getCanonicalType(ToType1);
2646 FromType2 = S.Context.getCanonicalType(FromType2);
2647 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002648
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002649 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002650 //
2651 // If class B is derived directly or indirectly from class A and
2652 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002653 //
2654 // For Objective-C, we let A, B, and C also be Objective-C
2655 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002656
2657 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002658 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002659 SCS2.Second == ICK_Pointer_Conversion &&
2660 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2661 FromType1->isPointerType() && FromType2->isPointerType() &&
2662 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002663 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002664 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002665 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002666 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002667 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002668 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002669 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002670 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002671
John McCall8b07ec22010-05-15 11:32:37 +00002672 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2673 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2674 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2675 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002676
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002677 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002678 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002679 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002680 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002681 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002682 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002683
2684 if (ToIface1 && ToIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002685 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002686 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002687 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002688 return ImplicitConversionSequence::Worse;
2689 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002690 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002691
2692 // -- conversion of B* to A* is better than conversion of C* to A*,
2693 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002694 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002695 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002696 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002697 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002698
Douglas Gregor237f96c2008-11-26 23:31:11 +00002699 if (FromIface1 && FromIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002700 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002701 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002702 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002703 return ImplicitConversionSequence::Worse;
2704 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002705 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002706 }
2707
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002708 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002709 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2710 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2711 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2712 const MemberPointerType * FromMemPointer1 =
2713 FromType1->getAs<MemberPointerType>();
2714 const MemberPointerType * ToMemPointer1 =
2715 ToType1->getAs<MemberPointerType>();
2716 const MemberPointerType * FromMemPointer2 =
2717 FromType2->getAs<MemberPointerType>();
2718 const MemberPointerType * ToMemPointer2 =
2719 ToType2->getAs<MemberPointerType>();
2720 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2721 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2722 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2723 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2724 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2725 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2726 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2727 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002728 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002729 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002730 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002731 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002732 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002733 return ImplicitConversionSequence::Better;
2734 }
2735 // conversion of B::* to C::* is better than conversion of A::* to C::*
2736 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002737 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002738 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002739 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002740 return ImplicitConversionSequence::Worse;
2741 }
2742 }
2743
Douglas Gregor5ab11652010-04-17 22:01:05 +00002744 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002745 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002746 // -- binding of an expression of type C to a reference of type
2747 // B& is better than binding an expression of type C to a
2748 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002749 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2750 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2751 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002752 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002753 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002754 return ImplicitConversionSequence::Worse;
2755 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002756
Douglas Gregor2fe98832008-11-03 19:09:14 +00002757 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002758 // -- binding of an expression of type B to a reference of type
2759 // A& is better than binding an expression of type C to a
2760 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002761 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2762 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2763 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002764 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002765 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002766 return ImplicitConversionSequence::Worse;
2767 }
2768 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002769
Douglas Gregor5c407d92008-10-23 00:40:37 +00002770 return ImplicitConversionSequence::Indistinguishable;
2771}
2772
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002773/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2774/// determine whether they are reference-related,
2775/// reference-compatible, reference-compatible with added
2776/// qualification, or incompatible, for use in C++ initialization by
2777/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2778/// type, and the first type (T1) is the pointee type of the reference
2779/// type being initialized.
2780Sema::ReferenceCompareResult
2781Sema::CompareReferenceRelationship(SourceLocation Loc,
2782 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002783 bool &DerivedToBase,
2784 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002785 assert(!OrigT1->isReferenceType() &&
2786 "T1 must be the pointee type of the reference type");
2787 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2788
2789 QualType T1 = Context.getCanonicalType(OrigT1);
2790 QualType T2 = Context.getCanonicalType(OrigT2);
2791 Qualifiers T1Quals, T2Quals;
2792 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2793 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2794
2795 // C++ [dcl.init.ref]p4:
2796 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2797 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2798 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002799 DerivedToBase = false;
2800 ObjCConversion = false;
2801 if (UnqualT1 == UnqualT2) {
2802 // Nothing to do.
2803 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002804 IsDerivedFrom(UnqualT2, UnqualT1))
2805 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002806 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2807 UnqualT2->isObjCObjectOrInterfaceType() &&
2808 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2809 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002810 else
2811 return Ref_Incompatible;
2812
2813 // At this point, we know that T1 and T2 are reference-related (at
2814 // least).
2815
2816 // If the type is an array type, promote the element qualifiers to the type
2817 // for comparison.
2818 if (isa<ArrayType>(T1) && T1Quals)
2819 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2820 if (isa<ArrayType>(T2) && T2Quals)
2821 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2822
2823 // C++ [dcl.init.ref]p4:
2824 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2825 // reference-related to T2 and cv1 is the same cv-qualification
2826 // as, or greater cv-qualification than, cv2. For purposes of
2827 // overload resolution, cases for which cv1 is greater
2828 // cv-qualification than cv2 are identified as
2829 // reference-compatible with added qualification (see 13.3.3.2).
2830 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2831 return Ref_Compatible;
2832 else if (T1.isMoreQualifiedThan(T2))
2833 return Ref_Compatible_With_Added_Qualification;
2834 else
2835 return Ref_Related;
2836}
2837
Douglas Gregor836a7e82010-08-11 02:15:33 +00002838/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002839/// with DeclType. Return true if something definite is found.
2840static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002841FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2842 QualType DeclType, SourceLocation DeclLoc,
2843 Expr *Init, QualType T2, bool AllowRvalues,
2844 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002845 assert(T2->isRecordType() && "Can only find conversions of record types.");
2846 CXXRecordDecl *T2RecordDecl
2847 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2848
2849 OverloadCandidateSet CandidateSet(DeclLoc);
2850 const UnresolvedSetImpl *Conversions
2851 = T2RecordDecl->getVisibleConversionFunctions();
2852 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2853 E = Conversions->end(); I != E; ++I) {
2854 NamedDecl *D = *I;
2855 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2856 if (isa<UsingShadowDecl>(D))
2857 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2858
2859 FunctionTemplateDecl *ConvTemplate
2860 = dyn_cast<FunctionTemplateDecl>(D);
2861 CXXConversionDecl *Conv;
2862 if (ConvTemplate)
2863 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2864 else
2865 Conv = cast<CXXConversionDecl>(D);
2866
Douglas Gregor836a7e82010-08-11 02:15:33 +00002867 // If this is an explicit conversion, and we're not allowed to consider
2868 // explicit conversions, skip it.
2869 if (!AllowExplicit && Conv->isExplicit())
2870 continue;
2871
2872 if (AllowRvalues) {
2873 bool DerivedToBase = false;
2874 bool ObjCConversion = false;
2875 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00002876 S.CompareReferenceRelationship(
2877 DeclLoc,
2878 Conv->getConversionType().getNonReferenceType()
2879 .getUnqualifiedType(),
2880 DeclType.getNonReferenceType().getUnqualifiedType(),
2881 DerivedToBase, ObjCConversion) ==
2882 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00002883 continue;
2884 } else {
2885 // If the conversion function doesn't return a reference type,
2886 // it can't be considered for this conversion. An rvalue reference
2887 // is only acceptable if its referencee is a function type.
2888
2889 const ReferenceType *RefType =
2890 Conv->getConversionType()->getAs<ReferenceType>();
2891 if (!RefType ||
2892 (!RefType->isLValueReferenceType() &&
2893 !RefType->getPointeeType()->isFunctionType()))
2894 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002895 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002896
2897 if (ConvTemplate)
2898 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00002899 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00002900 else
2901 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00002902 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002903 }
2904
2905 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002906 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002907 case OR_Success:
2908 // C++ [over.ics.ref]p1:
2909 //
2910 // [...] If the parameter binds directly to the result of
2911 // applying a conversion function to the argument
2912 // expression, the implicit conversion sequence is a
2913 // user-defined conversion sequence (13.3.3.1.2), with the
2914 // second standard conversion sequence either an identity
2915 // conversion or, if the conversion function returns an
2916 // entity of a type that is a derived class of the parameter
2917 // type, a derived-to-base Conversion.
2918 if (!Best->FinalConversion.DirectBinding)
2919 return false;
2920
2921 ICS.setUserDefined();
2922 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2923 ICS.UserDefined.After = Best->FinalConversion;
2924 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002925 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redld92badf2010-06-30 18:13:39 +00002926 ICS.UserDefined.EllipsisConversion = false;
2927 assert(ICS.UserDefined.After.ReferenceBinding &&
2928 ICS.UserDefined.After.DirectBinding &&
2929 "Expected a direct reference binding!");
2930 return true;
2931
2932 case OR_Ambiguous:
2933 ICS.setAmbiguous();
2934 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2935 Cand != CandidateSet.end(); ++Cand)
2936 if (Cand->Viable)
2937 ICS.Ambiguous.addConversion(Cand->Function);
2938 return true;
2939
2940 case OR_No_Viable_Function:
2941 case OR_Deleted:
2942 // There was no suitable conversion, or we found a deleted
2943 // conversion; continue with other checks.
2944 return false;
2945 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002946
2947 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002948}
2949
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002950/// \brief Compute an implicit conversion sequence for reference
2951/// initialization.
2952static ImplicitConversionSequence
2953TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2954 SourceLocation DeclLoc,
2955 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002956 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002957 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2958
2959 // Most paths end in a failed conversion.
2960 ImplicitConversionSequence ICS;
2961 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2962
2963 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2964 QualType T2 = Init->getType();
2965
2966 // If the initializer is the address of an overloaded function, try
2967 // to resolve the overloaded function. If all goes well, T2 is the
2968 // type of the resulting function.
2969 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2970 DeclAccessPair Found;
2971 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2972 false, Found))
2973 T2 = Fn->getType();
2974 }
2975
2976 // Compute some basic properties of the types and the initializer.
2977 bool isRValRef = DeclType->isRValueReferenceType();
2978 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002979 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002980 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002981 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002982 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2983 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002984
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002985
Sebastian Redld92badf2010-06-30 18:13:39 +00002986 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002987 // A reference to type "cv1 T1" is initialized by an expression
2988 // of type "cv2 T2" as follows:
2989
Sebastian Redld92badf2010-06-30 18:13:39 +00002990 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00002991 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002992 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2993 // reference-compatible with "cv2 T2," or
2994 //
2995 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2996 if (InitCategory.isLValue() &&
2997 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002998 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002999 // When a parameter of reference type binds directly (8.5.3)
3000 // to an argument expression, the implicit conversion sequence
3001 // is the identity conversion, unless the argument expression
3002 // has a type that is a derived class of the parameter type,
3003 // in which case the implicit conversion sequence is a
3004 // derived-to-base Conversion (13.3.3.1).
3005 ICS.setStandard();
3006 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003007 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3008 : ObjCConversion? ICK_Compatible_Conversion
3009 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003010 ICS.Standard.Third = ICK_Identity;
3011 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3012 ICS.Standard.setToType(0, T2);
3013 ICS.Standard.setToType(1, T1);
3014 ICS.Standard.setToType(2, T1);
3015 ICS.Standard.ReferenceBinding = true;
3016 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003017 ICS.Standard.IsLvalueReference = !isRValRef;
3018 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3019 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003020 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003021 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003022
Sebastian Redld92badf2010-06-30 18:13:39 +00003023 // Nothing more to do: the inaccessibility/ambiguity check for
3024 // derived-to-base conversions is suppressed when we're
3025 // computing the implicit conversion sequence (C++
3026 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003027 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003028 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003029
Sebastian Redld92badf2010-06-30 18:13:39 +00003030 // -- has a class type (i.e., T2 is a class type), where T1 is
3031 // not reference-related to T2, and can be implicitly
3032 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3033 // is reference-compatible with "cv3 T3" 92) (this
3034 // conversion is selected by enumerating the applicable
3035 // conversion functions (13.3.1.6) and choosing the best
3036 // one through overload resolution (13.3)),
3037 if (!SuppressUserConversions && T2->isRecordType() &&
3038 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3039 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003040 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3041 Init, T2, /*AllowRvalues=*/false,
3042 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003043 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003044 }
3045 }
3046
Sebastian Redld92badf2010-06-30 18:13:39 +00003047 // -- Otherwise, the reference shall be an lvalue reference to a
3048 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003049 // shall be an rvalue reference.
Douglas Gregor870f3742010-04-18 09:22:00 +00003050 //
3051 // We actually handle one oddity of C++ [over.ics.ref] at this
3052 // point, which is that, due to p2 (which short-circuits reference
3053 // binding by only attempting a simple conversion for non-direct
3054 // bindings) and p3's strange wording, we allow a const volatile
3055 // reference to bind to an rvalue. Hence the check for the presence
3056 // of "const" rather than checking for "const" being the only
3057 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003058 // This is also the point where rvalue references and lvalue inits no longer
3059 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003060 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003061 return ICS;
3062
Douglas Gregorf143cd52011-01-24 16:14:37 +00003063 // -- If the initializer expression
3064 //
3065 // -- is an xvalue, class prvalue, array prvalue or function
3066 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3067 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3068 (InitCategory.isXValue() ||
3069 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3070 (InitCategory.isLValue() && T2->isFunctionType()))) {
3071 ICS.setStandard();
3072 ICS.Standard.First = ICK_Identity;
3073 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3074 : ObjCConversion? ICK_Compatible_Conversion
3075 : ICK_Identity;
3076 ICS.Standard.Third = ICK_Identity;
3077 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3078 ICS.Standard.setToType(0, T2);
3079 ICS.Standard.setToType(1, T1);
3080 ICS.Standard.setToType(2, T1);
3081 ICS.Standard.ReferenceBinding = true;
3082 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3083 // binding unless we're binding to a class prvalue.
3084 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3085 // allow the use of rvalue references in C++98/03 for the benefit of
3086 // standard library implementors; therefore, we need the xvalue check here.
3087 ICS.Standard.DirectBinding =
3088 S.getLangOptions().CPlusPlus0x ||
3089 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003090 ICS.Standard.IsLvalueReference = !isRValRef;
3091 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3092 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003093 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003094 ICS.Standard.CopyConstructor = 0;
3095 return ICS;
3096 }
3097
3098 // -- has a class type (i.e., T2 is a class type), where T1 is not
3099 // reference-related to T2, and can be implicitly converted to
3100 // an xvalue, class prvalue, or function lvalue of type
3101 // "cv3 T3", where "cv1 T1" is reference-compatible with
3102 // "cv3 T3",
3103 //
3104 // then the reference is bound to the value of the initializer
3105 // expression in the first case and to the result of the conversion
3106 // in the second case (or, in either case, to an appropriate base
3107 // class subobject).
3108 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3109 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
3110 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3111 Init, T2, /*AllowRvalues=*/true,
3112 AllowExplicit)) {
3113 // In the second case, if the reference is an rvalue reference
3114 // and the second standard conversion sequence of the
3115 // user-defined conversion sequence includes an lvalue-to-rvalue
3116 // conversion, the program is ill-formed.
3117 if (ICS.isUserDefined() && isRValRef &&
3118 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3119 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3120
Douglas Gregor95273c32011-01-21 16:36:05 +00003121 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003122 }
Douglas Gregor95273c32011-01-21 16:36:05 +00003123
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003124 // -- Otherwise, a temporary of type "cv1 T1" is created and
3125 // initialized from the initializer expression using the
3126 // rules for a non-reference copy initialization (8.5). The
3127 // reference is then bound to the temporary. If T1 is
3128 // reference-related to T2, cv1 must be the same
3129 // cv-qualification as, or greater cv-qualification than,
3130 // cv2; otherwise, the program is ill-formed.
3131 if (RefRelationship == Sema::Ref_Related) {
3132 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3133 // we would be reference-compatible or reference-compatible with
3134 // added qualification. But that wasn't the case, so the reference
3135 // initialization fails.
3136 return ICS;
3137 }
3138
3139 // If at least one of the types is a class type, the types are not
3140 // related, and we aren't allowed any user conversions, the
3141 // reference binding fails. This case is important for breaking
3142 // recursion, since TryImplicitConversion below will attempt to
3143 // create a temporary through the use of a copy constructor.
3144 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3145 (T1->isRecordType() || T2->isRecordType()))
3146 return ICS;
3147
Douglas Gregorcba72b12011-01-21 05:18:22 +00003148 // If T1 is reference-related to T2 and the reference is an rvalue
3149 // reference, the initializer expression shall not be an lvalue.
3150 if (RefRelationship >= Sema::Ref_Related &&
3151 isRValRef && Init->Classify(S.Context).isLValue())
3152 return ICS;
3153
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003154 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003155 // When a parameter of reference type is not bound directly to
3156 // an argument expression, the conversion sequence is the one
3157 // required to convert the argument expression to the
3158 // underlying type of the reference according to
3159 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3160 // to copy-initializing a temporary of the underlying type with
3161 // the argument expression. Any difference in top-level
3162 // cv-qualification is subsumed by the initialization itself
3163 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003164 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3165 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003166 /*InOverloadResolution=*/false,
3167 /*CStyle=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003168
3169 // Of course, that's still a reference binding.
3170 if (ICS.isStandard()) {
3171 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003172 ICS.Standard.IsLvalueReference = !isRValRef;
3173 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3174 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003175 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003176 } else if (ICS.isUserDefined()) {
3177 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003178 ICS.Standard.IsLvalueReference = !isRValRef;
3179 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3180 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003181 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003182 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003183
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003184 return ICS;
3185}
3186
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003187/// TryCopyInitialization - Try to copy-initialize a value of type
3188/// ToType from the expression From. Return the implicit conversion
3189/// sequence required to pass this argument, which may be a bad
3190/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003191/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003192/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003193static ImplicitConversionSequence
3194TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00003195 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003196 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003197 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003198 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003199 /*FIXME:*/From->getLocStart(),
3200 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003201 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003202
John McCall5c32be02010-08-24 20:38:10 +00003203 return TryImplicitConversion(S, From, ToType,
3204 SuppressUserConversions,
3205 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003206 InOverloadResolution,
3207 /*CStyle=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003208}
3209
Douglas Gregor436424c2008-11-18 23:14:02 +00003210/// TryObjectArgumentInitialization - Try to initialize the object
3211/// parameter of the given member function (@c Method) from the
3212/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003213static ImplicitConversionSequence
3214TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003215 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003216 CXXMethodDecl *Method,
3217 CXXRecordDecl *ActingContext) {
3218 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003219 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3220 // const volatile object.
3221 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3222 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003223 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003224
3225 // Set up the conversion sequence as a "bad" conversion, to allow us
3226 // to exit early.
3227 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003228
3229 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003230 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003231 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003232 FromType = PT->getPointeeType();
3233
Douglas Gregor02824322011-01-26 19:30:28 +00003234 // When we had a pointer, it's implicitly dereferenced, so we
3235 // better have an lvalue.
3236 assert(FromClassification.isLValue());
3237 }
3238
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003239 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003240
Douglas Gregor02824322011-01-26 19:30:28 +00003241 // C++0x [over.match.funcs]p4:
3242 // For non-static member functions, the type of the implicit object
3243 // parameter is
3244 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003245 // - "lvalue reference to cv X" for functions declared without a
3246 // ref-qualifier or with the & ref-qualifier
3247 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003248 // ref-qualifier
3249 //
3250 // where X is the class of which the function is a member and cv is the
3251 // cv-qualification on the member function declaration.
3252 //
3253 // However, when finding an implicit conversion sequence for the argument, we
3254 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003255 // (C++ [over.match.funcs]p5). We perform a simplified version of
3256 // reference binding here, that allows class rvalues to bind to
3257 // non-constant references.
3258
Douglas Gregor02824322011-01-26 19:30:28 +00003259 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003260 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003261 if (ImplicitParamType.getCVRQualifiers()
3262 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003263 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003264 ICS.setBad(BadConversionSequence::bad_qualifiers,
3265 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003266 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003267 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003268
3269 // Check that we have either the same type or a derived type. It
3270 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003271 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003272 ImplicitConversionKind SecondKind;
3273 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3274 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003275 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003276 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003277 else {
John McCall65eb8792010-02-25 01:37:24 +00003278 ICS.setBad(BadConversionSequence::unrelated_class,
3279 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003280 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003281 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003282
Douglas Gregor02824322011-01-26 19:30:28 +00003283 // Check the ref-qualifier.
3284 switch (Method->getRefQualifier()) {
3285 case RQ_None:
3286 // Do nothing; we don't care about lvalueness or rvalueness.
3287 break;
3288
3289 case RQ_LValue:
3290 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3291 // non-const lvalue reference cannot bind to an rvalue
3292 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
3293 ImplicitParamType);
3294 return ICS;
3295 }
3296 break;
3297
3298 case RQ_RValue:
3299 if (!FromClassification.isRValue()) {
3300 // rvalue reference cannot bind to an lvalue
3301 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
3302 ImplicitParamType);
3303 return ICS;
3304 }
3305 break;
3306 }
3307
Douglas Gregor436424c2008-11-18 23:14:02 +00003308 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003309 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003310 ICS.Standard.setAsIdentityConversion();
3311 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003312 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003313 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003314 ICS.Standard.ReferenceBinding = true;
3315 ICS.Standard.DirectBinding = true;
Douglas Gregor02824322011-01-26 19:30:28 +00003316 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003317 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003318 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3319 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3320 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003321 return ICS;
3322}
3323
3324/// PerformObjectArgumentInitialization - Perform initialization of
3325/// the implicit object parameter for the given Method with the given
3326/// expression.
3327bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003328Sema::PerformObjectArgumentInitialization(Expr *&From,
3329 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003330 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003331 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003332 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003333 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003334 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003335
Douglas Gregor02824322011-01-26 19:30:28 +00003336 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003337 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003338 FromRecordType = PT->getPointeeType();
3339 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003340 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003341 } else {
3342 FromRecordType = From->getType();
3343 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003344 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003345 }
3346
John McCall6e9f8f62009-12-03 04:06:58 +00003347 // Note that we always use the true parent context when performing
3348 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003349 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003350 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3351 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003352 if (ICS.isBad()) {
3353 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3354 Qualifiers FromQs = FromRecordType.getQualifiers();
3355 Qualifiers ToQs = DestType.getQualifiers();
3356 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3357 if (CVR) {
3358 Diag(From->getSourceRange().getBegin(),
3359 diag::err_member_function_call_bad_cvr)
3360 << Method->getDeclName() << FromRecordType << (CVR - 1)
3361 << From->getSourceRange();
3362 Diag(Method->getLocation(), diag::note_previous_decl)
3363 << Method->getDeclName();
3364 return true;
3365 }
3366 }
3367
Douglas Gregor436424c2008-11-18 23:14:02 +00003368 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003369 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003370 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003371 }
Mike Stump11289f42009-09-09 15:08:12 +00003372
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003373 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003374 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003375
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003376 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003377 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003378 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003379 return false;
3380}
3381
Douglas Gregor5fb53972009-01-14 15:45:31 +00003382/// TryContextuallyConvertToBool - Attempt to contextually convert the
3383/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003384static ImplicitConversionSequence
3385TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003386 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003387 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003388 // FIXME: Are these flags correct?
3389 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003390 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003391 /*InOverloadResolution=*/false,
3392 /*CStyle=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003393}
3394
3395/// PerformContextuallyConvertToBool - Perform a contextual conversion
3396/// of the expression From to bool (C++0x [conv]p3).
3397bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003398 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003399 if (!ICS.isBad())
3400 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003401
Fariborz Jahanian76197412009-11-18 18:26:29 +00003402 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003403 return Diag(From->getSourceRange().getBegin(),
3404 diag::err_typecheck_bool_condition)
3405 << From->getType() << From->getSourceRange();
3406 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003407}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003408
3409/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3410/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003411static ImplicitConversionSequence
3412TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3413 QualType Ty = S.Context.getObjCIdType();
3414 return TryImplicitConversion(S, From, Ty,
3415 // FIXME: Are these flags correct?
3416 /*SuppressUserConversions=*/false,
3417 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003418 /*InOverloadResolution=*/false,
3419 /*CStyle=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003420}
John McCall5c32be02010-08-24 20:38:10 +00003421
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003422/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3423/// of the expression From to 'id'.
3424bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003425 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003426 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003427 if (!ICS.isBad())
3428 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3429 return true;
3430}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003431
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003432/// \brief Attempt to convert the given expression to an integral or
3433/// enumeration type.
3434///
3435/// This routine will attempt to convert an expression of class type to an
3436/// integral or enumeration type, if that class type only has a single
3437/// conversion to an integral or enumeration type.
3438///
Douglas Gregor4799d032010-06-30 00:20:43 +00003439/// \param Loc The source location of the construct that requires the
3440/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003441///
Douglas Gregor4799d032010-06-30 00:20:43 +00003442/// \param FromE The expression we're converting from.
3443///
3444/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3445/// have integral or enumeration type.
3446///
3447/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3448/// incomplete class type.
3449///
3450/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3451/// explicit conversion function (because no implicit conversion functions
3452/// were available). This is a recovery mode.
3453///
3454/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3455/// showing which conversion was picked.
3456///
3457/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3458/// conversion function that could convert to integral or enumeration type.
3459///
3460/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3461/// usable conversion function.
3462///
3463/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3464/// function, which may be an extension in this case.
3465///
3466/// \returns The expression, converted to an integral or enumeration type if
3467/// successful.
John McCalldadc5752010-08-24 06:29:42 +00003468ExprResult
John McCallb268a282010-08-23 23:25:46 +00003469Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003470 const PartialDiagnostic &NotIntDiag,
3471 const PartialDiagnostic &IncompleteDiag,
3472 const PartialDiagnostic &ExplicitConvDiag,
3473 const PartialDiagnostic &ExplicitConvNote,
3474 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003475 const PartialDiagnostic &AmbigNote,
3476 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003477 // We can't perform any more checking for type-dependent expressions.
3478 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003479 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003480
3481 // If the expression already has integral or enumeration type, we're golden.
3482 QualType T = From->getType();
3483 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003484 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003485
3486 // FIXME: Check for missing '()' if T is a function type?
3487
3488 // If we don't have a class type in C++, there's no way we can get an
3489 // expression of integral or enumeration type.
3490 const RecordType *RecordTy = T->getAs<RecordType>();
3491 if (!RecordTy || !getLangOptions().CPlusPlus) {
3492 Diag(Loc, NotIntDiag)
3493 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003494 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003495 }
3496
3497 // We must have a complete class type.
3498 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003499 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003500
3501 // Look for a conversion to an integral or enumeration type.
3502 UnresolvedSet<4> ViableConversions;
3503 UnresolvedSet<4> ExplicitConversions;
3504 const UnresolvedSetImpl *Conversions
3505 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3506
3507 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3508 E = Conversions->end();
3509 I != E;
3510 ++I) {
3511 if (CXXConversionDecl *Conversion
3512 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3513 if (Conversion->getConversionType().getNonReferenceType()
3514 ->isIntegralOrEnumerationType()) {
3515 if (Conversion->isExplicit())
3516 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3517 else
3518 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3519 }
3520 }
3521
3522 switch (ViableConversions.size()) {
3523 case 0:
3524 if (ExplicitConversions.size() == 1) {
3525 DeclAccessPair Found = ExplicitConversions[0];
3526 CXXConversionDecl *Conversion
3527 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3528
3529 // The user probably meant to invoke the given explicit
3530 // conversion; use it.
3531 QualType ConvTy
3532 = Conversion->getConversionType().getNonReferenceType();
3533 std::string TypeStr;
3534 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3535
3536 Diag(Loc, ExplicitConvDiag)
3537 << T << ConvTy
3538 << FixItHint::CreateInsertion(From->getLocStart(),
3539 "static_cast<" + TypeStr + ">(")
3540 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3541 ")");
3542 Diag(Conversion->getLocation(), ExplicitConvNote)
3543 << ConvTy->isEnumeralType() << ConvTy;
3544
3545 // If we aren't in a SFINAE context, build a call to the
3546 // explicit conversion function.
3547 if (isSFINAEContext())
3548 return ExprError();
3549
3550 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00003551 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3552 if (Result.isInvalid())
3553 return ExprError();
3554
3555 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003556 }
3557
3558 // We'll complain below about a non-integral condition type.
3559 break;
3560
3561 case 1: {
3562 // Apply this conversion.
3563 DeclAccessPair Found = ViableConversions[0];
3564 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003565
3566 CXXConversionDecl *Conversion
3567 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3568 QualType ConvTy
3569 = Conversion->getConversionType().getNonReferenceType();
3570 if (ConvDiag.getDiagID()) {
3571 if (isSFINAEContext())
3572 return ExprError();
3573
3574 Diag(Loc, ConvDiag)
3575 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3576 }
3577
Douglas Gregor668443e2011-01-20 00:18:04 +00003578 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003579 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00003580 if (Result.isInvalid())
3581 return ExprError();
3582
3583 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003584 break;
3585 }
3586
3587 default:
3588 Diag(Loc, AmbigDiag)
3589 << T << From->getSourceRange();
3590 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3591 CXXConversionDecl *Conv
3592 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3593 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3594 Diag(Conv->getLocation(), AmbigNote)
3595 << ConvTy->isEnumeralType() << ConvTy;
3596 }
John McCallb268a282010-08-23 23:25:46 +00003597 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003598 }
3599
Douglas Gregor5823da32010-06-29 23:25:20 +00003600 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003601 Diag(Loc, NotIntDiag)
3602 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003603
John McCallb268a282010-08-23 23:25:46 +00003604 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003605}
3606
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003607/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003608/// candidate functions, using the given function call arguments. If
3609/// @p SuppressUserConversions, then don't allow user-defined
3610/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003611///
3612/// \para PartialOverloading true if we are performing "partial" overloading
3613/// based on an incomplete set of function arguments. This feature is used by
3614/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003615void
3616Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003617 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003618 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003619 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003620 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003621 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003622 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003623 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003624 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003625 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003626 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003627
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003628 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003629 if (!isa<CXXConstructorDecl>(Method)) {
3630 // If we get here, it's because we're calling a member function
3631 // that is named without a member access expression (e.g.,
3632 // "this->f") that was either written explicitly or created
3633 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003634 // function, e.g., X::f(). We use an empty type for the implied
3635 // object argument (C++ [over.call.func]p3), and the acting context
3636 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003637 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00003638 QualType(), Expr::Classification::makeSimpleLValue(),
3639 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003640 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003641 return;
3642 }
3643 // We treat a constructor like a non-member function, since its object
3644 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003645 }
3646
Douglas Gregorff7028a2009-11-13 23:59:09 +00003647 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003648 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003649
Douglas Gregor27381f32009-11-23 12:27:39 +00003650 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003651 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003652
Douglas Gregorffe14e32009-11-14 01:20:54 +00003653 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3654 // C++ [class.copy]p3:
3655 // A member function template is never instantiated to perform the copy
3656 // of a class object to an object of its class type.
3657 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3658 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003659 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003660 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3661 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003662 return;
3663 }
3664
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003665 // Add this candidate
3666 CandidateSet.push_back(OverloadCandidate());
3667 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003668 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003669 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003670 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003671 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003672 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003673 Candidate.ExplicitCallArguments = NumArgs;
3674
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003675 unsigned NumArgsInProto = Proto->getNumArgs();
3676
3677 // (C++ 13.3.2p2): A candidate function having fewer than m
3678 // parameters is viable only if it has an ellipsis in its parameter
3679 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003680 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3681 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003682 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003683 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003684 return;
3685 }
3686
3687 // (C++ 13.3.2p2): A candidate function having more than m parameters
3688 // is viable only if the (m+1)st parameter has a default argument
3689 // (8.3.6). For the purposes of overload resolution, the
3690 // parameter list is truncated on the right, so that there are
3691 // exactly m parameters.
3692 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003693 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003694 // Not enough arguments.
3695 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003696 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003697 return;
3698 }
3699
3700 // Determine the implicit conversion sequences for each of the
3701 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003702 Candidate.Conversions.resize(NumArgs);
3703 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3704 if (ArgIdx < NumArgsInProto) {
3705 // (C++ 13.3.2p3): for F to be a viable function, there shall
3706 // exist for each argument an implicit conversion sequence
3707 // (13.3.3.1) that converts that argument to the corresponding
3708 // parameter of F.
3709 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003710 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003711 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003712 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003713 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003714 if (Candidate.Conversions[ArgIdx].isBad()) {
3715 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003716 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003717 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003718 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003719 } else {
3720 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3721 // argument for which there is no corresponding parameter is
3722 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003723 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003724 }
3725 }
3726}
3727
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003728/// \brief Add all of the function declarations in the given function set to
3729/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003730void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003731 Expr **Args, unsigned NumArgs,
3732 OverloadCandidateSet& CandidateSet,
3733 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003734 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003735 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3736 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003737 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003738 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003739 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00003740 Args[0]->getType(), Args[0]->Classify(Context),
3741 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003742 CandidateSet, SuppressUserConversions);
3743 else
John McCalla0296f72010-03-19 07:35:19 +00003744 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003745 SuppressUserConversions);
3746 } else {
John McCalla0296f72010-03-19 07:35:19 +00003747 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003748 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3749 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003750 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003751 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003752 /*FIXME: explicit args */ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00003753 Args[0]->getType(),
3754 Args[0]->Classify(Context),
3755 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003756 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003757 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003758 else
John McCalla0296f72010-03-19 07:35:19 +00003759 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003760 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003761 Args, NumArgs, CandidateSet,
3762 SuppressUserConversions);
3763 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003764 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003765}
3766
John McCallf0f1cf02009-11-17 07:50:12 +00003767/// AddMethodCandidate - Adds a named decl (which is some kind of
3768/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003769void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003770 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00003771 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00003772 Expr **Args, unsigned NumArgs,
3773 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003774 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003775 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003776 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003777
3778 if (isa<UsingShadowDecl>(Decl))
3779 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3780
3781 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3782 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3783 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003784 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3785 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00003786 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003787 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003788 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003789 } else {
John McCalla0296f72010-03-19 07:35:19 +00003790 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00003791 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003792 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003793 }
3794}
3795
Douglas Gregor436424c2008-11-18 23:14:02 +00003796/// AddMethodCandidate - Adds the given C++ member function to the set
3797/// of candidate functions, using the given function call arguments
3798/// and the object argument (@c Object). For example, in a call
3799/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3800/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3801/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003802/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003803void
John McCalla0296f72010-03-19 07:35:19 +00003804Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003805 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00003806 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00003807 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003808 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003809 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003810 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003811 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003812 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003813 assert(!isa<CXXConstructorDecl>(Method) &&
3814 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003815
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003816 if (!CandidateSet.isNewCandidate(Method))
3817 return;
3818
Douglas Gregor27381f32009-11-23 12:27:39 +00003819 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003820 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003821
Douglas Gregor436424c2008-11-18 23:14:02 +00003822 // Add this candidate
3823 CandidateSet.push_back(OverloadCandidate());
3824 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003825 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003826 Candidate.Function = Method;
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;
Douglas Gregor436424c2008-11-18 23:14:02 +00003830
3831 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).
3836 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3837 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003838 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003839 return;
3840 }
3841
3842 // (C++ 13.3.2p2): A candidate function having more than m parameters
3843 // is viable only if the (m+1)st parameter has a default argument
3844 // (8.3.6). For the purposes of overload resolution, the
3845 // parameter list is truncated on the right, so that there are
3846 // exactly m parameters.
3847 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3848 if (NumArgs < MinRequiredArgs) {
3849 // Not enough arguments.
3850 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003851 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003852 return;
3853 }
3854
3855 Candidate.Viable = true;
3856 Candidate.Conversions.resize(NumArgs + 1);
3857
John McCall6e9f8f62009-12-03 04:06:58 +00003858 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003859 // The implicit object argument is ignored.
3860 Candidate.IgnoreObjectArgument = true;
3861 else {
3862 // Determine the implicit conversion sequence for the object
3863 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003864 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00003865 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
3866 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003867 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003868 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003869 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003870 return;
3871 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003872 }
3873
3874 // Determine the implicit conversion sequences for each of the
3875 // arguments.
3876 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3877 if (ArgIdx < NumArgsInProto) {
3878 // (C++ 13.3.2p3): for F to be a viable function, there shall
3879 // exist for each argument an implicit conversion sequence
3880 // (13.3.3.1) that converts that argument to the corresponding
3881 // parameter of F.
3882 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003883 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003884 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003885 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003886 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003887 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003888 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003889 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003890 break;
3891 }
3892 } else {
3893 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3894 // argument for which there is no corresponding parameter is
3895 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003896 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003897 }
3898 }
3899}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003900
Douglas Gregor97628d62009-08-21 00:16:32 +00003901/// \brief Add a C++ member function template as a candidate to the candidate
3902/// set, using template argument deduction to produce an appropriate member
3903/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003904void
Douglas Gregor97628d62009-08-21 00:16:32 +00003905Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003906 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003907 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003908 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003909 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00003910 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00003911 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003912 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003913 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003914 if (!CandidateSet.isNewCandidate(MethodTmpl))
3915 return;
3916
Douglas Gregor97628d62009-08-21 00:16:32 +00003917 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003918 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003919 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003920 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003921 // candidate functions in the usual way.113) A given name can refer to one
3922 // or more function templates and also to a set of overloaded non-template
3923 // functions. In such a case, the candidate functions generated from each
3924 // function template are combined with the set of non-template candidate
3925 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003926 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003927 FunctionDecl *Specialization = 0;
3928 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003929 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003930 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003931 CandidateSet.push_back(OverloadCandidate());
3932 OverloadCandidate &Candidate = CandidateSet.back();
3933 Candidate.FoundDecl = FoundDecl;
3934 Candidate.Function = MethodTmpl->getTemplatedDecl();
3935 Candidate.Viable = false;
3936 Candidate.FailureKind = ovl_fail_bad_deduction;
3937 Candidate.IsSurrogate = false;
3938 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003939 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003940 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3941 Info);
3942 return;
3943 }
Mike Stump11289f42009-09-09 15:08:12 +00003944
Douglas Gregor97628d62009-08-21 00:16:32 +00003945 // Add the function template specialization produced by template argument
3946 // deduction as a candidate.
3947 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003948 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003949 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003950 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00003951 ActingContext, ObjectType, ObjectClassification,
3952 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003953}
3954
Douglas Gregor05155d82009-08-21 23:19:43 +00003955/// \brief Add a C++ function template specialization as a candidate
3956/// in the candidate set, using template argument deduction to produce
3957/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003958void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003959Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003960 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003961 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003962 Expr **Args, unsigned NumArgs,
3963 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003964 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003965 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3966 return;
3967
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003968 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003969 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003970 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003971 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003972 // candidate functions in the usual way.113) A given name can refer to one
3973 // or more function templates and also to a set of overloaded non-template
3974 // functions. In such a case, the candidate functions generated from each
3975 // function template are combined with the set of non-template candidate
3976 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003977 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003978 FunctionDecl *Specialization = 0;
3979 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003980 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003981 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003982 CandidateSet.push_back(OverloadCandidate());
3983 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003984 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003985 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3986 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003987 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003988 Candidate.IsSurrogate = false;
3989 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003990 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003991 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3992 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003993 return;
3994 }
Mike Stump11289f42009-09-09 15:08:12 +00003995
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003996 // Add the function template specialization produced by template argument
3997 // deduction as a candidate.
3998 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003999 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004000 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004001}
Mike Stump11289f42009-09-09 15:08:12 +00004002
Douglas Gregora1f013e2008-11-07 22:36:19 +00004003/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004004/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004005/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004006/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004007/// (which may or may not be the same type as the type that the
4008/// conversion function produces).
4009void
4010Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004011 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004012 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004013 Expr *From, QualType ToType,
4014 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004015 assert(!Conversion->getDescribedFunctionTemplate() &&
4016 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004017 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004018 if (!CandidateSet.isNewCandidate(Conversion))
4019 return;
4020
Douglas Gregor27381f32009-11-23 12:27:39 +00004021 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004022 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004023
Douglas Gregora1f013e2008-11-07 22:36:19 +00004024 // Add this candidate
4025 CandidateSet.push_back(OverloadCandidate());
4026 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004027 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004028 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004029 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004030 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004031 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004032 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004033 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004034 Candidate.Viable = true;
4035 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004036 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004037
Douglas Gregor6affc782010-08-19 15:37:02 +00004038 // C++ [over.match.funcs]p4:
4039 // For conversion functions, the function is considered to be a member of
4040 // the class of the implicit implied object argument for the purpose of
4041 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004042 //
4043 // Determine the implicit conversion sequence for the implicit
4044 // object parameter.
4045 QualType ImplicitParamType = From->getType();
4046 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4047 ImplicitParamType = FromPtrType->getPointeeType();
4048 CXXRecordDecl *ConversionContext
4049 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
4050
4051 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004052 = TryObjectArgumentInitialization(*this, From->getType(),
4053 From->Classify(Context),
4054 Conversion, ConversionContext);
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004055
John McCall0d1da222010-01-12 00:44:57 +00004056 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004057 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004058 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004059 return;
4060 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004061
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004062 // We won't go through a user-define type conversion function to convert a
4063 // derived to base as such conversions are given Conversion Rank. They only
4064 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4065 QualType FromCanon
4066 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4067 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4068 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4069 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004070 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004071 return;
4072 }
4073
Douglas Gregora1f013e2008-11-07 22:36:19 +00004074 // To determine what the conversion from the result of calling the
4075 // conversion function to the type we're eventually trying to
4076 // convert to (ToType), we need to synthesize a call to the
4077 // conversion function and attempt copy initialization from it. This
4078 // makes sure that we get the right semantics with respect to
4079 // lvalues/rvalues and the type. Fortunately, we can allocate this
4080 // call on the stack and we don't need its arguments to be
4081 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004082 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004083 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004084 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4085 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004086 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004087 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004088
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004089 QualType CallResultType
4090 = Conversion->getConversionType().getNonLValueExprType(Context);
4091 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4092 Candidate.Viable = false;
4093 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4094 return;
4095 }
4096
John McCall7decc9e2010-11-18 06:31:45 +00004097 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4098
Mike Stump11289f42009-09-09 15:08:12 +00004099 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004100 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4101 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00004102 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004103 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004104 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004105 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004106 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00004107 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004108
John McCall0d1da222010-01-12 00:44:57 +00004109 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004110 case ImplicitConversionSequence::StandardConversion:
4111 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004112
4113 // C++ [over.ics.user]p3:
4114 // If the user-defined conversion is specified by a specialization of a
4115 // conversion function template, the second standard conversion sequence
4116 // shall have exact match rank.
4117 if (Conversion->getPrimaryTemplate() &&
4118 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4119 Candidate.Viable = false;
4120 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4121 }
4122
Douglas Gregorcba72b12011-01-21 05:18:22 +00004123 // C++0x [dcl.init.ref]p5:
4124 // In the second case, if the reference is an rvalue reference and
4125 // the second standard conversion sequence of the user-defined
4126 // conversion sequence includes an lvalue-to-rvalue conversion, the
4127 // program is ill-formed.
4128 if (ToType->isRValueReferenceType() &&
4129 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4130 Candidate.Viable = false;
4131 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4132 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004133 break;
4134
4135 case ImplicitConversionSequence::BadConversion:
4136 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004137 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004138 break;
4139
4140 default:
Mike Stump11289f42009-09-09 15:08:12 +00004141 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004142 "Can only end up with a standard conversion sequence or failure");
4143 }
4144}
4145
Douglas Gregor05155d82009-08-21 23:19:43 +00004146/// \brief Adds a conversion function template specialization
4147/// candidate to the overload set, using template argument deduction
4148/// to deduce the template arguments of the conversion function
4149/// template from the type that we are converting to (C++
4150/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004151void
Douglas Gregor05155d82009-08-21 23:19:43 +00004152Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004153 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004154 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004155 Expr *From, QualType ToType,
4156 OverloadCandidateSet &CandidateSet) {
4157 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4158 "Only conversion function templates permitted here");
4159
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004160 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4161 return;
4162
John McCallbc077cf2010-02-08 23:07:23 +00004163 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004164 CXXConversionDecl *Specialization = 0;
4165 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004166 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004167 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004168 CandidateSet.push_back(OverloadCandidate());
4169 OverloadCandidate &Candidate = CandidateSet.back();
4170 Candidate.FoundDecl = FoundDecl;
4171 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4172 Candidate.Viable = false;
4173 Candidate.FailureKind = ovl_fail_bad_deduction;
4174 Candidate.IsSurrogate = false;
4175 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004176 Candidate.ExplicitCallArguments = 1;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004177 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4178 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004179 return;
4180 }
Mike Stump11289f42009-09-09 15:08:12 +00004181
Douglas Gregor05155d82009-08-21 23:19:43 +00004182 // Add the conversion function template specialization produced by
4183 // template argument deduction as a candidate.
4184 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004185 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004186 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004187}
4188
Douglas Gregorab7897a2008-11-19 22:57:39 +00004189/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4190/// converts the given @c Object to a function pointer via the
4191/// conversion function @c Conversion, and then attempts to call it
4192/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4193/// the type of function that we'll eventually be calling.
4194void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004195 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004196 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004197 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004198 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004199 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004200 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004201 if (!CandidateSet.isNewCandidate(Conversion))
4202 return;
4203
Douglas Gregor27381f32009-11-23 12:27:39 +00004204 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004205 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004206
Douglas Gregorab7897a2008-11-19 22:57:39 +00004207 CandidateSet.push_back(OverloadCandidate());
4208 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004209 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004210 Candidate.Function = 0;
4211 Candidate.Surrogate = Conversion;
4212 Candidate.Viable = true;
4213 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004214 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004215 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004216 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004217
4218 // Determine the implicit conversion sequence for the implicit
4219 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004220 ImplicitConversionSequence ObjectInit
Douglas Gregor02824322011-01-26 19:30:28 +00004221 = TryObjectArgumentInitialization(*this, Object->getType(),
4222 Object->Classify(Context),
4223 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004224 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004225 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004226 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004227 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004228 return;
4229 }
4230
4231 // The first conversion is actually a user-defined conversion whose
4232 // first conversion is ObjectInit's standard conversion (which is
4233 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004234 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004235 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004236 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004237 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00004238 Candidate.Conversions[0].UserDefined.FoundConversionFunction
4239 = FoundDecl.getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004240 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004241 = Candidate.Conversions[0].UserDefined.Before;
4242 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4243
Mike Stump11289f42009-09-09 15:08:12 +00004244 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004245 unsigned NumArgsInProto = Proto->getNumArgs();
4246
4247 // (C++ 13.3.2p2): A candidate function having fewer than m
4248 // parameters is viable only if it has an ellipsis in its parameter
4249 // list (8.3.5).
4250 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4251 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004252 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004253 return;
4254 }
4255
4256 // Function types don't have any default arguments, so just check if
4257 // we have enough arguments.
4258 if (NumArgs < NumArgsInProto) {
4259 // Not enough arguments.
4260 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004261 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004262 return;
4263 }
4264
4265 // Determine the implicit conversion sequences for each of the
4266 // arguments.
4267 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4268 if (ArgIdx < NumArgsInProto) {
4269 // (C++ 13.3.2p3): for F to be a viable function, there shall
4270 // exist for each argument an implicit conversion sequence
4271 // (13.3.3.1) that converts that argument to the corresponding
4272 // parameter of F.
4273 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004274 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004275 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004276 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004277 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004278 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004279 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004280 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004281 break;
4282 }
4283 } else {
4284 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4285 // argument for which there is no corresponding parameter is
4286 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004287 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004288 }
4289 }
4290}
4291
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004292/// \brief Add overload candidates for overloaded operators that are
4293/// member functions.
4294///
4295/// Add the overloaded operator candidates that are member functions
4296/// for the operator Op that was used in an operator expression such
4297/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4298/// CandidateSet will store the added overload candidates. (C++
4299/// [over.match.oper]).
4300void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4301 SourceLocation OpLoc,
4302 Expr **Args, unsigned NumArgs,
4303 OverloadCandidateSet& CandidateSet,
4304 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004305 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4306
4307 // C++ [over.match.oper]p3:
4308 // For a unary operator @ with an operand of a type whose
4309 // cv-unqualified version is T1, and for a binary operator @ with
4310 // a left operand of a type whose cv-unqualified version is T1 and
4311 // a right operand of a type whose cv-unqualified version is T2,
4312 // three sets of candidate functions, designated member
4313 // candidates, non-member candidates and built-in candidates, are
4314 // constructed as follows:
4315 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004316
4317 // -- If T1 is a class type, the set of member candidates is the
4318 // result of the qualified lookup of T1::operator@
4319 // (13.3.1.1.1); otherwise, the set of member candidates is
4320 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004321 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004322 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004323 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004324 return;
Mike Stump11289f42009-09-09 15:08:12 +00004325
John McCall27b18f82009-11-17 02:14:36 +00004326 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4327 LookupQualifiedName(Operators, T1Rec->getDecl());
4328 Operators.suppressDiagnostics();
4329
Mike Stump11289f42009-09-09 15:08:12 +00004330 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004331 OperEnd = Operators.end();
4332 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004333 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004334 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004335 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
4336 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004337 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004338 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004339}
4340
Douglas Gregora11693b2008-11-12 17:17:38 +00004341/// AddBuiltinCandidate - Add a candidate for a built-in
4342/// operator. ResultTy and ParamTys are the result and parameter types
4343/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004344/// arguments being passed to the candidate. IsAssignmentOperator
4345/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004346/// operator. NumContextualBoolArguments is the number of arguments
4347/// (at the beginning of the argument list) that will be contextually
4348/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004349void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004350 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004351 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004352 bool IsAssignmentOperator,
4353 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004354 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004355 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004356
Douglas Gregora11693b2008-11-12 17:17:38 +00004357 // Add this candidate
4358 CandidateSet.push_back(OverloadCandidate());
4359 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004360 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004361 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004362 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004363 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004364 Candidate.BuiltinTypes.ResultTy = ResultTy;
4365 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4366 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4367
4368 // Determine the implicit conversion sequences for each of the
4369 // arguments.
4370 Candidate.Viable = true;
4371 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004372 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004373 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004374 // C++ [over.match.oper]p4:
4375 // For the built-in assignment operators, conversions of the
4376 // left operand are restricted as follows:
4377 // -- no temporaries are introduced to hold the left operand, and
4378 // -- no user-defined conversions are applied to the left
4379 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004380 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004381 //
4382 // We block these conversions by turning off user-defined
4383 // conversions, since that is the only way that initialization of
4384 // a reference to a non-class type can occur from something that
4385 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004386 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004387 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004388 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004389 Candidate.Conversions[ArgIdx]
4390 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004391 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004392 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004393 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004394 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004395 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004396 }
John McCall0d1da222010-01-12 00:44:57 +00004397 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004398 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004399 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004400 break;
4401 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004402 }
4403}
4404
4405/// BuiltinCandidateTypeSet - A set of types that will be used for the
4406/// candidate operator functions for built-in operators (C++
4407/// [over.built]). The types are separated into pointer types and
4408/// enumeration types.
4409class BuiltinCandidateTypeSet {
4410 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004411 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004412
4413 /// PointerTypes - The set of pointer types that will be used in the
4414 /// built-in candidates.
4415 TypeSet PointerTypes;
4416
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004417 /// MemberPointerTypes - The set of member pointer types that will be
4418 /// used in the built-in candidates.
4419 TypeSet MemberPointerTypes;
4420
Douglas Gregora11693b2008-11-12 17:17:38 +00004421 /// EnumerationTypes - The set of enumeration types that will be
4422 /// used in the built-in candidates.
4423 TypeSet EnumerationTypes;
4424
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004425 /// \brief The set of vector types that will be used in the built-in
4426 /// candidates.
4427 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004428
4429 /// \brief A flag indicating non-record types are viable candidates
4430 bool HasNonRecordTypes;
4431
4432 /// \brief A flag indicating whether either arithmetic or enumeration types
4433 /// were present in the candidate set.
4434 bool HasArithmeticOrEnumeralTypes;
4435
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004436 /// Sema - The semantic analysis instance where we are building the
4437 /// candidate type set.
4438 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004439
Douglas Gregora11693b2008-11-12 17:17:38 +00004440 /// Context - The AST context in which we will build the type sets.
4441 ASTContext &Context;
4442
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004443 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4444 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004445 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004446
4447public:
4448 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004449 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004450
Mike Stump11289f42009-09-09 15:08:12 +00004451 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004452 : HasNonRecordTypes(false),
4453 HasArithmeticOrEnumeralTypes(false),
4454 SemaRef(SemaRef),
4455 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004456
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004457 void AddTypesConvertedFrom(QualType Ty,
4458 SourceLocation Loc,
4459 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004460 bool AllowExplicitConversions,
4461 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004462
4463 /// pointer_begin - First pointer type found;
4464 iterator pointer_begin() { return PointerTypes.begin(); }
4465
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004466 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004467 iterator pointer_end() { return PointerTypes.end(); }
4468
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004469 /// member_pointer_begin - First member pointer type found;
4470 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4471
4472 /// member_pointer_end - Past the last member pointer type found;
4473 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4474
Douglas Gregora11693b2008-11-12 17:17:38 +00004475 /// enumeration_begin - First enumeration type found;
4476 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4477
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004478 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004479 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004480
4481 iterator vector_begin() { return VectorTypes.begin(); }
4482 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00004483
4484 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4485 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregora11693b2008-11-12 17:17:38 +00004486};
4487
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004488/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004489/// the set of pointer types along with any more-qualified variants of
4490/// that type. For example, if @p Ty is "int const *", this routine
4491/// will add "int const *", "int const volatile *", "int const
4492/// restrict *", and "int const volatile restrict *" to the set of
4493/// pointer types. Returns true if the add of @p Ty itself succeeded,
4494/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004495///
4496/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004497bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004498BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4499 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004500
Douglas Gregora11693b2008-11-12 17:17:38 +00004501 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004502 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004503 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004504
4505 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004506 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004507 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004508 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004509 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004510 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004511 buildObjCPtr = true;
4512 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004513 else
4514 assert(false && "type was not a pointer type!");
4515 }
4516 else
4517 PointeeTy = PointerTy->getPointeeType();
4518
Sebastian Redl4990a632009-11-18 20:39:26 +00004519 // Don't add qualified variants of arrays. For one, they're not allowed
4520 // (the qualifier would sink to the element type), and for another, the
4521 // only overload situation where it matters is subscript or pointer +- int,
4522 // and those shouldn't have qualifier variants anyway.
4523 if (PointeeTy->isArrayType())
4524 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004525 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004526 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004527 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004528 bool hasVolatile = VisibleQuals.hasVolatile();
4529 bool hasRestrict = VisibleQuals.hasRestrict();
4530
John McCall8ccfcb52009-09-24 19:53:00 +00004531 // Iterate through all strict supersets of BaseCVR.
4532 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4533 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004534 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4535 // in the types.
4536 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4537 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004538 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004539 if (!buildObjCPtr)
4540 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4541 else
4542 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004543 }
4544
4545 return true;
4546}
4547
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004548/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4549/// to the set of pointer types along with any more-qualified variants of
4550/// that type. For example, if @p Ty is "int const *", this routine
4551/// will add "int const *", "int const volatile *", "int const
4552/// restrict *", and "int const volatile restrict *" to the set of
4553/// pointer types. Returns true if the add of @p Ty itself succeeded,
4554/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004555///
4556/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004557bool
4558BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4559 QualType Ty) {
4560 // Insert this type.
4561 if (!MemberPointerTypes.insert(Ty))
4562 return false;
4563
John McCall8ccfcb52009-09-24 19:53:00 +00004564 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4565 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004566
John McCall8ccfcb52009-09-24 19:53:00 +00004567 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004568 // Don't add qualified variants of arrays. For one, they're not allowed
4569 // (the qualifier would sink to the element type), and for another, the
4570 // only overload situation where it matters is subscript or pointer +- int,
4571 // and those shouldn't have qualifier variants anyway.
4572 if (PointeeTy->isArrayType())
4573 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004574 const Type *ClassTy = PointerTy->getClass();
4575
4576 // Iterate through all strict supersets of the pointee type's CVR
4577 // qualifiers.
4578 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4579 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4580 if ((CVR | BaseCVR) != CVR) continue;
4581
4582 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00004583 MemberPointerTypes.insert(
4584 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004585 }
4586
4587 return true;
4588}
4589
Douglas Gregora11693b2008-11-12 17:17:38 +00004590/// AddTypesConvertedFrom - Add each of the types to which the type @p
4591/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004592/// primarily interested in pointer types and enumeration types. We also
4593/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004594/// AllowUserConversions is true if we should look at the conversion
4595/// functions of a class type, and AllowExplicitConversions if we
4596/// should also include the explicit conversion functions of a class
4597/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004598void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004599BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004600 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004601 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004602 bool AllowExplicitConversions,
4603 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004604 // Only deal with canonical types.
4605 Ty = Context.getCanonicalType(Ty);
4606
4607 // Look through reference types; they aren't part of the type of an
4608 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004609 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004610 Ty = RefTy->getPointeeType();
4611
John McCall33ddac02011-01-19 10:06:00 +00004612 // If we're dealing with an array type, decay to the pointer.
4613 if (Ty->isArrayType())
4614 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4615
4616 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004617 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004618
Chandler Carruth00a38332010-12-13 01:44:01 +00004619 // Flag if we ever add a non-record type.
4620 const RecordType *TyRec = Ty->getAs<RecordType>();
4621 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4622
Chandler Carruth00a38332010-12-13 01:44:01 +00004623 // Flag if we encounter an arithmetic type.
4624 HasArithmeticOrEnumeralTypes =
4625 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4626
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004627 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4628 PointerTypes.insert(Ty);
4629 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004630 // Insert our type, and its more-qualified variants, into the set
4631 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004632 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004633 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004634 } else if (Ty->isMemberPointerType()) {
4635 // Member pointers are far easier, since the pointee can't be converted.
4636 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4637 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004638 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004639 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00004640 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004641 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004642 // We treat vector types as arithmetic types in many contexts as an
4643 // extension.
4644 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004645 VectorTypes.insert(Ty);
Chandler Carruth00a38332010-12-13 01:44:01 +00004646 } else if (AllowUserConversions && TyRec) {
4647 // No conversion functions in incomplete types.
4648 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4649 return;
Mike Stump11289f42009-09-09 15:08:12 +00004650
Chandler Carruth00a38332010-12-13 01:44:01 +00004651 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4652 const UnresolvedSetImpl *Conversions
4653 = ClassDecl->getVisibleConversionFunctions();
4654 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4655 E = Conversions->end(); I != E; ++I) {
4656 NamedDecl *D = I.getDecl();
4657 if (isa<UsingShadowDecl>(D))
4658 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004659
Chandler Carruth00a38332010-12-13 01:44:01 +00004660 // Skip conversion function templates; they don't tell us anything
4661 // about which builtin types we can convert to.
4662 if (isa<FunctionTemplateDecl>(D))
4663 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00004664
Chandler Carruth00a38332010-12-13 01:44:01 +00004665 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4666 if (AllowExplicitConversions || !Conv->isExplicit()) {
4667 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4668 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004669 }
4670 }
4671 }
4672}
4673
Douglas Gregor84605ae2009-08-24 13:43:27 +00004674/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4675/// the volatile- and non-volatile-qualified assignment operators for the
4676/// given type to the candidate set.
4677static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4678 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004679 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004680 unsigned NumArgs,
4681 OverloadCandidateSet &CandidateSet) {
4682 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004683
Douglas Gregor84605ae2009-08-24 13:43:27 +00004684 // T& operator=(T&, T)
4685 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4686 ParamTypes[1] = T;
4687 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4688 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004689
Douglas Gregor84605ae2009-08-24 13:43:27 +00004690 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4691 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004692 ParamTypes[0]
4693 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004694 ParamTypes[1] = T;
4695 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004696 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004697 }
4698}
Mike Stump11289f42009-09-09 15:08:12 +00004699
Sebastian Redl1054fae2009-10-25 17:03:50 +00004700/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4701/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004702static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4703 Qualifiers VRQuals;
4704 const RecordType *TyRec;
4705 if (const MemberPointerType *RHSMPType =
4706 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004707 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004708 else
4709 TyRec = ArgExpr->getType()->getAs<RecordType>();
4710 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004711 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004712 VRQuals.addVolatile();
4713 VRQuals.addRestrict();
4714 return VRQuals;
4715 }
4716
4717 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004718 if (!ClassDecl->hasDefinition())
4719 return VRQuals;
4720
John McCallad371252010-01-20 00:46:10 +00004721 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004722 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004723
John McCallad371252010-01-20 00:46:10 +00004724 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004725 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004726 NamedDecl *D = I.getDecl();
4727 if (isa<UsingShadowDecl>(D))
4728 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4729 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004730 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4731 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4732 CanTy = ResTypeRef->getPointeeType();
4733 // Need to go down the pointer/mempointer chain and add qualifiers
4734 // as see them.
4735 bool done = false;
4736 while (!done) {
4737 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4738 CanTy = ResTypePtr->getPointeeType();
4739 else if (const MemberPointerType *ResTypeMPtr =
4740 CanTy->getAs<MemberPointerType>())
4741 CanTy = ResTypeMPtr->getPointeeType();
4742 else
4743 done = true;
4744 if (CanTy.isVolatileQualified())
4745 VRQuals.addVolatile();
4746 if (CanTy.isRestrictQualified())
4747 VRQuals.addRestrict();
4748 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4749 return VRQuals;
4750 }
4751 }
4752 }
4753 return VRQuals;
4754}
John McCall52872982010-11-13 05:51:15 +00004755
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004756namespace {
John McCall52872982010-11-13 05:51:15 +00004757
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004758/// \brief Helper class to manage the addition of builtin operator overload
4759/// candidates. It provides shared state and utility methods used throughout
4760/// the process, as well as a helper method to add each group of builtin
4761/// operator overloads from the standard to a candidate set.
4762class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004763 // Common instance state available to all overload candidate addition methods.
4764 Sema &S;
4765 Expr **Args;
4766 unsigned NumArgs;
4767 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00004768 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruthc6586e52010-12-12 10:35:00 +00004769 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4770 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004771
Chandler Carruthc6586e52010-12-12 10:35:00 +00004772 // Define some constants used to index and iterate over the arithemetic types
4773 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00004774 // The "promoted arithmetic types" are the arithmetic
4775 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00004776 static const unsigned FirstIntegralType = 3;
4777 static const unsigned LastIntegralType = 18;
4778 static const unsigned FirstPromotedIntegralType = 3,
4779 LastPromotedIntegralType = 9;
4780 static const unsigned FirstPromotedArithmeticType = 0,
4781 LastPromotedArithmeticType = 9;
4782 static const unsigned NumArithmeticTypes = 18;
4783
Chandler Carruthc6586e52010-12-12 10:35:00 +00004784 /// \brief Get the canonical type for a given arithmetic type index.
4785 CanQualType getArithmeticType(unsigned index) {
4786 assert(index < NumArithmeticTypes);
4787 static CanQualType ASTContext::* const
4788 ArithmeticTypes[NumArithmeticTypes] = {
4789 // Start of promoted types.
4790 &ASTContext::FloatTy,
4791 &ASTContext::DoubleTy,
4792 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00004793
Chandler Carruthc6586e52010-12-12 10:35:00 +00004794 // Start of integral types.
4795 &ASTContext::IntTy,
4796 &ASTContext::LongTy,
4797 &ASTContext::LongLongTy,
4798 &ASTContext::UnsignedIntTy,
4799 &ASTContext::UnsignedLongTy,
4800 &ASTContext::UnsignedLongLongTy,
4801 // End of promoted types.
4802
4803 &ASTContext::BoolTy,
4804 &ASTContext::CharTy,
4805 &ASTContext::WCharTy,
4806 &ASTContext::Char16Ty,
4807 &ASTContext::Char32Ty,
4808 &ASTContext::SignedCharTy,
4809 &ASTContext::ShortTy,
4810 &ASTContext::UnsignedCharTy,
4811 &ASTContext::UnsignedShortTy,
4812 // End of integral types.
4813 // FIXME: What about complex?
4814 };
4815 return S.Context.*ArithmeticTypes[index];
4816 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004817
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004818 /// \brief Gets the canonical type resulting from the usual arithemetic
4819 /// converions for the given arithmetic types.
4820 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
4821 // Accelerator table for performing the usual arithmetic conversions.
4822 // The rules are basically:
4823 // - if either is floating-point, use the wider floating-point
4824 // - if same signedness, use the higher rank
4825 // - if same size, use unsigned of the higher rank
4826 // - use the larger type
4827 // These rules, together with the axiom that higher ranks are
4828 // never smaller, are sufficient to precompute all of these results
4829 // *except* when dealing with signed types of higher rank.
4830 // (we could precompute SLL x UI for all known platforms, but it's
4831 // better not to make any assumptions).
4832 enum PromotedType {
4833 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
4834 };
4835 static PromotedType ConversionsTable[LastPromotedArithmeticType]
4836 [LastPromotedArithmeticType] = {
4837 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4838 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4839 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4840 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4841 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4842 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4843 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4844 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4845 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
4846 };
4847
4848 assert(L < LastPromotedArithmeticType);
4849 assert(R < LastPromotedArithmeticType);
4850 int Idx = ConversionsTable[L][R];
4851
4852 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004853 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004854
4855 // Slow path: we need to compare widths.
4856 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004857 CanQualType LT = getArithmeticType(L),
4858 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004859 unsigned LW = S.Context.getIntWidth(LT),
4860 RW = S.Context.getIntWidth(RT);
4861
4862 // If they're different widths, use the signed type.
4863 if (LW > RW) return LT;
4864 else if (LW < RW) return RT;
4865
4866 // Otherwise, use the unsigned type of the signed type's rank.
4867 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
4868 assert(L == SLL || R == SLL);
4869 return S.Context.UnsignedLongLongTy;
4870 }
4871
Chandler Carruth5659c0c2010-12-12 09:22:45 +00004872 /// \brief Helper method to factor out the common pattern of adding overloads
4873 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004874 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
4875 bool HasVolatile) {
4876 QualType ParamTypes[2] = {
4877 S.Context.getLValueReferenceType(CandidateTy),
4878 S.Context.IntTy
4879 };
4880
4881 // Non-volatile version.
4882 if (NumArgs == 1)
4883 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4884 else
4885 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4886
4887 // Use a heuristic to reduce number of builtin candidates in the set:
4888 // add volatile version only if there are conversions to a volatile type.
4889 if (HasVolatile) {
4890 ParamTypes[0] =
4891 S.Context.getLValueReferenceType(
4892 S.Context.getVolatileType(CandidateTy));
4893 if (NumArgs == 1)
4894 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4895 else
4896 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4897 }
4898 }
4899
4900public:
4901 BuiltinOperatorOverloadBuilder(
4902 Sema &S, Expr **Args, unsigned NumArgs,
4903 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00004904 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004905 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
4906 OverloadCandidateSet &CandidateSet)
4907 : S(S), Args(Args), NumArgs(NumArgs),
4908 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00004909 HasArithmeticOrEnumeralCandidateType(
4910 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004911 CandidateTypes(CandidateTypes),
4912 CandidateSet(CandidateSet) {
4913 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004914 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004915 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004916 assert(getArithmeticType(LastPromotedIntegralType - 1)
4917 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004918 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004919 assert(getArithmeticType(FirstPromotedArithmeticType)
4920 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004921 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004922 assert(getArithmeticType(LastPromotedArithmeticType - 1)
4923 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004924 "Invalid last promoted arithmetic type");
4925 }
4926
4927 // C++ [over.built]p3:
4928 //
4929 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4930 // is either volatile or empty, there exist candidate operator
4931 // functions of the form
4932 //
4933 // VQ T& operator++(VQ T&);
4934 // T operator++(VQ T&, int);
4935 //
4936 // C++ [over.built]p4:
4937 //
4938 // For every pair (T, VQ), where T is an arithmetic type other
4939 // than bool, and VQ is either volatile or empty, there exist
4940 // candidate operator functions of the form
4941 //
4942 // VQ T& operator--(VQ T&);
4943 // T operator--(VQ T&, int);
4944 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004945 if (!HasArithmeticOrEnumeralCandidateType)
4946 return;
4947
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004948 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
4949 Arith < NumArithmeticTypes; ++Arith) {
4950 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00004951 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004952 VisibleTypeConversionsQuals.hasVolatile());
4953 }
4954 }
4955
4956 // C++ [over.built]p5:
4957 //
4958 // For every pair (T, VQ), where T is a cv-qualified or
4959 // cv-unqualified object type, and VQ is either volatile or
4960 // empty, there exist candidate operator functions of the form
4961 //
4962 // T*VQ& operator++(T*VQ&);
4963 // T*VQ& operator--(T*VQ&);
4964 // T* operator++(T*VQ&, int);
4965 // T* operator--(T*VQ&, int);
4966 void addPlusPlusMinusMinusPointerOverloads() {
4967 for (BuiltinCandidateTypeSet::iterator
4968 Ptr = CandidateTypes[0].pointer_begin(),
4969 PtrEnd = CandidateTypes[0].pointer_end();
4970 Ptr != PtrEnd; ++Ptr) {
4971 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00004972 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004973 continue;
4974
4975 addPlusPlusMinusMinusStyleOverloads(*Ptr,
4976 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4977 VisibleTypeConversionsQuals.hasVolatile()));
4978 }
4979 }
4980
4981 // C++ [over.built]p6:
4982 // For every cv-qualified or cv-unqualified object type T, there
4983 // exist candidate operator functions of the form
4984 //
4985 // T& operator*(T*);
4986 //
4987 // C++ [over.built]p7:
Douglas Gregor02824322011-01-26 19:30:28 +00004988 // For every function type T that does not have cv-qualifiers or a
4989 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004990 // T& operator*(T*);
4991 void addUnaryStarPointerOverloads() {
4992 for (BuiltinCandidateTypeSet::iterator
4993 Ptr = CandidateTypes[0].pointer_begin(),
4994 PtrEnd = CandidateTypes[0].pointer_end();
4995 Ptr != PtrEnd; ++Ptr) {
4996 QualType ParamTy = *Ptr;
4997 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00004998 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
4999 continue;
5000
Douglas Gregor02824322011-01-26 19:30:28 +00005001 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5002 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5003 continue;
5004
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005005 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5006 &ParamTy, Args, 1, CandidateSet);
5007 }
5008 }
5009
5010 // C++ [over.built]p9:
5011 // For every promoted arithmetic type T, there exist candidate
5012 // operator functions of the form
5013 //
5014 // T operator+(T);
5015 // T operator-(T);
5016 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005017 if (!HasArithmeticOrEnumeralCandidateType)
5018 return;
5019
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005020 for (unsigned Arith = FirstPromotedArithmeticType;
5021 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005022 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005023 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5024 }
5025
5026 // Extension: We also add these operators for vector types.
5027 for (BuiltinCandidateTypeSet::iterator
5028 Vec = CandidateTypes[0].vector_begin(),
5029 VecEnd = CandidateTypes[0].vector_end();
5030 Vec != VecEnd; ++Vec) {
5031 QualType VecTy = *Vec;
5032 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5033 }
5034 }
5035
5036 // C++ [over.built]p8:
5037 // For every type T, there exist candidate operator functions of
5038 // the form
5039 //
5040 // T* operator+(T*);
5041 void addUnaryPlusPointerOverloads() {
5042 for (BuiltinCandidateTypeSet::iterator
5043 Ptr = CandidateTypes[0].pointer_begin(),
5044 PtrEnd = CandidateTypes[0].pointer_end();
5045 Ptr != PtrEnd; ++Ptr) {
5046 QualType ParamTy = *Ptr;
5047 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5048 }
5049 }
5050
5051 // C++ [over.built]p10:
5052 // For every promoted integral type T, there exist candidate
5053 // operator functions of the form
5054 //
5055 // T operator~(T);
5056 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005057 if (!HasArithmeticOrEnumeralCandidateType)
5058 return;
5059
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005060 for (unsigned Int = FirstPromotedIntegralType;
5061 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005062 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005063 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5064 }
5065
5066 // Extension: We also add this operator for vector types.
5067 for (BuiltinCandidateTypeSet::iterator
5068 Vec = CandidateTypes[0].vector_begin(),
5069 VecEnd = CandidateTypes[0].vector_end();
5070 Vec != VecEnd; ++Vec) {
5071 QualType VecTy = *Vec;
5072 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5073 }
5074 }
5075
5076 // C++ [over.match.oper]p16:
5077 // For every pointer to member type T, there exist candidate operator
5078 // functions of the form
5079 //
5080 // bool operator==(T,T);
5081 // bool operator!=(T,T);
5082 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5083 /// Set of (canonical) types that we've already handled.
5084 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5085
5086 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5087 for (BuiltinCandidateTypeSet::iterator
5088 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5089 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5090 MemPtr != MemPtrEnd;
5091 ++MemPtr) {
5092 // Don't add the same builtin candidate twice.
5093 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5094 continue;
5095
5096 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5097 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5098 CandidateSet);
5099 }
5100 }
5101 }
5102
5103 // C++ [over.built]p15:
5104 //
5105 // For every pointer or enumeration type T, there exist
5106 // candidate operator functions of the form
5107 //
5108 // bool operator<(T, T);
5109 // bool operator>(T, T);
5110 // bool operator<=(T, T);
5111 // bool operator>=(T, T);
5112 // bool operator==(T, T);
5113 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005114 void addRelationalPointerOrEnumeralOverloads() {
5115 // C++ [over.built]p1:
5116 // If there is a user-written candidate with the same name and parameter
5117 // types as a built-in candidate operator function, the built-in operator
5118 // function is hidden and is not included in the set of candidate
5119 // functions.
5120 //
5121 // The text is actually in a note, but if we don't implement it then we end
5122 // up with ambiguities when the user provides an overloaded operator for
5123 // an enumeration type. Note that only enumeration types have this problem,
5124 // so we track which enumeration types we've seen operators for. Also, the
5125 // only other overloaded operator with enumeration argumenst, operator=,
5126 // cannot be overloaded for enumeration types, so this is the only place
5127 // where we must suppress candidates like this.
5128 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5129 UserDefinedBinaryOperators;
5130
5131 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5132 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5133 CandidateTypes[ArgIdx].enumeration_end()) {
5134 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5135 CEnd = CandidateSet.end();
5136 C != CEnd; ++C) {
5137 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5138 continue;
5139
5140 QualType FirstParamType =
5141 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5142 QualType SecondParamType =
5143 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5144
5145 // Skip if either parameter isn't of enumeral type.
5146 if (!FirstParamType->isEnumeralType() ||
5147 !SecondParamType->isEnumeralType())
5148 continue;
5149
5150 // Add this operator to the set of known user-defined operators.
5151 UserDefinedBinaryOperators.insert(
5152 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5153 S.Context.getCanonicalType(SecondParamType)));
5154 }
5155 }
5156 }
5157
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005158 /// Set of (canonical) types that we've already handled.
5159 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5160
5161 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5162 for (BuiltinCandidateTypeSet::iterator
5163 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5164 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5165 Ptr != PtrEnd; ++Ptr) {
5166 // Don't add the same builtin candidate twice.
5167 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5168 continue;
5169
5170 QualType ParamTypes[2] = { *Ptr, *Ptr };
5171 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5172 CandidateSet);
5173 }
5174 for (BuiltinCandidateTypeSet::iterator
5175 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5176 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5177 Enum != EnumEnd; ++Enum) {
5178 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5179
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005180 // Don't add the same builtin candidate twice, or if a user defined
5181 // candidate exists.
5182 if (!AddedTypes.insert(CanonType) ||
5183 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5184 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005185 continue;
5186
5187 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005188 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5189 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005190 }
5191 }
5192 }
5193
5194 // C++ [over.built]p13:
5195 //
5196 // For every cv-qualified or cv-unqualified object type T
5197 // there exist candidate operator functions of the form
5198 //
5199 // T* operator+(T*, ptrdiff_t);
5200 // T& operator[](T*, ptrdiff_t); [BELOW]
5201 // T* operator-(T*, ptrdiff_t);
5202 // T* operator+(ptrdiff_t, T*);
5203 // T& operator[](ptrdiff_t, T*); [BELOW]
5204 //
5205 // C++ [over.built]p14:
5206 //
5207 // For every T, where T is a pointer to object type, there
5208 // exist candidate operator functions of the form
5209 //
5210 // ptrdiff_t operator-(T, T);
5211 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5212 /// Set of (canonical) types that we've already handled.
5213 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5214
5215 for (int Arg = 0; Arg < 2; ++Arg) {
5216 QualType AsymetricParamTypes[2] = {
5217 S.Context.getPointerDiffType(),
5218 S.Context.getPointerDiffType(),
5219 };
5220 for (BuiltinCandidateTypeSet::iterator
5221 Ptr = CandidateTypes[Arg].pointer_begin(),
5222 PtrEnd = CandidateTypes[Arg].pointer_end();
5223 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005224 QualType PointeeTy = (*Ptr)->getPointeeType();
5225 if (!PointeeTy->isObjectType())
5226 continue;
5227
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005228 AsymetricParamTypes[Arg] = *Ptr;
5229 if (Arg == 0 || Op == OO_Plus) {
5230 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5231 // T* operator+(ptrdiff_t, T*);
5232 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5233 CandidateSet);
5234 }
5235 if (Op == OO_Minus) {
5236 // ptrdiff_t operator-(T, T);
5237 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5238 continue;
5239
5240 QualType ParamTypes[2] = { *Ptr, *Ptr };
5241 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5242 Args, 2, CandidateSet);
5243 }
5244 }
5245 }
5246 }
5247
5248 // C++ [over.built]p12:
5249 //
5250 // For every pair of promoted arithmetic types L and R, there
5251 // exist candidate operator functions of the form
5252 //
5253 // LR operator*(L, R);
5254 // LR operator/(L, R);
5255 // LR operator+(L, R);
5256 // LR operator-(L, R);
5257 // bool operator<(L, R);
5258 // bool operator>(L, R);
5259 // bool operator<=(L, R);
5260 // bool operator>=(L, R);
5261 // bool operator==(L, R);
5262 // bool operator!=(L, R);
5263 //
5264 // where LR is the result of the usual arithmetic conversions
5265 // between types L and R.
5266 //
5267 // C++ [over.built]p24:
5268 //
5269 // For every pair of promoted arithmetic types L and R, there exist
5270 // candidate operator functions of the form
5271 //
5272 // LR operator?(bool, L, R);
5273 //
5274 // where LR is the result of the usual arithmetic conversions
5275 // between types L and R.
5276 // Our candidates ignore the first parameter.
5277 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005278 if (!HasArithmeticOrEnumeralCandidateType)
5279 return;
5280
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005281 for (unsigned Left = FirstPromotedArithmeticType;
5282 Left < LastPromotedArithmeticType; ++Left) {
5283 for (unsigned Right = FirstPromotedArithmeticType;
5284 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005285 QualType LandR[2] = { getArithmeticType(Left),
5286 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005287 QualType Result =
5288 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005289 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005290 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5291 }
5292 }
5293
5294 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5295 // conditional operator for vector types.
5296 for (BuiltinCandidateTypeSet::iterator
5297 Vec1 = CandidateTypes[0].vector_begin(),
5298 Vec1End = CandidateTypes[0].vector_end();
5299 Vec1 != Vec1End; ++Vec1) {
5300 for (BuiltinCandidateTypeSet::iterator
5301 Vec2 = CandidateTypes[1].vector_begin(),
5302 Vec2End = CandidateTypes[1].vector_end();
5303 Vec2 != Vec2End; ++Vec2) {
5304 QualType LandR[2] = { *Vec1, *Vec2 };
5305 QualType Result = S.Context.BoolTy;
5306 if (!isComparison) {
5307 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5308 Result = *Vec1;
5309 else
5310 Result = *Vec2;
5311 }
5312
5313 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5314 }
5315 }
5316 }
5317
5318 // C++ [over.built]p17:
5319 //
5320 // For every pair of promoted integral types L and R, there
5321 // exist candidate operator functions of the form
5322 //
5323 // LR operator%(L, R);
5324 // LR operator&(L, R);
5325 // LR operator^(L, R);
5326 // LR operator|(L, R);
5327 // L operator<<(L, R);
5328 // L operator>>(L, R);
5329 //
5330 // where LR is the result of the usual arithmetic conversions
5331 // between types L and R.
5332 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005333 if (!HasArithmeticOrEnumeralCandidateType)
5334 return;
5335
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005336 for (unsigned Left = FirstPromotedIntegralType;
5337 Left < LastPromotedIntegralType; ++Left) {
5338 for (unsigned Right = FirstPromotedIntegralType;
5339 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005340 QualType LandR[2] = { getArithmeticType(Left),
5341 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005342 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5343 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005344 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005345 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5346 }
5347 }
5348 }
5349
5350 // C++ [over.built]p20:
5351 //
5352 // For every pair (T, VQ), where T is an enumeration or
5353 // pointer to member type and VQ is either volatile or
5354 // empty, there exist candidate operator functions of the form
5355 //
5356 // VQ T& operator=(VQ T&, T);
5357 void addAssignmentMemberPointerOrEnumeralOverloads() {
5358 /// Set of (canonical) types that we've already handled.
5359 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5360
5361 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5362 for (BuiltinCandidateTypeSet::iterator
5363 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5364 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5365 Enum != EnumEnd; ++Enum) {
5366 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5367 continue;
5368
5369 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5370 CandidateSet);
5371 }
5372
5373 for (BuiltinCandidateTypeSet::iterator
5374 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5375 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5376 MemPtr != MemPtrEnd; ++MemPtr) {
5377 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5378 continue;
5379
5380 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5381 CandidateSet);
5382 }
5383 }
5384 }
5385
5386 // C++ [over.built]p19:
5387 //
5388 // For every pair (T, VQ), where T is any type and VQ is either
5389 // volatile or empty, there exist candidate operator functions
5390 // of the form
5391 //
5392 // T*VQ& operator=(T*VQ&, T*);
5393 //
5394 // C++ [over.built]p21:
5395 //
5396 // For every pair (T, VQ), where T is a cv-qualified or
5397 // cv-unqualified object type and VQ is either volatile or
5398 // empty, there exist candidate operator functions of the form
5399 //
5400 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5401 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5402 void addAssignmentPointerOverloads(bool isEqualOp) {
5403 /// Set of (canonical) types that we've already handled.
5404 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5405
5406 for (BuiltinCandidateTypeSet::iterator
5407 Ptr = CandidateTypes[0].pointer_begin(),
5408 PtrEnd = CandidateTypes[0].pointer_end();
5409 Ptr != PtrEnd; ++Ptr) {
5410 // If this is operator=, keep track of the builtin candidates we added.
5411 if (isEqualOp)
5412 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005413 else if (!(*Ptr)->getPointeeType()->isObjectType())
5414 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005415
5416 // non-volatile version
5417 QualType ParamTypes[2] = {
5418 S.Context.getLValueReferenceType(*Ptr),
5419 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5420 };
5421 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5422 /*IsAssigmentOperator=*/ isEqualOp);
5423
5424 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5425 VisibleTypeConversionsQuals.hasVolatile()) {
5426 // volatile version
5427 ParamTypes[0] =
5428 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5429 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5430 /*IsAssigmentOperator=*/isEqualOp);
5431 }
5432 }
5433
5434 if (isEqualOp) {
5435 for (BuiltinCandidateTypeSet::iterator
5436 Ptr = CandidateTypes[1].pointer_begin(),
5437 PtrEnd = CandidateTypes[1].pointer_end();
5438 Ptr != PtrEnd; ++Ptr) {
5439 // Make sure we don't add the same candidate twice.
5440 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5441 continue;
5442
Chandler Carruth8e543b32010-12-12 08:17:55 +00005443 QualType ParamTypes[2] = {
5444 S.Context.getLValueReferenceType(*Ptr),
5445 *Ptr,
5446 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005447
5448 // non-volatile version
5449 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5450 /*IsAssigmentOperator=*/true);
5451
5452 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5453 VisibleTypeConversionsQuals.hasVolatile()) {
5454 // volatile version
5455 ParamTypes[0] =
5456 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00005457 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5458 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005459 }
5460 }
5461 }
5462 }
5463
5464 // C++ [over.built]p18:
5465 //
5466 // For every triple (L, VQ, R), where L is an arithmetic type,
5467 // VQ is either volatile or empty, and R is a promoted
5468 // arithmetic type, there exist candidate operator functions of
5469 // the form
5470 //
5471 // VQ L& operator=(VQ L&, R);
5472 // VQ L& operator*=(VQ L&, R);
5473 // VQ L& operator/=(VQ L&, R);
5474 // VQ L& operator+=(VQ L&, R);
5475 // VQ L& operator-=(VQ L&, R);
5476 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005477 if (!HasArithmeticOrEnumeralCandidateType)
5478 return;
5479
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005480 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5481 for (unsigned Right = FirstPromotedArithmeticType;
5482 Right < LastPromotedArithmeticType; ++Right) {
5483 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005484 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005485
5486 // Add this built-in operator as a candidate (VQ is empty).
5487 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005488 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005489 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5490 /*IsAssigmentOperator=*/isEqualOp);
5491
5492 // Add this built-in operator as a candidate (VQ is 'volatile').
5493 if (VisibleTypeConversionsQuals.hasVolatile()) {
5494 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005495 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005496 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005497 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5498 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005499 /*IsAssigmentOperator=*/isEqualOp);
5500 }
5501 }
5502 }
5503
5504 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5505 for (BuiltinCandidateTypeSet::iterator
5506 Vec1 = CandidateTypes[0].vector_begin(),
5507 Vec1End = CandidateTypes[0].vector_end();
5508 Vec1 != Vec1End; ++Vec1) {
5509 for (BuiltinCandidateTypeSet::iterator
5510 Vec2 = CandidateTypes[1].vector_begin(),
5511 Vec2End = CandidateTypes[1].vector_end();
5512 Vec2 != Vec2End; ++Vec2) {
5513 QualType ParamTypes[2];
5514 ParamTypes[1] = *Vec2;
5515 // Add this built-in operator as a candidate (VQ is empty).
5516 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5517 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5518 /*IsAssigmentOperator=*/isEqualOp);
5519
5520 // Add this built-in operator as a candidate (VQ is 'volatile').
5521 if (VisibleTypeConversionsQuals.hasVolatile()) {
5522 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5523 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005524 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5525 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005526 /*IsAssigmentOperator=*/isEqualOp);
5527 }
5528 }
5529 }
5530 }
5531
5532 // C++ [over.built]p22:
5533 //
5534 // For every triple (L, VQ, R), where L is an integral type, VQ
5535 // is either volatile or empty, and R is a promoted integral
5536 // type, there exist candidate operator functions of the form
5537 //
5538 // VQ L& operator%=(VQ L&, R);
5539 // VQ L& operator<<=(VQ L&, R);
5540 // VQ L& operator>>=(VQ L&, R);
5541 // VQ L& operator&=(VQ L&, R);
5542 // VQ L& operator^=(VQ L&, R);
5543 // VQ L& operator|=(VQ L&, R);
5544 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005545 if (!HasArithmeticOrEnumeralCandidateType)
5546 return;
5547
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005548 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5549 for (unsigned Right = FirstPromotedIntegralType;
5550 Right < LastPromotedIntegralType; ++Right) {
5551 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005552 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005553
5554 // Add this built-in operator as a candidate (VQ is empty).
5555 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005556 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005557 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5558 if (VisibleTypeConversionsQuals.hasVolatile()) {
5559 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00005560 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005561 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5562 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5563 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5564 CandidateSet);
5565 }
5566 }
5567 }
5568 }
5569
5570 // C++ [over.operator]p23:
5571 //
5572 // There also exist candidate operator functions of the form
5573 //
5574 // bool operator!(bool);
5575 // bool operator&&(bool, bool);
5576 // bool operator||(bool, bool);
5577 void addExclaimOverload() {
5578 QualType ParamTy = S.Context.BoolTy;
5579 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5580 /*IsAssignmentOperator=*/false,
5581 /*NumContextualBoolArguments=*/1);
5582 }
5583 void addAmpAmpOrPipePipeOverload() {
5584 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5585 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5586 /*IsAssignmentOperator=*/false,
5587 /*NumContextualBoolArguments=*/2);
5588 }
5589
5590 // C++ [over.built]p13:
5591 //
5592 // For every cv-qualified or cv-unqualified object type T there
5593 // exist candidate operator functions of the form
5594 //
5595 // T* operator+(T*, ptrdiff_t); [ABOVE]
5596 // T& operator[](T*, ptrdiff_t);
5597 // T* operator-(T*, ptrdiff_t); [ABOVE]
5598 // T* operator+(ptrdiff_t, T*); [ABOVE]
5599 // T& operator[](ptrdiff_t, T*);
5600 void addSubscriptOverloads() {
5601 for (BuiltinCandidateTypeSet::iterator
5602 Ptr = CandidateTypes[0].pointer_begin(),
5603 PtrEnd = CandidateTypes[0].pointer_end();
5604 Ptr != PtrEnd; ++Ptr) {
5605 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5606 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005607 if (!PointeeType->isObjectType())
5608 continue;
5609
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005610 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5611
5612 // T& operator[](T*, ptrdiff_t)
5613 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5614 }
5615
5616 for (BuiltinCandidateTypeSet::iterator
5617 Ptr = CandidateTypes[1].pointer_begin(),
5618 PtrEnd = CandidateTypes[1].pointer_end();
5619 Ptr != PtrEnd; ++Ptr) {
5620 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5621 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005622 if (!PointeeType->isObjectType())
5623 continue;
5624
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005625 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5626
5627 // T& operator[](ptrdiff_t, T*)
5628 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5629 }
5630 }
5631
5632 // C++ [over.built]p11:
5633 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5634 // C1 is the same type as C2 or is a derived class of C2, T is an object
5635 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5636 // there exist candidate operator functions of the form
5637 //
5638 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5639 //
5640 // where CV12 is the union of CV1 and CV2.
5641 void addArrowStarOverloads() {
5642 for (BuiltinCandidateTypeSet::iterator
5643 Ptr = CandidateTypes[0].pointer_begin(),
5644 PtrEnd = CandidateTypes[0].pointer_end();
5645 Ptr != PtrEnd; ++Ptr) {
5646 QualType C1Ty = (*Ptr);
5647 QualType C1;
5648 QualifierCollector Q1;
5649 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5650 if (!isa<RecordType>(C1))
5651 continue;
5652 // heuristic to reduce number of builtin candidates in the set.
5653 // Add volatile/restrict version only if there are conversions to a
5654 // volatile/restrict type.
5655 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5656 continue;
5657 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5658 continue;
5659 for (BuiltinCandidateTypeSet::iterator
5660 MemPtr = CandidateTypes[1].member_pointer_begin(),
5661 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5662 MemPtr != MemPtrEnd; ++MemPtr) {
5663 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5664 QualType C2 = QualType(mptr->getClass(), 0);
5665 C2 = C2.getUnqualifiedType();
5666 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5667 break;
5668 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5669 // build CV12 T&
5670 QualType T = mptr->getPointeeType();
5671 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5672 T.isVolatileQualified())
5673 continue;
5674 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5675 T.isRestrictQualified())
5676 continue;
5677 T = Q1.apply(S.Context, T);
5678 QualType ResultTy = S.Context.getLValueReferenceType(T);
5679 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5680 }
5681 }
5682 }
5683
5684 // Note that we don't consider the first argument, since it has been
5685 // contextually converted to bool long ago. The candidates below are
5686 // therefore added as binary.
5687 //
5688 // C++ [over.built]p25:
5689 // For every type T, where T is a pointer, pointer-to-member, or scoped
5690 // enumeration type, there exist candidate operator functions of the form
5691 //
5692 // T operator?(bool, T, T);
5693 //
5694 void addConditionalOperatorOverloads() {
5695 /// Set of (canonical) types that we've already handled.
5696 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5697
5698 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5699 for (BuiltinCandidateTypeSet::iterator
5700 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5701 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5702 Ptr != PtrEnd; ++Ptr) {
5703 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5704 continue;
5705
5706 QualType ParamTypes[2] = { *Ptr, *Ptr };
5707 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5708 }
5709
5710 for (BuiltinCandidateTypeSet::iterator
5711 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5712 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5713 MemPtr != MemPtrEnd; ++MemPtr) {
5714 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5715 continue;
5716
5717 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5718 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5719 }
5720
5721 if (S.getLangOptions().CPlusPlus0x) {
5722 for (BuiltinCandidateTypeSet::iterator
5723 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5724 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5725 Enum != EnumEnd; ++Enum) {
5726 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5727 continue;
5728
5729 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5730 continue;
5731
5732 QualType ParamTypes[2] = { *Enum, *Enum };
5733 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5734 }
5735 }
5736 }
5737 }
5738};
5739
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005740} // end anonymous namespace
5741
5742/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5743/// operator overloads to the candidate set (C++ [over.built]), based
5744/// on the operator @p Op and the arguments given. For example, if the
5745/// operator is a binary '+', this routine might add "int
5746/// operator+(int, int)" to cover integer addition.
5747void
5748Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5749 SourceLocation OpLoc,
5750 Expr **Args, unsigned NumArgs,
5751 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005752 // Find all of the types that the arguments can convert to, but only
5753 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00005754 // that make use of these types. Also record whether we encounter non-record
5755 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005756 Qualifiers VisibleTypeConversionsQuals;
5757 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005758 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5759 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00005760
5761 bool HasNonRecordCandidateType = false;
5762 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005763 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5764 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5765 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5766 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5767 OpLoc,
5768 true,
5769 (Op == OO_Exclaim ||
5770 Op == OO_AmpAmp ||
5771 Op == OO_PipePipe),
5772 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00005773 HasNonRecordCandidateType = HasNonRecordCandidateType ||
5774 CandidateTypes[ArgIdx].hasNonRecordTypes();
5775 HasArithmeticOrEnumeralCandidateType =
5776 HasArithmeticOrEnumeralCandidateType ||
5777 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005778 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005779
Chandler Carruth00a38332010-12-13 01:44:01 +00005780 // Exit early when no non-record types have been added to the candidate set
5781 // for any of the arguments to the operator.
5782 if (!HasNonRecordCandidateType)
5783 return;
5784
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005785 // Setup an object to manage the common state for building overloads.
5786 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
5787 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005788 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005789 CandidateTypes, CandidateSet);
5790
5791 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00005792 switch (Op) {
5793 case OO_None:
5794 case NUM_OVERLOADED_OPERATORS:
5795 assert(false && "Expected an overloaded operator");
5796 break;
5797
Chandler Carruth5184de02010-12-12 08:51:33 +00005798 case OO_New:
5799 case OO_Delete:
5800 case OO_Array_New:
5801 case OO_Array_Delete:
5802 case OO_Call:
5803 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
5804 break;
5805
5806 case OO_Comma:
5807 case OO_Arrow:
5808 // C++ [over.match.oper]p3:
5809 // -- For the operator ',', the unary operator '&', or the
5810 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00005811 break;
5812
5813 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00005814 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005815 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00005816 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00005817
5818 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00005819 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005820 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00005821 } else {
5822 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
5823 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5824 }
Douglas Gregord08452f2008-11-19 15:42:04 +00005825 break;
5826
Chandler Carruth5184de02010-12-12 08:51:33 +00005827 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00005828 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00005829 OpBuilder.addUnaryStarPointerOverloads();
5830 else
5831 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5832 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005833
Chandler Carruth5184de02010-12-12 08:51:33 +00005834 case OO_Slash:
5835 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00005836 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005837
5838 case OO_PlusPlus:
5839 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005840 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
5841 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00005842 break;
5843
Douglas Gregor84605ae2009-08-24 13:43:27 +00005844 case OO_EqualEqual:
5845 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005846 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00005847 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00005848
Douglas Gregora11693b2008-11-12 17:17:38 +00005849 case OO_Less:
5850 case OO_Greater:
5851 case OO_LessEqual:
5852 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005853 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00005854 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
5855 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005856
Douglas Gregora11693b2008-11-12 17:17:38 +00005857 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00005858 case OO_Caret:
5859 case OO_Pipe:
5860 case OO_LessLess:
5861 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005862 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00005863 break;
5864
Chandler Carruth5184de02010-12-12 08:51:33 +00005865 case OO_Amp: // '&' is either unary or binary
5866 if (NumArgs == 1)
5867 // C++ [over.match.oper]p3:
5868 // -- For the operator ',', the unary operator '&', or the
5869 // operator '->', the built-in candidates set is empty.
5870 break;
5871
5872 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
5873 break;
5874
5875 case OO_Tilde:
5876 OpBuilder.addUnaryTildePromotedIntegralOverloads();
5877 break;
5878
Douglas Gregora11693b2008-11-12 17:17:38 +00005879 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005880 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005881 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00005882
5883 case OO_PlusEqual:
5884 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005885 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005886 // Fall through.
5887
5888 case OO_StarEqual:
5889 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005890 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005891 break;
5892
5893 case OO_PercentEqual:
5894 case OO_LessLessEqual:
5895 case OO_GreaterGreaterEqual:
5896 case OO_AmpEqual:
5897 case OO_CaretEqual:
5898 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005899 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005900 break;
5901
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005902 case OO_Exclaim:
5903 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00005904 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005905
Douglas Gregora11693b2008-11-12 17:17:38 +00005906 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005907 case OO_PipePipe:
5908 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00005909 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005910
5911 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005912 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005913 break;
5914
5915 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005916 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005917 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005918
5919 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005920 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00005921 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5922 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005923 }
5924}
5925
Douglas Gregore254f902009-02-04 00:32:51 +00005926/// \brief Add function candidates found via argument-dependent lookup
5927/// to the set of overloading candidates.
5928///
5929/// This routine performs argument-dependent name lookup based on the
5930/// given function name (which may also be an operator name) and adds
5931/// all of the overload candidates found by ADL to the overload
5932/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005933void
Douglas Gregore254f902009-02-04 00:32:51 +00005934Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005935 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005936 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005937 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005938 OverloadCandidateSet& CandidateSet,
5939 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005940 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005941
John McCall91f61fc2010-01-26 06:04:06 +00005942 // FIXME: This approach for uniquing ADL results (and removing
5943 // redundant candidates from the set) relies on pointer-equality,
5944 // which means we need to key off the canonical decl. However,
5945 // always going back to the canonical decl might not get us the
5946 // right set of default arguments. What default arguments are
5947 // we supposed to consider on ADL candidates, anyway?
5948
Douglas Gregorcabea402009-09-22 15:41:20 +00005949 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005950 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005951
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005952 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005953 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5954 CandEnd = CandidateSet.end();
5955 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005956 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005957 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005958 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005959 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005960 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005961
5962 // For each of the ADL candidates we found, add it to the overload
5963 // set.
John McCall8fe68082010-01-26 07:16:45 +00005964 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005965 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005966 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005967 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005968 continue;
5969
John McCalla0296f72010-03-19 07:35:19 +00005970 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005971 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005972 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005973 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005974 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005975 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005976 }
Douglas Gregore254f902009-02-04 00:32:51 +00005977}
5978
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005979/// isBetterOverloadCandidate - Determines whether the first overload
5980/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005981bool
John McCall5c32be02010-08-24 20:38:10 +00005982isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00005983 const OverloadCandidate &Cand1,
5984 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005985 SourceLocation Loc,
5986 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005987 // Define viable functions to be better candidates than non-viable
5988 // functions.
5989 if (!Cand2.Viable)
5990 return Cand1.Viable;
5991 else if (!Cand1.Viable)
5992 return false;
5993
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005994 // C++ [over.match.best]p1:
5995 //
5996 // -- if F is a static member function, ICS1(F) is defined such
5997 // that ICS1(F) is neither better nor worse than ICS1(G) for
5998 // any function G, and, symmetrically, ICS1(G) is neither
5999 // better nor worse than ICS1(F).
6000 unsigned StartArg = 0;
6001 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6002 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006003
Douglas Gregord3cb3562009-07-07 23:38:56 +00006004 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006005 // A viable function F1 is defined to be a better function than another
6006 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006007 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006008 unsigned NumArgs = Cand1.Conversions.size();
6009 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6010 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006011 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006012 switch (CompareImplicitConversionSequences(S,
6013 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006014 Cand2.Conversions[ArgIdx])) {
6015 case ImplicitConversionSequence::Better:
6016 // Cand1 has a better conversion sequence.
6017 HasBetterConversion = true;
6018 break;
6019
6020 case ImplicitConversionSequence::Worse:
6021 // Cand1 can't be better than Cand2.
6022 return false;
6023
6024 case ImplicitConversionSequence::Indistinguishable:
6025 // Do nothing.
6026 break;
6027 }
6028 }
6029
Mike Stump11289f42009-09-09 15:08:12 +00006030 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006031 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006032 if (HasBetterConversion)
6033 return true;
6034
Mike Stump11289f42009-09-09 15:08:12 +00006035 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006036 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006037 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006038 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6039 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006040
6041 // -- F1 and F2 are function template specializations, and the function
6042 // template for F1 is more specialized than the template for F2
6043 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006044 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006045 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006046 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006047 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006048 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6049 Cand2.Function->getPrimaryTemplate(),
6050 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00006051 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006052 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006053 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006054 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006055 }
6056
Douglas Gregora1f013e2008-11-07 22:36:19 +00006057 // -- the context is an initialization by user-defined conversion
6058 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6059 // from the return type of F1 to the destination type (i.e.,
6060 // the type of the entity being initialized) is a better
6061 // conversion sequence than the standard conversion sequence
6062 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006063 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006064 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006065 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006066 switch (CompareStandardConversionSequences(S,
6067 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006068 Cand2.FinalConversion)) {
6069 case ImplicitConversionSequence::Better:
6070 // Cand1 has a better conversion sequence.
6071 return true;
6072
6073 case ImplicitConversionSequence::Worse:
6074 // Cand1 can't be better than Cand2.
6075 return false;
6076
6077 case ImplicitConversionSequence::Indistinguishable:
6078 // Do nothing
6079 break;
6080 }
6081 }
6082
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006083 return false;
6084}
6085
Mike Stump11289f42009-09-09 15:08:12 +00006086/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006087/// within an overload candidate set.
6088///
6089/// \param CandidateSet the set of candidate functions.
6090///
6091/// \param Loc the location of the function name (or operator symbol) for
6092/// which overload resolution occurs.
6093///
Mike Stump11289f42009-09-09 15:08:12 +00006094/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006095/// function, Best points to the candidate function found.
6096///
6097/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006098OverloadingResult
6099OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006100 iterator &Best,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006101 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006102 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006103 Best = end();
6104 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6105 if (Cand->Viable)
Douglas Gregord5b730c92010-09-12 08:07:23 +00006106 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
6107 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006108 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006109 }
6110
6111 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006112 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006113 return OR_No_Viable_Function;
6114
6115 // Make sure that this function is better than every other viable
6116 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006117 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006118 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006119 Cand != Best &&
Douglas Gregord5b730c92010-09-12 08:07:23 +00006120 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
6121 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006122 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006123 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006124 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006125 }
Mike Stump11289f42009-09-09 15:08:12 +00006126
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006127 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006128 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006129 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00006130 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006131 return OR_Deleted;
6132
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006133 // C++ [basic.def.odr]p2:
6134 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00006135 // when referred to from a potentially-evaluated expression. [Note: this
6136 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006137 // (clause 13), user-defined conversions (12.3.2), allocation function for
6138 // placement new (5.3.4), as well as non-default initialization (8.5).
6139 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00006140 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006141
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006142 return OR_Success;
6143}
6144
John McCall53262c92010-01-12 02:15:36 +00006145namespace {
6146
6147enum OverloadCandidateKind {
6148 oc_function,
6149 oc_method,
6150 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006151 oc_function_template,
6152 oc_method_template,
6153 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006154 oc_implicit_default_constructor,
6155 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006156 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00006157};
6158
John McCalle1ac8d12010-01-13 00:25:19 +00006159OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6160 FunctionDecl *Fn,
6161 std::string &Description) {
6162 bool isTemplate = false;
6163
6164 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6165 isTemplate = true;
6166 Description = S.getTemplateArgumentBindingsText(
6167 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6168 }
John McCallfd0b2f82010-01-06 09:43:14 +00006169
6170 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006171 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006172 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006173
John McCall53262c92010-01-12 02:15:36 +00006174 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6175 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006176 }
6177
6178 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6179 // This actually gets spelled 'candidate function' for now, but
6180 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006181 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006182 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006183
Douglas Gregorec3bec02010-09-27 22:37:28 +00006184 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006185 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006186 return oc_implicit_copy_assignment;
6187 }
6188
John McCalle1ac8d12010-01-13 00:25:19 +00006189 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006190}
6191
6192} // end anonymous namespace
6193
6194// Notes the location of an overload candidate.
6195void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006196 std::string FnDesc;
6197 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6198 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6199 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00006200}
6201
John McCall0d1da222010-01-12 00:44:57 +00006202/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6203/// "lead" diagnostic; it will be given two arguments, the source and
6204/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006205void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6206 Sema &S,
6207 SourceLocation CaretLoc,
6208 const PartialDiagnostic &PDiag) const {
6209 S.Diag(CaretLoc, PDiag)
6210 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006211 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006212 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6213 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006214 }
John McCall12f97bc2010-01-08 04:41:39 +00006215}
6216
John McCall0d1da222010-01-12 00:44:57 +00006217namespace {
6218
John McCall6a61b522010-01-13 09:16:55 +00006219void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6220 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6221 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006222 assert(Cand->Function && "for now, candidate must be a function");
6223 FunctionDecl *Fn = Cand->Function;
6224
6225 // There's a conversion slot for the object argument if this is a
6226 // non-constructor method. Note that 'I' corresponds the
6227 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006228 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006229 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006230 if (I == 0)
6231 isObjectArgument = true;
6232 else
6233 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006234 }
6235
John McCalle1ac8d12010-01-13 00:25:19 +00006236 std::string FnDesc;
6237 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6238
John McCall6a61b522010-01-13 09:16:55 +00006239 Expr *FromExpr = Conv.Bad.FromExpr;
6240 QualType FromTy = Conv.Bad.getFromType();
6241 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006242
John McCallfb7ad0f2010-02-02 02:42:52 +00006243 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006244 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006245 Expr *E = FromExpr->IgnoreParens();
6246 if (isa<UnaryOperator>(E))
6247 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006248 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006249
6250 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6251 << (unsigned) FnKind << FnDesc
6252 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6253 << ToTy << Name << I+1;
6254 return;
6255 }
6256
John McCall6d174642010-01-23 08:10:49 +00006257 // Do some hand-waving analysis to see if the non-viability is due
6258 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006259 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6260 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6261 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6262 CToTy = RT->getPointeeType();
6263 else {
6264 // TODO: detect and diagnose the full richness of const mismatches.
6265 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6266 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6267 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6268 }
6269
6270 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6271 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6272 // It is dumb that we have to do this here.
6273 while (isa<ArrayType>(CFromTy))
6274 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6275 while (isa<ArrayType>(CToTy))
6276 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6277
6278 Qualifiers FromQs = CFromTy.getQualifiers();
6279 Qualifiers ToQs = CToTy.getQualifiers();
6280
6281 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6282 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6283 << (unsigned) FnKind << FnDesc
6284 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6285 << FromTy
6286 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6287 << (unsigned) isObjectArgument << I+1;
6288 return;
6289 }
6290
6291 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6292 assert(CVR && "unexpected qualifiers mismatch");
6293
6294 if (isObjectArgument) {
6295 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6296 << (unsigned) FnKind << FnDesc
6297 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6298 << FromTy << (CVR - 1);
6299 } else {
6300 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6301 << (unsigned) FnKind << FnDesc
6302 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6303 << FromTy << (CVR - 1) << I+1;
6304 }
6305 return;
6306 }
6307
John McCall6d174642010-01-23 08:10:49 +00006308 // Diagnose references or pointers to incomplete types differently,
6309 // since it's far from impossible that the incompleteness triggered
6310 // the failure.
6311 QualType TempFromTy = FromTy.getNonReferenceType();
6312 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6313 TempFromTy = PTy->getPointeeType();
6314 if (TempFromTy->isIncompleteType()) {
6315 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6316 << (unsigned) FnKind << FnDesc
6317 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6318 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6319 return;
6320 }
6321
Douglas Gregor56f2e342010-06-30 23:01:39 +00006322 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006323 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006324 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6325 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6326 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6327 FromPtrTy->getPointeeType()) &&
6328 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6329 !ToPtrTy->getPointeeType()->isIncompleteType() &&
6330 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
6331 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006332 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006333 }
6334 } else if (const ObjCObjectPointerType *FromPtrTy
6335 = FromTy->getAs<ObjCObjectPointerType>()) {
6336 if (const ObjCObjectPointerType *ToPtrTy
6337 = ToTy->getAs<ObjCObjectPointerType>())
6338 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6339 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6340 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6341 FromPtrTy->getPointeeType()) &&
6342 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006343 BaseToDerivedConversion = 2;
6344 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6345 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6346 !FromTy->isIncompleteType() &&
6347 !ToRefTy->getPointeeType()->isIncompleteType() &&
6348 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6349 BaseToDerivedConversion = 3;
6350 }
6351
6352 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00006353 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006354 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006355 << (unsigned) FnKind << FnDesc
6356 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006357 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006358 << FromTy << ToTy << I+1;
6359 return;
6360 }
6361
John McCall47000992010-01-14 03:28:57 +00006362 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006363 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6364 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006365 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006366 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00006367}
6368
6369void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6370 unsigned NumFormalArgs) {
6371 // TODO: treat calls to a missing default constructor as a special case
6372
6373 FunctionDecl *Fn = Cand->Function;
6374 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6375
6376 unsigned MinParams = Fn->getMinRequiredArguments();
6377
6378 // at least / at most / exactly
6379 unsigned mode, modeCount;
6380 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006381 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6382 (Cand->FailureKind == ovl_fail_bad_deduction &&
6383 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
Douglas Gregor7825bf32011-01-06 22:09:01 +00006384 if (MinParams != FnTy->getNumArgs() ||
6385 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00006386 mode = 0; // "at least"
6387 else
6388 mode = 2; // "exactly"
6389 modeCount = MinParams;
6390 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006391 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6392 (Cand->FailureKind == ovl_fail_bad_deduction &&
6393 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006394 if (MinParams != FnTy->getNumArgs())
6395 mode = 1; // "at most"
6396 else
6397 mode = 2; // "exactly"
6398 modeCount = FnTy->getNumArgs();
6399 }
6400
6401 std::string Description;
6402 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6403
6404 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00006405 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6406 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00006407}
6408
John McCall8b9ed552010-02-01 18:53:26 +00006409/// Diagnose a failed template-argument deduction.
6410void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6411 Expr **Args, unsigned NumArgs) {
6412 FunctionDecl *Fn = Cand->Function; // pattern
6413
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006414 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006415 NamedDecl *ParamD;
6416 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6417 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6418 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006419 switch (Cand->DeductionFailure.Result) {
6420 case Sema::TDK_Success:
6421 llvm_unreachable("TDK_success while diagnosing bad deduction");
6422
6423 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006424 assert(ParamD && "no parameter found for incomplete deduction result");
6425 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6426 << ParamD->getDeclName();
6427 return;
6428 }
6429
John McCall42d7d192010-08-05 09:05:08 +00006430 case Sema::TDK_Underqualified: {
6431 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6432 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6433
6434 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6435
6436 // Param will have been canonicalized, but it should just be a
6437 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00006438 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00006439 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00006440 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00006441 assert(S.Context.hasSameType(Param, NonCanonParam));
6442
6443 // Arg has also been canonicalized, but there's nothing we can do
6444 // about that. It also doesn't matter as much, because it won't
6445 // have any template parameters in it (because deduction isn't
6446 // done on dependent types).
6447 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6448
6449 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6450 << ParamD->getDeclName() << Arg << NonCanonParam;
6451 return;
6452 }
6453
6454 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00006455 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006456 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006457 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006458 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006459 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006460 which = 1;
6461 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006462 which = 2;
6463 }
6464
6465 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6466 << which << ParamD->getDeclName()
6467 << *Cand->DeductionFailure.getFirstArg()
6468 << *Cand->DeductionFailure.getSecondArg();
6469 return;
6470 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006471
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006472 case Sema::TDK_InvalidExplicitArguments:
6473 assert(ParamD && "no parameter found for invalid explicit arguments");
6474 if (ParamD->getDeclName())
6475 S.Diag(Fn->getLocation(),
6476 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6477 << ParamD->getDeclName();
6478 else {
6479 int index = 0;
6480 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6481 index = TTP->getIndex();
6482 else if (NonTypeTemplateParmDecl *NTTP
6483 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6484 index = NTTP->getIndex();
6485 else
6486 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6487 S.Diag(Fn->getLocation(),
6488 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6489 << (index + 1);
6490 }
6491 return;
6492
Douglas Gregor02eb4832010-05-08 18:13:28 +00006493 case Sema::TDK_TooManyArguments:
6494 case Sema::TDK_TooFewArguments:
6495 DiagnoseArityMismatch(S, Cand, NumArgs);
6496 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006497
6498 case Sema::TDK_InstantiationDepth:
6499 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6500 return;
6501
6502 case Sema::TDK_SubstitutionFailure: {
6503 std::string ArgString;
6504 if (TemplateArgumentList *Args
6505 = Cand->DeductionFailure.getTemplateArgumentList())
6506 ArgString = S.getTemplateArgumentBindingsText(
6507 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6508 *Args);
6509 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6510 << ArgString;
6511 return;
6512 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006513
John McCall8b9ed552010-02-01 18:53:26 +00006514 // TODO: diagnose these individually, then kill off
6515 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006516 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006517 case Sema::TDK_FailedOverloadResolution:
6518 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6519 return;
6520 }
6521}
6522
6523/// Generates a 'note' diagnostic for an overload candidate. We've
6524/// already generated a primary error at the call site.
6525///
6526/// It really does need to be a single diagnostic with its caret
6527/// pointed at the candidate declaration. Yes, this creates some
6528/// major challenges of technical writing. Yes, this makes pointing
6529/// out problems with specific arguments quite awkward. It's still
6530/// better than generating twenty screens of text for every failed
6531/// overload.
6532///
6533/// It would be great to be able to express per-candidate problems
6534/// more richly for those diagnostic clients that cared, but we'd
6535/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006536void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6537 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006538 FunctionDecl *Fn = Cand->Function;
6539
John McCall12f97bc2010-01-08 04:41:39 +00006540 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00006541 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006542 std::string FnDesc;
6543 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006544
6545 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006546 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00006547 return;
John McCall12f97bc2010-01-08 04:41:39 +00006548 }
6549
John McCalle1ac8d12010-01-13 00:25:19 +00006550 // We don't really have anything else to say about viable candidates.
6551 if (Cand->Viable) {
6552 S.NoteOverloadCandidate(Fn);
6553 return;
6554 }
John McCall0d1da222010-01-12 00:44:57 +00006555
John McCall6a61b522010-01-13 09:16:55 +00006556 switch (Cand->FailureKind) {
6557 case ovl_fail_too_many_arguments:
6558 case ovl_fail_too_few_arguments:
6559 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006560
John McCall6a61b522010-01-13 09:16:55 +00006561 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006562 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6563
John McCallfe796dd2010-01-23 05:17:32 +00006564 case ovl_fail_trivial_conversion:
6565 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006566 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006567 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006568
John McCall65eb8792010-02-25 01:37:24 +00006569 case ovl_fail_bad_conversion: {
6570 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6571 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006572 if (Cand->Conversions[I].isBad())
6573 return DiagnoseBadConversion(S, Cand, I);
6574
6575 // FIXME: this currently happens when we're called from SemaInit
6576 // when user-conversion overload fails. Figure out how to handle
6577 // those conditions and diagnose them well.
6578 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006579 }
John McCall65eb8792010-02-25 01:37:24 +00006580 }
John McCalld3224162010-01-08 00:58:21 +00006581}
6582
6583void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6584 // Desugar the type of the surrogate down to a function type,
6585 // retaining as many typedefs as possible while still showing
6586 // the function type (and, therefore, its parameter types).
6587 QualType FnType = Cand->Surrogate->getConversionType();
6588 bool isLValueReference = false;
6589 bool isRValueReference = false;
6590 bool isPointer = false;
6591 if (const LValueReferenceType *FnTypeRef =
6592 FnType->getAs<LValueReferenceType>()) {
6593 FnType = FnTypeRef->getPointeeType();
6594 isLValueReference = true;
6595 } else if (const RValueReferenceType *FnTypeRef =
6596 FnType->getAs<RValueReferenceType>()) {
6597 FnType = FnTypeRef->getPointeeType();
6598 isRValueReference = true;
6599 }
6600 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6601 FnType = FnTypePtr->getPointeeType();
6602 isPointer = true;
6603 }
6604 // Desugar down to a function type.
6605 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6606 // Reconstruct the pointer/reference as appropriate.
6607 if (isPointer) FnType = S.Context.getPointerType(FnType);
6608 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6609 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6610
6611 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6612 << FnType;
6613}
6614
6615void NoteBuiltinOperatorCandidate(Sema &S,
6616 const char *Opc,
6617 SourceLocation OpLoc,
6618 OverloadCandidate *Cand) {
6619 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6620 std::string TypeStr("operator");
6621 TypeStr += Opc;
6622 TypeStr += "(";
6623 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6624 if (Cand->Conversions.size() == 1) {
6625 TypeStr += ")";
6626 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6627 } else {
6628 TypeStr += ", ";
6629 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6630 TypeStr += ")";
6631 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6632 }
6633}
6634
6635void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6636 OverloadCandidate *Cand) {
6637 unsigned NoOperands = Cand->Conversions.size();
6638 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6639 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006640 if (ICS.isBad()) break; // all meaningless after first invalid
6641 if (!ICS.isAmbiguous()) continue;
6642
John McCall5c32be02010-08-24 20:38:10 +00006643 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006644 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006645 }
6646}
6647
John McCall3712d9e2010-01-15 23:32:50 +00006648SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6649 if (Cand->Function)
6650 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006651 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006652 return Cand->Surrogate->getLocation();
6653 return SourceLocation();
6654}
6655
John McCallad2587a2010-01-12 00:48:53 +00006656struct CompareOverloadCandidatesForDisplay {
6657 Sema &S;
6658 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006659
6660 bool operator()(const OverloadCandidate *L,
6661 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006662 // Fast-path this check.
6663 if (L == R) return false;
6664
John McCall12f97bc2010-01-08 04:41:39 +00006665 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006666 if (L->Viable) {
6667 if (!R->Viable) return true;
6668
6669 // TODO: introduce a tri-valued comparison for overload
6670 // candidates. Would be more worthwhile if we had a sort
6671 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006672 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6673 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006674 } else if (R->Viable)
6675 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006676
John McCall3712d9e2010-01-15 23:32:50 +00006677 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006678
John McCall3712d9e2010-01-15 23:32:50 +00006679 // Criteria by which we can sort non-viable candidates:
6680 if (!L->Viable) {
6681 // 1. Arity mismatches come after other candidates.
6682 if (L->FailureKind == ovl_fail_too_many_arguments ||
6683 L->FailureKind == ovl_fail_too_few_arguments)
6684 return false;
6685 if (R->FailureKind == ovl_fail_too_many_arguments ||
6686 R->FailureKind == ovl_fail_too_few_arguments)
6687 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006688
John McCallfe796dd2010-01-23 05:17:32 +00006689 // 2. Bad conversions come first and are ordered by the number
6690 // of bad conversions and quality of good conversions.
6691 if (L->FailureKind == ovl_fail_bad_conversion) {
6692 if (R->FailureKind != ovl_fail_bad_conversion)
6693 return true;
6694
6695 // If there's any ordering between the defined conversions...
6696 // FIXME: this might not be transitive.
6697 assert(L->Conversions.size() == R->Conversions.size());
6698
6699 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006700 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6701 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006702 switch (CompareImplicitConversionSequences(S,
6703 L->Conversions[I],
6704 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006705 case ImplicitConversionSequence::Better:
6706 leftBetter++;
6707 break;
6708
6709 case ImplicitConversionSequence::Worse:
6710 leftBetter--;
6711 break;
6712
6713 case ImplicitConversionSequence::Indistinguishable:
6714 break;
6715 }
6716 }
6717 if (leftBetter > 0) return true;
6718 if (leftBetter < 0) return false;
6719
6720 } else if (R->FailureKind == ovl_fail_bad_conversion)
6721 return false;
6722
John McCall3712d9e2010-01-15 23:32:50 +00006723 // TODO: others?
6724 }
6725
6726 // Sort everything else by location.
6727 SourceLocation LLoc = GetLocationForCandidate(L);
6728 SourceLocation RLoc = GetLocationForCandidate(R);
6729
6730 // Put candidates without locations (e.g. builtins) at the end.
6731 if (LLoc.isInvalid()) return false;
6732 if (RLoc.isInvalid()) return true;
6733
6734 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006735 }
6736};
6737
John McCallfe796dd2010-01-23 05:17:32 +00006738/// CompleteNonViableCandidate - Normally, overload resolution only
6739/// computes up to the first
6740void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6741 Expr **Args, unsigned NumArgs) {
6742 assert(!Cand->Viable);
6743
6744 // Don't do anything on failures other than bad conversion.
6745 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6746
6747 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006748 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006749 unsigned ConvCount = Cand->Conversions.size();
6750 while (true) {
6751 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6752 ConvIdx++;
6753 if (Cand->Conversions[ConvIdx - 1].isBad())
6754 break;
6755 }
6756
6757 if (ConvIdx == ConvCount)
6758 return;
6759
John McCall65eb8792010-02-25 01:37:24 +00006760 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6761 "remaining conversion is initialized?");
6762
Douglas Gregoradc7a702010-04-16 17:45:54 +00006763 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006764 // operation somehow.
6765 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006766
6767 const FunctionProtoType* Proto;
6768 unsigned ArgIdx = ConvIdx;
6769
6770 if (Cand->IsSurrogate) {
6771 QualType ConvType
6772 = Cand->Surrogate->getConversionType().getNonReferenceType();
6773 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6774 ConvType = ConvPtrType->getPointeeType();
6775 Proto = ConvType->getAs<FunctionProtoType>();
6776 ArgIdx--;
6777 } else if (Cand->Function) {
6778 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6779 if (isa<CXXMethodDecl>(Cand->Function) &&
6780 !isa<CXXConstructorDecl>(Cand->Function))
6781 ArgIdx--;
6782 } else {
6783 // Builtin binary operator with a bad first conversion.
6784 assert(ConvCount <= 3);
6785 for (; ConvIdx != ConvCount; ++ConvIdx)
6786 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006787 = TryCopyInitialization(S, Args[ConvIdx],
6788 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6789 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006790 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006791 return;
6792 }
6793
6794 // Fill in the rest of the conversions.
6795 unsigned NumArgsInProto = Proto->getNumArgs();
6796 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6797 if (ArgIdx < NumArgsInProto)
6798 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006799 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6800 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006801 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006802 else
6803 Cand->Conversions[ConvIdx].setEllipsis();
6804 }
6805}
6806
John McCalld3224162010-01-08 00:58:21 +00006807} // end anonymous namespace
6808
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006809/// PrintOverloadCandidates - When overload resolution fails, prints
6810/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006811/// set.
John McCall5c32be02010-08-24 20:38:10 +00006812void OverloadCandidateSet::NoteCandidates(Sema &S,
6813 OverloadCandidateDisplayKind OCD,
6814 Expr **Args, unsigned NumArgs,
6815 const char *Opc,
6816 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006817 // Sort the candidates by viability and position. Sorting directly would
6818 // be prohibitive, so we make a set of pointers and sort those.
6819 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00006820 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6821 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00006822 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006823 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006824 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00006825 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006826 if (Cand->Function || Cand->IsSurrogate)
6827 Cands.push_back(Cand);
6828 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6829 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006830 }
6831 }
6832
John McCallad2587a2010-01-12 00:48:53 +00006833 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00006834 CompareOverloadCandidatesForDisplay(S));
John McCall12f97bc2010-01-08 04:41:39 +00006835
John McCall0d1da222010-01-12 00:44:57 +00006836 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006837
John McCall12f97bc2010-01-08 04:41:39 +00006838 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00006839 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006840 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006841 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6842 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006843
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006844 // Set an arbitrary limit on the number of candidate functions we'll spam
6845 // the user with. FIXME: This limit should depend on details of the
6846 // candidate list.
6847 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6848 break;
6849 }
6850 ++CandsShown;
6851
John McCalld3224162010-01-08 00:58:21 +00006852 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00006853 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006854 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00006855 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006856 else {
6857 assert(Cand->Viable &&
6858 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006859 // Generally we only see ambiguities including viable builtin
6860 // operators if overload resolution got screwed up by an
6861 // ambiguous user-defined conversion.
6862 //
6863 // FIXME: It's quite possible for different conversions to see
6864 // different ambiguities, though.
6865 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00006866 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00006867 ReportedAmbiguousConversions = true;
6868 }
John McCalld3224162010-01-08 00:58:21 +00006869
John McCall0d1da222010-01-12 00:44:57 +00006870 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00006871 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006872 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006873 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006874
6875 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00006876 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006877}
6878
John McCalla0296f72010-03-19 07:35:19 +00006879static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006880 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006881 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006882
John McCalla0296f72010-03-19 07:35:19 +00006883 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006884}
6885
Douglas Gregorcd695e52008-11-10 20:40:00 +00006886/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6887/// an overloaded function (C++ [over.over]), where @p From is an
6888/// expression with overloaded function type and @p ToType is the type
6889/// we're trying to resolve to. For example:
6890///
6891/// @code
6892/// int f(double);
6893/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006894///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006895/// int (*pfd)(double) = f; // selects f(double)
6896/// @endcode
6897///
6898/// This routine returns the resulting FunctionDecl if it could be
6899/// resolved, and NULL otherwise. When @p Complain is true, this
6900/// routine will emit diagnostics if there is an error.
6901FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006902Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006903 bool Complain,
6904 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006905 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006906 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006907 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006908 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006909 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006910 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006911 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006912 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006913 FunctionType = MemTypePtr->getPointeeType();
6914 IsMember = true;
6915 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006916
Douglas Gregorcd695e52008-11-10 20:40:00 +00006917 // C++ [over.over]p1:
6918 // [...] [Note: any redundant set of parentheses surrounding the
6919 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006920 // C++ [over.over]p1:
6921 // [...] The overloaded function name can be preceded by the &
6922 // operator.
John McCall7d460512010-08-24 23:26:21 +00006923 // However, remember whether the expression has member-pointer form:
6924 // C++ [expr.unary.op]p4:
6925 // A pointer to member is only formed when an explicit & is used
6926 // and its operand is a qualified-id not enclosed in
6927 // parentheses.
John McCall8d08b9b2010-08-27 09:08:28 +00006928 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6929 OverloadExpr *OvlExpr = Ovl.Expression;
John McCall7d460512010-08-24 23:26:21 +00006930
Douglas Gregor064fdb22010-04-14 23:11:21 +00006931 // We expect a pointer or reference to function, or a function pointer.
6932 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6933 if (!FunctionType->isFunctionType()) {
6934 if (Complain)
6935 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6936 << OvlExpr->getName() << ToType;
6937
6938 return 0;
6939 }
6940
John McCall24d18942010-08-24 22:52:39 +00006941 // If the overload expression doesn't have the form of a pointer to
John McCall7d460512010-08-24 23:26:21 +00006942 // member, don't try to convert it to a pointer-to-member type.
John McCall8d08b9b2010-08-27 09:08:28 +00006943 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCall24d18942010-08-24 22:52:39 +00006944 if (!Complain) return 0;
6945
6946 // TODO: Should we condition this on whether any functions might
6947 // have matched, or is it more appropriate to do that in callers?
6948 // TODO: a fixit wouldn't hurt.
6949 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6950 << ToType << OvlExpr->getSourceRange();
6951 return 0;
6952 }
6953
6954 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6955 if (OvlExpr->hasExplicitTemplateArgs()) {
6956 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6957 ExplicitTemplateArgs = &ETABuffer;
6958 }
6959
Douglas Gregor064fdb22010-04-14 23:11:21 +00006960 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006961
Douglas Gregorcd695e52008-11-10 20:40:00 +00006962 // Look through all of the overloaded functions, searching for one
6963 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006964 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006965 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006966
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006967 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006968 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6969 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006970 // Look through any using declarations to find the underlying function.
6971 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6972
Douglas Gregorcd695e52008-11-10 20:40:00 +00006973 // C++ [over.over]p3:
6974 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006975 // targets of type "pointer-to-function" or "reference-to-function."
6976 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006977 // type "pointer-to-member-function."
6978 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006979
Mike Stump11289f42009-09-09 15:08:12 +00006980 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006981 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006982 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006983 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006984 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006985 // static when converting to member pointer.
6986 if (Method->isStatic() == IsMember)
6987 continue;
6988 } else if (IsMember)
6989 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006990
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006991 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006992 // If the name is a function template, template argument deduction is
6993 // done (14.8.2.2), and if the argument deduction succeeds, the
6994 // resulting template argument list is used to generate a single
6995 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006996 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00006997 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006998 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006999 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00007000 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00007001 FunctionType, Specialization, Info)) {
7002 // FIXME: make a note of the failed deduction for diagnostics.
7003 (void)Result;
7004 } else {
Douglas Gregor4ed49f32010-09-29 21:14:36 +00007005 // Template argument deduction ensures that we have an exact match.
7006 // This function template specicalization works.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007007 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00007008 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00007009 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007010 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor9b146582009-07-08 20:55:45 +00007011 }
John McCalld14a8642009-11-21 08:51:07 +00007012
7013 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00007014 }
Mike Stump11289f42009-09-09 15:08:12 +00007015
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007016 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007017 // Skip non-static functions when converting to pointer, and static
7018 // when converting to member pointer.
7019 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00007020 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00007021
7022 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00007023 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00007024 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007025 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007026 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007027
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007028 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007029 QualType ResultTy;
7030 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
7031 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
7032 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00007033 Matches.push_back(std::make_pair(I.getPair(),
7034 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007035 FoundNonTemplateFunction = true;
7036 }
Mike Stump11289f42009-09-09 15:08:12 +00007037 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00007038 }
7039
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007040 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00007041 if (Matches.empty()) {
7042 if (Complain) {
7043 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
7044 << OvlExpr->getName() << FunctionType;
7045 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7046 E = OvlExpr->decls_end();
7047 I != E; ++I)
7048 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
7049 NoteOverloadCandidate(F);
7050 }
7051
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007052 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00007053 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00007054 FunctionDecl *Result = Matches[0].second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007055 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007056 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007057 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00007058 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007059 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007060 return Result;
7061 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007062
7063 // C++ [over.over]p4:
7064 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00007065 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007066 // [...] and any given function template specialization F1 is
7067 // eliminated if the set contains a second function template
7068 // specialization whose function template is more specialized
7069 // than the function template of F1 according to the partial
7070 // ordering rules of 14.5.5.2.
7071
7072 // The algorithm specified above is quadratic. We instead use a
7073 // two-pass algorithm (similar to the one used to identify the
7074 // best viable function in an overload set) that identifies the
7075 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007076
7077 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7078 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7079 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00007080
7081 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00007082 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00007083 TPOC_Other, 0, From->getLocStart(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007084 PDiag(),
7085 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00007086 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00007087 PDiag(diag::note_ovl_candidate)
7088 << (unsigned) oc_function_template);
Douglas Gregorbdd7b232010-09-12 08:16:09 +00007089 if (Result == MatchesCopy.end())
7090 return 0;
7091
John McCall58cc69d2010-01-27 01:50:18 +00007092 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00007093 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007094 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00007095 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00007096 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007097 }
Mike Stump11289f42009-09-09 15:08:12 +00007098
Douglas Gregorfae1d712009-09-26 03:56:17 +00007099 // [...] any function template specializations in the set are
7100 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00007101 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00007102 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00007103 ++I;
7104 else {
John McCalla0296f72010-03-19 07:35:19 +00007105 Matches[I] = Matches[--N];
7106 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00007107 }
7108 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00007109
Mike Stump11289f42009-09-09 15:08:12 +00007110 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007111 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00007112 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00007113 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00007114 FoundResult = Matches[0].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007115 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00007116 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
7117 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007118 }
Mike Stump11289f42009-09-09 15:08:12 +00007119
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007120 // FIXME: We should probably return the same thing that BestViableFunction
7121 // returns (even if we issue the diagnostics here).
Douglas Gregore81f58e2010-11-08 03:40:48 +00007122 if (Complain) {
7123 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
7124 << Matches[0].second->getDeclName();
7125 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7126 NoteOverloadCandidate(Matches[I].second);
7127 }
7128
Douglas Gregorcd695e52008-11-10 20:40:00 +00007129 return 0;
7130}
7131
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007132/// \brief Given an expression that refers to an overloaded function, try to
7133/// resolve that overloaded function expression down to a single function.
7134///
7135/// This routine can only resolve template-ids that refer to a single function
7136/// template, where that template-id refers to a single template whose template
7137/// arguments are either provided by the template-id or have defaults,
7138/// as described in C++0x [temp.arg.explicit]p3.
7139FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
7140 // C++ [over.over]p1:
7141 // [...] [Note: any redundant set of parentheses surrounding the
7142 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007143 // C++ [over.over]p1:
7144 // [...] The overloaded function name can be preceded by the &
7145 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00007146
7147 if (From->getType() != Context.OverloadTy)
7148 return 0;
7149
John McCall8d08b9b2010-08-27 09:08:28 +00007150 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007151
7152 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00007153 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007154 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007155
7156 TemplateArgumentListInfo ExplicitTemplateArgs;
7157 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007158
7159 // Look through all of the overloaded functions, searching for one
7160 // whose type matches exactly.
7161 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00007162 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7163 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007164 // C++0x [temp.arg.explicit]p3:
7165 // [...] In contexts where deduction is done and fails, or in contexts
7166 // where deduction is not done, if a template argument list is
7167 // specified and it, along with any default template arguments,
7168 // identifies a single function template specialization, then the
7169 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00007170 FunctionTemplateDecl *FunctionTemplate
7171 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007172
7173 // C++ [over.over]p2:
7174 // If the name is a function template, template argument deduction is
7175 // done (14.8.2.2), and if the argument deduction succeeds, the
7176 // resulting template argument list is used to generate a single
7177 // function template specialization, which is added to the set of
7178 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007179 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00007180 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007181 if (TemplateDeductionResult Result
7182 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7183 Specialization, Info)) {
7184 // FIXME: make a note of the failed deduction for diagnostics.
7185 (void)Result;
7186 continue;
7187 }
7188
7189 // Multiple matches; we can't resolve to a single declaration.
7190 if (Matched)
7191 return 0;
7192
7193 Matched = Specialization;
7194 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007195
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007196 return Matched;
7197}
7198
Douglas Gregorcabea402009-09-22 15:41:20 +00007199/// \brief Add a single candidate to the overload set.
7200static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00007201 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00007202 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007203 Expr **Args, unsigned NumArgs,
7204 OverloadCandidateSet &CandidateSet,
7205 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00007206 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00007207 if (isa<UsingShadowDecl>(Callee))
7208 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7209
Douglas Gregorcabea402009-09-22 15:41:20 +00007210 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00007211 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00007212 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007213 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007214 return;
John McCalld14a8642009-11-21 08:51:07 +00007215 }
7216
7217 if (FunctionTemplateDecl *FuncTemplate
7218 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00007219 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7220 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007221 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00007222 return;
7223 }
7224
7225 assert(false && "unhandled case in overloaded call candidate");
7226
7227 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00007228}
7229
7230/// \brief Add the overload candidates named by callee and/or found by argument
7231/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00007232void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00007233 Expr **Args, unsigned NumArgs,
7234 OverloadCandidateSet &CandidateSet,
7235 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00007236
7237#ifndef NDEBUG
7238 // Verify that ArgumentDependentLookup is consistent with the rules
7239 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00007240 //
Douglas Gregorcabea402009-09-22 15:41:20 +00007241 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7242 // and let Y be the lookup set produced by argument dependent
7243 // lookup (defined as follows). If X contains
7244 //
7245 // -- a declaration of a class member, or
7246 //
7247 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00007248 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00007249 //
7250 // -- a declaration that is neither a function or a function
7251 // template
7252 //
7253 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00007254
John McCall57500772009-12-16 12:17:52 +00007255 if (ULE->requiresADL()) {
7256 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7257 E = ULE->decls_end(); I != E; ++I) {
7258 assert(!(*I)->getDeclContext()->isRecord());
7259 assert(isa<UsingShadowDecl>(*I) ||
7260 !(*I)->getDeclContext()->isFunctionOrMethod());
7261 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00007262 }
7263 }
7264#endif
7265
John McCall57500772009-12-16 12:17:52 +00007266 // It would be nice to avoid this copy.
7267 TemplateArgumentListInfo TABuffer;
7268 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7269 if (ULE->hasExplicitTemplateArgs()) {
7270 ULE->copyTemplateArgumentsInto(TABuffer);
7271 ExplicitTemplateArgs = &TABuffer;
7272 }
7273
7274 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7275 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00007276 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007277 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00007278 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00007279
John McCall57500772009-12-16 12:17:52 +00007280 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00007281 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7282 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007283 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007284 CandidateSet,
7285 PartialOverloading);
7286}
John McCalld681c392009-12-16 08:11:27 +00007287
7288/// Attempts to recover from a call where no functions were found.
7289///
7290/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00007291static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007292BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00007293 UnresolvedLookupExpr *ULE,
7294 SourceLocation LParenLoc,
7295 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007296 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00007297
7298 CXXScopeSpec SS;
7299 if (ULE->getQualifier()) {
7300 SS.setScopeRep(ULE->getQualifier());
7301 SS.setRange(ULE->getQualifierRange());
7302 }
7303
John McCall57500772009-12-16 12:17:52 +00007304 TemplateArgumentListInfo TABuffer;
7305 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7306 if (ULE->hasExplicitTemplateArgs()) {
7307 ULE->copyTemplateArgumentsInto(TABuffer);
7308 ExplicitTemplateArgs = &TABuffer;
7309 }
7310
John McCalld681c392009-12-16 08:11:27 +00007311 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7312 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00007313 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00007314 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00007315
John McCall57500772009-12-16 12:17:52 +00007316 assert(!R.empty() && "lookup results empty despite recovery");
7317
7318 // Build an implicit member call if appropriate. Just drop the
7319 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00007320 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00007321 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00007322 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7323 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00007324 else if (ExplicitTemplateArgs)
7325 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7326 else
7327 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7328
7329 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007330 return ExprError();
John McCall57500772009-12-16 12:17:52 +00007331
7332 // This shouldn't cause an infinite loop because we're giving it
7333 // an expression with non-empty lookup results, which should never
7334 // end up here.
John McCallb268a282010-08-23 23:25:46 +00007335 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007336 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007337}
Douglas Gregor4038cf42010-06-08 17:35:15 +00007338
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007339/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00007340/// (which eventually refers to the declaration Func) and the call
7341/// arguments Args/NumArgs, attempt to resolve the function call down
7342/// to a specific function. If overload resolution succeeds, returns
7343/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00007344/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007345/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00007346ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007347Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00007348 SourceLocation LParenLoc,
7349 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007350 SourceLocation RParenLoc) {
7351#ifndef NDEBUG
7352 if (ULE->requiresADL()) {
7353 // To do ADL, we must have found an unqualified name.
7354 assert(!ULE->getQualifier() && "qualified name with ADL");
7355
7356 // We don't perform ADL for implicit declarations of builtins.
7357 // Verify that this was correctly set up.
7358 FunctionDecl *F;
7359 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7360 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7361 F->getBuiltinID() && F->isImplicit())
7362 assert(0 && "performing ADL for builtin");
7363
7364 // We don't perform ADL in C.
7365 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7366 }
7367#endif
7368
John McCallbc077cf2010-02-08 23:07:23 +00007369 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007370
John McCall57500772009-12-16 12:17:52 +00007371 // Add the functions denoted by the callee to the set of candidate
7372 // functions, including those from argument-dependent lookup.
7373 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007374
7375 // If we found nothing, try to recover.
7376 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7377 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007378 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007379 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007380 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007381
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007382 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007383 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007384 case OR_Success: {
7385 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00007386 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007387 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7388 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007389 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007390 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
7391 RParenLoc);
John McCall57500772009-12-16 12:17:52 +00007392 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007393
7394 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007395 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007396 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007397 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007398 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007399 break;
7400
7401 case OR_Ambiguous:
7402 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007403 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007404 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007405 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007406
7407 case OR_Deleted:
7408 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7409 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00007410 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00007411 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007412 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007413 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007414 }
7415
Douglas Gregorb412e172010-07-25 18:17:45 +00007416 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007417 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007418}
7419
John McCall4c4c1df2010-01-26 03:27:55 +00007420static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007421 return Functions.size() > 1 ||
7422 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7423}
7424
Douglas Gregor084d8552009-03-13 23:49:33 +00007425/// \brief Create a unary operation that may resolve to an overloaded
7426/// operator.
7427///
7428/// \param OpLoc The location of the operator itself (e.g., '*').
7429///
7430/// \param OpcIn The UnaryOperator::Opcode that describes this
7431/// operator.
7432///
7433/// \param Functions The set of non-member functions that will be
7434/// considered by overload resolution. The caller needs to build this
7435/// set based on the context using, e.g.,
7436/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7437/// set should not contain any member functions; those will be added
7438/// by CreateOverloadedUnaryOp().
7439///
7440/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007441ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007442Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7443 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007444 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007445 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007446
7447 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7448 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7449 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007450 // TODO: provide better source location info.
7451 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007452
John McCalle26a8722010-12-04 08:14:53 +00007453 if (Input->getObjectKind() == OK_ObjCProperty)
7454 ConvertPropertyForRValue(Input);
7455
Douglas Gregor084d8552009-03-13 23:49:33 +00007456 Expr *Args[2] = { Input, 0 };
7457 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007458
Douglas Gregor084d8552009-03-13 23:49:33 +00007459 // For post-increment and post-decrement, add the implicit '0' as
7460 // the second argument, so that we know this is a post-increment or
7461 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007462 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007463 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007464 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7465 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007466 NumArgs = 2;
7467 }
7468
7469 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007470 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007471 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00007472 Opc,
7473 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007474 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00007475 OpLoc));
7476
John McCall58cc69d2010-01-27 01:50:18 +00007477 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007478 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007479 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007480 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007481 /*ADL*/ true, IsOverloaded(Fns),
7482 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007483 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7484 &Args[0], NumArgs,
7485 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007486 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00007487 OpLoc));
7488 }
7489
7490 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007491 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007492
7493 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007494 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007495
7496 // Add operator candidates that are member functions.
7497 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7498
John McCall4c4c1df2010-01-26 03:27:55 +00007499 // Add candidates from ADL.
7500 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007501 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007502 /*ExplicitTemplateArgs*/ 0,
7503 CandidateSet);
7504
Douglas Gregor084d8552009-03-13 23:49:33 +00007505 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007506 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007507
7508 // Perform overload resolution.
7509 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007510 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007511 case OR_Success: {
7512 // We found a built-in operator or an overloaded operator.
7513 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007514
Douglas Gregor084d8552009-03-13 23:49:33 +00007515 if (FnDecl) {
7516 // We matched an overloaded operator. Build a call to that
7517 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007518
Douglas Gregor084d8552009-03-13 23:49:33 +00007519 // Convert the arguments.
7520 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007521 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007522
John McCall16df1e52010-03-30 21:47:33 +00007523 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7524 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007525 return ExprError();
7526 } else {
7527 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007528 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007529 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007530 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007531 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00007532 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007533 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007534 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007535 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007536 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007537 }
7538
John McCall4fa0d5f2010-05-06 18:15:07 +00007539 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7540
John McCall7decc9e2010-11-18 06:31:45 +00007541 // Determine the result type.
7542 QualType ResultTy = FnDecl->getResultType();
7543 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7544 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00007545
Douglas Gregor084d8552009-03-13 23:49:33 +00007546 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007547 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007548
Eli Friedman030eee42009-11-18 03:58:17 +00007549 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007550 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007551 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007552 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007553
John McCallb268a282010-08-23 23:25:46 +00007554 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007555 FnDecl))
7556 return ExprError();
7557
John McCallb268a282010-08-23 23:25:46 +00007558 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007559 } else {
7560 // We matched a built-in operator. Convert the arguments, then
7561 // break out so that we will build the appropriate built-in
7562 // operator node.
7563 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007564 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007565 return ExprError();
7566
7567 break;
7568 }
7569 }
7570
7571 case OR_No_Viable_Function:
7572 // No viable function; fall through to handling this as a
7573 // built-in operator, which will produce an error message for us.
7574 break;
7575
7576 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007577 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregor084d8552009-03-13 23:49:33 +00007578 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007579 << Input->getType()
Douglas Gregor084d8552009-03-13 23:49:33 +00007580 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007581 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7582 Args, NumArgs,
7583 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007584 return ExprError();
7585
7586 case OR_Deleted:
7587 Diag(OpLoc, diag::err_ovl_deleted_oper)
7588 << Best->Function->isDeleted()
7589 << UnaryOperator::getOpcodeStr(Opc)
7590 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007591 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007592 return ExprError();
7593 }
7594
7595 // Either we found no viable overloaded operator or we matched a
7596 // built-in operator. In either case, fall through to trying to
7597 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007598 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007599}
7600
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007601/// \brief Create a binary operation that may resolve to an overloaded
7602/// operator.
7603///
7604/// \param OpLoc The location of the operator itself (e.g., '+').
7605///
7606/// \param OpcIn The BinaryOperator::Opcode that describes this
7607/// operator.
7608///
7609/// \param Functions The set of non-member functions that will be
7610/// considered by overload resolution. The caller needs to build this
7611/// set based on the context using, e.g.,
7612/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7613/// set should not contain any member functions; those will be added
7614/// by CreateOverloadedBinOp().
7615///
7616/// \param LHS Left-hand argument.
7617/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00007618ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007619Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007620 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00007621 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007622 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007623 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00007624 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007625
7626 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7627 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7628 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7629
7630 // If either side is type-dependent, create an appropriate dependent
7631 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00007632 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00007633 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00007634 // If there are no functions to store, just build a dependent
7635 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00007636 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00007637 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00007638 Context.DependentTy,
7639 VK_RValue, OK_Ordinary,
7640 OpLoc));
Douglas Gregor5287f092009-11-05 00:51:44 +00007641
7642 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7643 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007644 VK_LValue,
7645 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00007646 Context.DependentTy,
7647 Context.DependentTy,
7648 OpLoc));
7649 }
John McCall4c4c1df2010-01-26 03:27:55 +00007650
7651 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00007652 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007653 // TODO: provide better source location info in DNLoc component.
7654 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00007655 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007656 = UnresolvedLookupExpr::Create(Context, NamingClass, 0, SourceRange(),
7657 OpNameInfo, /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007658 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007659 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00007660 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007661 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007662 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007663 OpLoc));
7664 }
7665
John McCalle26a8722010-12-04 08:14:53 +00007666 // Always do property rvalue conversions on the RHS.
7667 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7668 ConvertPropertyForRValue(Args[1]);
7669
7670 // The LHS is more complicated.
7671 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
7672
7673 // There's a tension for assignment operators between primitive
7674 // property assignment and the overloaded operators.
7675 if (BinaryOperator::isAssignmentOp(Opc)) {
7676 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7677
7678 // Is the property "logically" settable?
7679 bool Settable = (PRE->isExplicitProperty() ||
7680 PRE->getImplicitPropertySetter());
7681
7682 // To avoid gratuitously inventing semantics, use the primitive
7683 // unless it isn't. Thoughts in case we ever really care:
7684 // - If the property isn't logically settable, we have to
7685 // load and hope.
7686 // - If the property is settable and this is simple assignment,
7687 // we really should use the primitive.
7688 // - If the property is settable, then we could try overloading
7689 // on a generic lvalue of the appropriate type; if it works
7690 // out to a builtin candidate, we would do that same operation
7691 // on the property, and otherwise just error.
7692 if (Settable)
7693 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7694 }
7695
7696 ConvertPropertyForRValue(Args[0]);
7697 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007698
Sebastian Redl6a96bf72009-11-18 23:10:33 +00007699 // If this is the assignment operator, we only perform overload resolution
7700 // if the left-hand side is a class or enumeration type. This is actually
7701 // a hack. The standard requires that we do overload resolution between the
7702 // various built-in candidates, but as DR507 points out, this can lead to
7703 // problems. So we do it this way, which pretty much follows what GCC does.
7704 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00007705 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00007706 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007707
John McCalle26a8722010-12-04 08:14:53 +00007708 // If this is the .* operator, which is not overloadable, just
7709 // create a built-in binary operator.
7710 if (Opc == BO_PtrMemD)
7711 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7712
Douglas Gregor084d8552009-03-13 23:49:33 +00007713 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007714 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007715
7716 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007717 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007718
7719 // Add operator candidates that are member functions.
7720 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7721
John McCall4c4c1df2010-01-26 03:27:55 +00007722 // Add candidates from ADL.
7723 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7724 Args, 2,
7725 /*ExplicitTemplateArgs*/ 0,
7726 CandidateSet);
7727
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007728 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007729 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007730
7731 // Perform overload resolution.
7732 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007733 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00007734 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007735 // We found a built-in operator or an overloaded operator.
7736 FunctionDecl *FnDecl = Best->Function;
7737
7738 if (FnDecl) {
7739 // We matched an overloaded operator. Build a call to that
7740 // operator.
7741
7742 // Convert the arguments.
7743 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00007744 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00007745 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007746
Chandler Carruth8e543b32010-12-12 08:17:55 +00007747 ExprResult Arg1 =
7748 PerformCopyInitialization(
7749 InitializedEntity::InitializeParameter(Context,
7750 FnDecl->getParamDecl(0)),
7751 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007752 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007753 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007754
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007755 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007756 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007757 return ExprError();
7758
7759 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007760 } else {
7761 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00007762 ExprResult Arg0 = PerformCopyInitialization(
7763 InitializedEntity::InitializeParameter(Context,
7764 FnDecl->getParamDecl(0)),
7765 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007766 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007767 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007768
Chandler Carruth8e543b32010-12-12 08:17:55 +00007769 ExprResult Arg1 =
7770 PerformCopyInitialization(
7771 InitializedEntity::InitializeParameter(Context,
7772 FnDecl->getParamDecl(1)),
7773 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007774 if (Arg1.isInvalid())
7775 return ExprError();
7776 Args[0] = LHS = Arg0.takeAs<Expr>();
7777 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007778 }
7779
John McCall4fa0d5f2010-05-06 18:15:07 +00007780 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7781
John McCall7decc9e2010-11-18 06:31:45 +00007782 // Determine the result type.
7783 QualType ResultTy = FnDecl->getResultType();
7784 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7785 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007786
7787 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007788 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007789
John McCallb268a282010-08-23 23:25:46 +00007790 CXXOperatorCallExpr *TheCall =
7791 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007792 Args, 2, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007793
John McCallb268a282010-08-23 23:25:46 +00007794 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007795 FnDecl))
7796 return ExprError();
7797
John McCallb268a282010-08-23 23:25:46 +00007798 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007799 } else {
7800 // We matched a built-in operator. Convert the arguments, then
7801 // break out so that we will build the appropriate built-in
7802 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00007803 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007804 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00007805 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007806 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007807 return ExprError();
7808
7809 break;
7810 }
7811 }
7812
Douglas Gregor66950a32009-09-30 21:46:01 +00007813 case OR_No_Viable_Function: {
7814 // C++ [over.match.oper]p9:
7815 // If the operator is the operator , [...] and there are no
7816 // viable functions, then the operator is assumed to be the
7817 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00007818 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00007819 break;
7820
Chandler Carruth8e543b32010-12-12 08:17:55 +00007821 // For class as left operand for assignment or compound assigment
7822 // operator do not fall through to handling in built-in, but report that
7823 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007824 ExprResult Result = ExprError();
Douglas Gregor66950a32009-09-30 21:46:01 +00007825 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00007826 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007827 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7828 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007829 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007830 } else {
7831 // No viable function; try to create a built-in operation, which will
7832 // produce an error. Then, show the non-viable candidates.
7833 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007834 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007835 assert(Result.isInvalid() &&
7836 "C++ binary operator overloading is missing candidates!");
7837 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00007838 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7839 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007840 return move(Result);
7841 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007842
7843 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007844 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007845 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007846 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00007847 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007848 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7849 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007850 return ExprError();
7851
7852 case OR_Deleted:
7853 Diag(OpLoc, diag::err_ovl_deleted_oper)
7854 << Best->Function->isDeleted()
7855 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007856 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007857 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007858 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007859 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007860
Douglas Gregor66950a32009-09-30 21:46:01 +00007861 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007862 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007863}
7864
John McCalldadc5752010-08-24 06:29:42 +00007865ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007866Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7867 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007868 Expr *Base, Expr *Idx) {
7869 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007870 DeclarationName OpName =
7871 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7872
7873 // If either side is type-dependent, create an appropriate dependent
7874 // expression.
7875 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7876
John McCall58cc69d2010-01-27 01:50:18 +00007877 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007878 // CHECKME: no 'operator' keyword?
7879 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7880 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007881 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007882 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007883 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007884 /*ADL*/ true, /*Overloaded*/ false,
7885 UnresolvedSetIterator(),
7886 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007887 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007888
Sebastian Redladba46e2009-10-29 20:17:01 +00007889 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7890 Args, 2,
7891 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007892 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00007893 RLoc));
7894 }
7895
John McCalle26a8722010-12-04 08:14:53 +00007896 if (Args[0]->getObjectKind() == OK_ObjCProperty)
7897 ConvertPropertyForRValue(Args[0]);
7898 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7899 ConvertPropertyForRValue(Args[1]);
7900
Sebastian Redladba46e2009-10-29 20:17:01 +00007901 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007902 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007903
7904 // Subscript can only be overloaded as a member function.
7905
7906 // Add operator candidates that are member functions.
7907 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7908
7909 // Add builtin operator candidates.
7910 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7911
7912 // Perform overload resolution.
7913 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007914 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00007915 case OR_Success: {
7916 // We found a built-in operator or an overloaded operator.
7917 FunctionDecl *FnDecl = Best->Function;
7918
7919 if (FnDecl) {
7920 // We matched an overloaded operator. Build a call to that
7921 // operator.
7922
John McCalla0296f72010-03-19 07:35:19 +00007923 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007924 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007925
Sebastian Redladba46e2009-10-29 20:17:01 +00007926 // Convert the arguments.
7927 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007928 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007929 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007930 return ExprError();
7931
Anders Carlssona68e51e2010-01-29 18:37:50 +00007932 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007933 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007934 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007935 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00007936 FnDecl->getParamDecl(0)),
7937 SourceLocation(),
7938 Owned(Args[1]));
7939 if (InputInit.isInvalid())
7940 return ExprError();
7941
7942 Args[1] = InputInit.takeAs<Expr>();
7943
Sebastian Redladba46e2009-10-29 20:17:01 +00007944 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00007945 QualType ResultTy = FnDecl->getResultType();
7946 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7947 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007948
7949 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007950 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007951
John McCallb268a282010-08-23 23:25:46 +00007952 CXXOperatorCallExpr *TheCall =
7953 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7954 FnExpr, Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00007955 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007956
John McCallb268a282010-08-23 23:25:46 +00007957 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007958 FnDecl))
7959 return ExprError();
7960
John McCallb268a282010-08-23 23:25:46 +00007961 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007962 } else {
7963 // We matched a built-in operator. Convert the arguments, then
7964 // break out so that we will build the appropriate built-in
7965 // operator node.
7966 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007967 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007968 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007969 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007970 return ExprError();
7971
7972 break;
7973 }
7974 }
7975
7976 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007977 if (CandidateSet.empty())
7978 Diag(LLoc, diag::err_ovl_no_oper)
7979 << Args[0]->getType() << /*subscript*/ 0
7980 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7981 else
7982 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7983 << Args[0]->getType()
7984 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007985 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7986 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00007987 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007988 }
7989
7990 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007991 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
7992 << "[]"
7993 << Args[0]->getType() << Args[1]->getType()
7994 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007995 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7996 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007997 return ExprError();
7998
7999 case OR_Deleted:
8000 Diag(LLoc, diag::err_ovl_deleted_oper)
8001 << Best->Function->isDeleted() << "[]"
8002 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008003 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8004 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008005 return ExprError();
8006 }
8007
8008 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00008009 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008010}
8011
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008012/// BuildCallToMemberFunction - Build a call to a member
8013/// function. MemExpr is the expression that refers to the member
8014/// function (and includes the object parameter), Args/NumArgs are the
8015/// arguments to the function call (not including the object
8016/// parameter). The caller needs to validate that the member
8017/// expression refers to a member function or an overloaded member
8018/// function.
John McCalldadc5752010-08-24 06:29:42 +00008019ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008020Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8021 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008022 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008023 // Dig out the member expression. This holds both the object
8024 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00008025 Expr *NakedMemExpr = MemExprE->IgnoreParens();
8026
John McCall10eae182009-11-30 22:42:35 +00008027 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008028 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00008029 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008030 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00008031 if (isa<MemberExpr>(NakedMemExpr)) {
8032 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00008033 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00008034 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008035 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00008036 } else {
8037 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008038 Qualifier = UnresExpr->getQualifier();
8039
John McCall6e9f8f62009-12-03 04:06:58 +00008040 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00008041 Expr::Classification ObjectClassification
8042 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
8043 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00008044
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008045 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00008046 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00008047
John McCall2d74de92009-12-01 22:10:20 +00008048 // FIXME: avoid copy.
8049 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8050 if (UnresExpr->hasExplicitTemplateArgs()) {
8051 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8052 TemplateArgs = &TemplateArgsBuffer;
8053 }
8054
John McCall10eae182009-11-30 22:42:35 +00008055 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
8056 E = UnresExpr->decls_end(); I != E; ++I) {
8057
John McCall6e9f8f62009-12-03 04:06:58 +00008058 NamedDecl *Func = *I;
8059 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
8060 if (isa<UsingShadowDecl>(Func))
8061 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
8062
Douglas Gregor02824322011-01-26 19:30:28 +00008063
Francois Pichet64225792011-01-18 05:04:39 +00008064 // Microsoft supports direct constructor calls.
8065 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
8066 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
8067 CandidateSet);
8068 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00008069 // If explicit template arguments were provided, we can't call a
8070 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00008071 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00008072 continue;
8073
John McCalla0296f72010-03-19 07:35:19 +00008074 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00008075 ObjectClassification,
8076 Args, NumArgs, CandidateSet,
8077 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008078 } else {
John McCall10eae182009-11-30 22:42:35 +00008079 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00008080 I.getPair(), ActingDC, TemplateArgs,
Douglas Gregor02824322011-01-26 19:30:28 +00008081 ObjectType, ObjectClassification,
8082 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008083 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008084 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008085 }
Mike Stump11289f42009-09-09 15:08:12 +00008086
John McCall10eae182009-11-30 22:42:35 +00008087 DeclarationName DeclName = UnresExpr->getMemberName();
8088
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008089 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008090 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00008091 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008092 case OR_Success:
8093 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008094 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00008095 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008096 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008097 break;
8098
8099 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00008100 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008101 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008102 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008103 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008104 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008105 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008106
8107 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00008108 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008109 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008110 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008111 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008112 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008113
8114 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00008115 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00008116 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00008117 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008118 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008119 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008120 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008121 }
8122
John McCall16df1e52010-03-30 21:47:33 +00008123 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00008124
John McCall2d74de92009-12-01 22:10:20 +00008125 // If overload resolution picked a static member, build a
8126 // non-member call based on that function.
8127 if (Method->isStatic()) {
8128 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8129 Args, NumArgs, RParenLoc);
8130 }
8131
John McCall10eae182009-11-30 22:42:35 +00008132 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008133 }
8134
John McCall7decc9e2010-11-18 06:31:45 +00008135 QualType ResultType = Method->getResultType();
8136 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8137 ResultType = ResultType.getNonLValueExprType(Context);
8138
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008139 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00008140 CXXMemberCallExpr *TheCall =
8141 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008142 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008143
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008144 // Check for a valid return type.
8145 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00008146 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00008147 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008148
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008149 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00008150 // We only need to do this if there was actually an overload; otherwise
8151 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00008152 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00008153 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00008154 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
8155 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00008156 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008157 MemExpr->setBase(ObjectArg);
8158
8159 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00008160 const FunctionProtoType *Proto =
8161 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00008162 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008163 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00008164 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008165
John McCallb268a282010-08-23 23:25:46 +00008166 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00008167 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00008168
John McCallb268a282010-08-23 23:25:46 +00008169 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008170}
8171
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008172/// BuildCallToObjectOfClassType - Build a call to an object of class
8173/// type (C++ [over.call.object]), which can end up invoking an
8174/// overloaded function call operator (@c operator()) or performing a
8175/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00008176ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008177Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00008178 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008179 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008180 SourceLocation RParenLoc) {
John McCalle26a8722010-12-04 08:14:53 +00008181 if (Object->getObjectKind() == OK_ObjCProperty)
8182 ConvertPropertyForRValue(Object);
8183
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008184 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008185 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00008186
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008187 // C++ [over.call.object]p1:
8188 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00008189 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008190 // candidate functions includes at least the function call
8191 // operators of T. The function call operators of T are obtained by
8192 // ordinary lookup of the name operator() in the context of
8193 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00008194 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00008195 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008196
8197 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00008198 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008199 << Object->getSourceRange()))
8200 return true;
8201
John McCall27b18f82009-11-17 02:14:36 +00008202 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8203 LookupQualifiedName(R, Record->getDecl());
8204 R.suppressDiagnostics();
8205
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008206 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00008207 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008208 AddMethodCandidate(Oper.getPair(), Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00008209 Object->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00008210 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00008211 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008212
Douglas Gregorab7897a2008-11-19 22:57:39 +00008213 // C++ [over.call.object]p2:
8214 // In addition, for each conversion function declared in T of the
8215 // form
8216 //
8217 // operator conversion-type-id () cv-qualifier;
8218 //
8219 // where cv-qualifier is the same cv-qualification as, or a
8220 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00008221 // denotes the type "pointer to function of (P1,...,Pn) returning
8222 // R", or the type "reference to pointer to function of
8223 // (P1,...,Pn) returning R", or the type "reference to function
8224 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00008225 // is also considered as a candidate function. Similarly,
8226 // surrogate call functions are added to the set of candidate
8227 // functions for each conversion function declared in an
8228 // accessible base class provided the function is not hidden
8229 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00008230 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00008231 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00008232 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00008233 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00008234 NamedDecl *D = *I;
8235 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8236 if (isa<UsingShadowDecl>(D))
8237 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8238
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008239 // Skip over templated conversion functions; they aren't
8240 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00008241 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008242 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00008243
John McCall6e9f8f62009-12-03 04:06:58 +00008244 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00008245
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008246 // Strip the reference type (if any) and then the pointer type (if
8247 // any) to get down to what might be a function type.
8248 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8249 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8250 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00008251
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008252 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00008253 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00008254 Object, Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008255 }
Mike Stump11289f42009-09-09 15:08:12 +00008256
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008257 // Perform overload resolution.
8258 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008259 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
8260 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008261 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00008262 // Overload resolution succeeded; we'll build the appropriate call
8263 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008264 break;
8265
8266 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00008267 if (CandidateSet.empty())
8268 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8269 << Object->getType() << /*call*/ 1
8270 << Object->getSourceRange();
8271 else
8272 Diag(Object->getSourceRange().getBegin(),
8273 diag::err_ovl_no_viable_object_call)
8274 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008275 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008276 break;
8277
8278 case OR_Ambiguous:
8279 Diag(Object->getSourceRange().getBegin(),
8280 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008281 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008282 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008283 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008284
8285 case OR_Deleted:
8286 Diag(Object->getSourceRange().getBegin(),
8287 diag::err_ovl_deleted_object_call)
8288 << Best->Function->isDeleted()
8289 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008290 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008291 break;
Mike Stump11289f42009-09-09 15:08:12 +00008292 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008293
Douglas Gregorb412e172010-07-25 18:17:45 +00008294 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008295 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008296
Douglas Gregorab7897a2008-11-19 22:57:39 +00008297 if (Best->Function == 0) {
8298 // Since there is no function declaration, this is one of the
8299 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00008300 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00008301 = cast<CXXConversionDecl>(
8302 Best->Conversions[0].UserDefined.ConversionFunction);
8303
John McCalla0296f72010-03-19 07:35:19 +00008304 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008305 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008306
Douglas Gregorab7897a2008-11-19 22:57:39 +00008307 // We selected one of the surrogate functions that converts the
8308 // object parameter to a function pointer. Perform the conversion
8309 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00008310
8311 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00008312 // and then call it.
Douglas Gregor668443e2011-01-20 00:18:04 +00008313 ExprResult Call = BuildCXXMemberCallExpr(Object, Best->FoundDecl, Conv);
8314 if (Call.isInvalid())
8315 return ExprError();
8316
8317 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008318 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008319 }
8320
John McCalla0296f72010-03-19 07:35:19 +00008321 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008322 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008323
Douglas Gregorab7897a2008-11-19 22:57:39 +00008324 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8325 // that calls this method, using Object for the implicit object
8326 // parameter and passing along the remaining arguments.
8327 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008328 const FunctionProtoType *Proto =
8329 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008330
8331 unsigned NumArgsInProto = Proto->getNumArgs();
8332 unsigned NumArgsToCheck = NumArgs;
8333
8334 // Build the full argument list for the method call (the
8335 // implicit object parameter is placed at the beginning of the
8336 // list).
8337 Expr **MethodArgs;
8338 if (NumArgs < NumArgsInProto) {
8339 NumArgsToCheck = NumArgsInProto;
8340 MethodArgs = new Expr*[NumArgsInProto + 1];
8341 } else {
8342 MethodArgs = new Expr*[NumArgs + 1];
8343 }
8344 MethodArgs[0] = Object;
8345 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8346 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00008347
John McCall7decc9e2010-11-18 06:31:45 +00008348 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008349
8350 // Once we've built TheCall, all of the expressions are properly
8351 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00008352 QualType ResultTy = Method->getResultType();
8353 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8354 ResultTy = ResultTy.getNonLValueExprType(Context);
8355
John McCallb268a282010-08-23 23:25:46 +00008356 CXXOperatorCallExpr *TheCall =
8357 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
8358 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00008359 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008360 delete [] MethodArgs;
8361
John McCallb268a282010-08-23 23:25:46 +00008362 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00008363 Method))
8364 return true;
8365
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008366 // We may have default arguments. If so, we need to allocate more
8367 // slots in the call for them.
8368 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00008369 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008370 else if (NumArgs > NumArgsInProto)
8371 NumArgsToCheck = NumArgsInProto;
8372
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008373 bool IsError = false;
8374
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008375 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008376 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008377 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008378 TheCall->setArg(0, Object);
8379
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008380
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008381 // Check the argument types.
8382 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008383 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008384 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008385 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00008386
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008387 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008388
John McCalldadc5752010-08-24 06:29:42 +00008389 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008390 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008391 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008392 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00008393 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008394
8395 IsError |= InputInit.isInvalid();
8396 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008397 } else {
John McCalldadc5752010-08-24 06:29:42 +00008398 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008399 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8400 if (DefArg.isInvalid()) {
8401 IsError = true;
8402 break;
8403 }
8404
8405 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008406 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008407
8408 TheCall->setArg(i + 1, Arg);
8409 }
8410
8411 // If this is a variadic call, handle args passed through "...".
8412 if (Proto->isVariadic()) {
8413 // Promote the arguments (C99 6.5.2.2p7).
8414 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8415 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00008416 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008417 TheCall->setArg(i + 1, Arg);
8418 }
8419 }
8420
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008421 if (IsError) return true;
8422
John McCallb268a282010-08-23 23:25:46 +00008423 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00008424 return true;
8425
John McCalle172be52010-08-24 06:09:16 +00008426 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008427}
8428
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008429/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00008430/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008431/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00008432ExprResult
John McCallb268a282010-08-23 23:25:46 +00008433Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008434 assert(Base->getType()->isRecordType() &&
8435 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00008436
John McCalle26a8722010-12-04 08:14:53 +00008437 if (Base->getObjectKind() == OK_ObjCProperty)
8438 ConvertPropertyForRValue(Base);
8439
John McCallbc077cf2010-02-08 23:07:23 +00008440 SourceLocation Loc = Base->getExprLoc();
8441
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008442 // C++ [over.ref]p1:
8443 //
8444 // [...] An expression x->m is interpreted as (x.operator->())->m
8445 // for a class object x of type T if T::operator->() exists and if
8446 // the operator is selected as the best match function by the
8447 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00008448 DeclarationName OpName =
8449 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00008450 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008451 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00008452
John McCallbc077cf2010-02-08 23:07:23 +00008453 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00008454 PDiag(diag::err_typecheck_incomplete_tag)
8455 << Base->getSourceRange()))
8456 return ExprError();
8457
John McCall27b18f82009-11-17 02:14:36 +00008458 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8459 LookupQualifiedName(R, BaseRecord->getDecl());
8460 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00008461
8462 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00008463 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00008464 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
8465 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00008466 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008467
8468 // Perform overload resolution.
8469 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008470 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008471 case OR_Success:
8472 // Overload resolution succeeded; we'll build the call below.
8473 break;
8474
8475 case OR_No_Viable_Function:
8476 if (CandidateSet.empty())
8477 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008478 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008479 else
8480 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008481 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008482 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008483 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008484
8485 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008486 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8487 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008488 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008489 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008490
8491 case OR_Deleted:
8492 Diag(OpLoc, diag::err_ovl_deleted_oper)
8493 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00008494 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008495 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008496 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008497 }
8498
John McCalla0296f72010-03-19 07:35:19 +00008499 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008500 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00008501
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008502 // Convert the object parameter.
8503 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008504 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8505 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00008506 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00008507
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008508 // Build the operator call.
John McCall7decc9e2010-11-18 06:31:45 +00008509 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008510
John McCall7decc9e2010-11-18 06:31:45 +00008511 QualType ResultTy = Method->getResultType();
8512 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8513 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00008514 CXXOperatorCallExpr *TheCall =
8515 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008516 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008517
John McCallb268a282010-08-23 23:25:46 +00008518 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008519 Method))
8520 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008521 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008522}
8523
Douglas Gregorcd695e52008-11-10 20:40:00 +00008524/// FixOverloadedFunctionReference - E is an expression that refers to
8525/// a C++ overloaded function (possibly with some parentheses and
8526/// perhaps a '&' around it). We have resolved the overloaded function
8527/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008528/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00008529Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00008530 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00008531 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008532 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8533 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008534 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008535 return PE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008536
8537 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8538 }
8539
8540 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008541 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8542 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00008543 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008544 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00008545 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00008546 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00008547 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008548 return ICE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008549
John McCallcf142162010-08-07 06:22:56 +00008550 return ImplicitCastExpr::Create(Context, ICE->getType(),
8551 ICE->getCastKind(),
8552 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00008553 ICE->getValueKind());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008554 }
8555
8556 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00008557 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008558 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008559 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8560 if (Method->isStatic()) {
8561 // Do nothing: static member functions aren't any different
8562 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008563 } else {
John McCalle66edc12009-11-24 19:00:30 +00008564 // Fix the sub expression, which really has to be an
8565 // UnresolvedLookupExpr holding an overloaded member function
8566 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008567 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8568 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008569 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008570 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008571
John McCalld14a8642009-11-21 08:51:07 +00008572 assert(isa<DeclRefExpr>(SubExpr)
8573 && "fixed to something other than a decl ref");
8574 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8575 && "fixed to a member ref with no nested name qualifier");
8576
8577 // We have taken the address of a pointer to member
8578 // function. Perform the computation here so that we get the
8579 // appropriate pointer to member type.
8580 QualType ClassType
8581 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8582 QualType MemPtrType
8583 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8584
John McCall7decc9e2010-11-18 06:31:45 +00008585 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8586 VK_RValue, OK_Ordinary,
8587 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008588 }
8589 }
John McCall16df1e52010-03-30 21:47:33 +00008590 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8591 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008592 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008593 return UnOp;
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008594
John McCalle3027922010-08-25 11:45:40 +00008595 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008596 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00008597 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008598 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008599 }
John McCalld14a8642009-11-21 08:51:07 +00008600
8601 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00008602 // FIXME: avoid copy.
8603 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00008604 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00008605 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8606 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00008607 }
8608
John McCalld14a8642009-11-21 08:51:07 +00008609 return DeclRefExpr::Create(Context,
8610 ULE->getQualifier(),
8611 ULE->getQualifierRange(),
8612 Fn,
8613 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00008614 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008615 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008616 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00008617 }
8618
John McCall10eae182009-11-30 22:42:35 +00008619 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00008620 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00008621 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8622 if (MemExpr->hasExplicitTemplateArgs()) {
8623 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8624 TemplateArgs = &TemplateArgsBuffer;
8625 }
John McCall6b51f282009-11-23 01:53:49 +00008626
John McCall2d74de92009-12-01 22:10:20 +00008627 Expr *Base;
8628
John McCall7decc9e2010-11-18 06:31:45 +00008629 // If we're filling in a static method where we used to have an
8630 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00008631 if (MemExpr->isImplicitAccess()) {
8632 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8633 return DeclRefExpr::Create(Context,
8634 MemExpr->getQualifier(),
8635 MemExpr->getQualifierRange(),
8636 Fn,
8637 MemExpr->getMemberLoc(),
8638 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008639 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008640 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00008641 } else {
8642 SourceLocation Loc = MemExpr->getMemberLoc();
8643 if (MemExpr->getQualifier())
8644 Loc = MemExpr->getQualifierRange().getBegin();
8645 Base = new (Context) CXXThisExpr(Loc,
8646 MemExpr->getBaseType(),
8647 /*isImplicit=*/true);
8648 }
John McCall2d74de92009-12-01 22:10:20 +00008649 } else
John McCallc3007a22010-10-26 07:05:15 +00008650 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00008651
8652 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008653 MemExpr->isArrow(),
8654 MemExpr->getQualifier(),
8655 MemExpr->getQualifierRange(),
8656 Fn,
John McCall16df1e52010-03-30 21:47:33 +00008657 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008658 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00008659 TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008660 Fn->getType(),
8661 cast<CXXMethodDecl>(Fn)->isStatic()
8662 ? VK_LValue : VK_RValue,
8663 OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008664 }
8665
John McCallc3007a22010-10-26 07:05:15 +00008666 llvm_unreachable("Invalid reference to overloaded function");
8667 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008668}
8669
John McCalldadc5752010-08-24 06:29:42 +00008670ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8671 DeclAccessPair Found,
8672 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00008673 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008674}
8675
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008676} // end namespace clang