blob: 9c9ff6ddea05b63319a0448cea8534ea3aefc935 [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.
John Wiegley01296292011-04-08 18:41:53 +000039static ExprResult
John McCall7decc9e2010-11-18 06:31:45 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41 SourceLocation Loc = SourceLocation()) {
John Wiegley01296292011-04-08 18:41:53 +000042 ExprResult E = S.Owned(new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc));
43 E = S.DefaultFunctionArrayConversion(E.take());
44 if (E.isInvalid())
45 return ExprError();
46 return move(E);
John McCall7decc9e2010-11-18 06:31:45 +000047}
48
John McCall5c32be02010-08-24 20:38:10 +000049static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
50 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000051 StandardConversionSequence &SCS,
52 bool CStyle);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000053
54static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
55 QualType &ToType,
56 bool InOverloadResolution,
57 StandardConversionSequence &SCS,
58 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000059static OverloadingResult
60IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
61 UserDefinedConversionSequence& User,
62 OverloadCandidateSet& Conversions,
63 bool AllowExplicit);
64
65
66static ImplicitConversionSequence::CompareKind
67CompareStandardConversionSequences(Sema &S,
68 const StandardConversionSequence& SCS1,
69 const StandardConversionSequence& SCS2);
70
71static ImplicitConversionSequence::CompareKind
72CompareQualificationConversions(Sema &S,
73 const StandardConversionSequence& SCS1,
74 const StandardConversionSequence& SCS2);
75
76static ImplicitConversionSequence::CompareKind
77CompareDerivedToBaseConversions(Sema &S,
78 const StandardConversionSequence& SCS1,
79 const StandardConversionSequence& SCS2);
80
81
82
Douglas Gregor5251f1b2008-10-21 16:13:35 +000083/// GetConversionCategory - Retrieve the implicit conversion
84/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000085ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000086GetConversionCategory(ImplicitConversionKind Kind) {
87 static const ImplicitConversionCategory
88 Category[(int)ICK_Num_Conversion_Kinds] = {
89 ICC_Identity,
90 ICC_Lvalue_Transformation,
91 ICC_Lvalue_Transformation,
92 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000093 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000094 ICC_Qualification_Adjustment,
95 ICC_Promotion,
96 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000097 ICC_Promotion,
98 ICC_Conversion,
99 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000100 ICC_Conversion,
101 ICC_Conversion,
102 ICC_Conversion,
103 ICC_Conversion,
104 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000105 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000106 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000107 ICC_Conversion,
108 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000109 ICC_Conversion
110 };
111 return Category[(int)Kind];
112}
113
114/// GetConversionRank - Retrieve the implicit conversion rank
115/// corresponding to the given implicit conversion kind.
116ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
117 static const ImplicitConversionRank
118 Rank[(int)ICK_Num_Conversion_Kinds] = {
119 ICR_Exact_Match,
120 ICR_Exact_Match,
121 ICR_Exact_Match,
122 ICR_Exact_Match,
123 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000124 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000125 ICR_Promotion,
126 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000127 ICR_Promotion,
128 ICR_Conversion,
129 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000130 ICR_Conversion,
131 ICR_Conversion,
132 ICR_Conversion,
133 ICR_Conversion,
134 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000135 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000136 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000137 ICR_Conversion,
138 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000139 ICR_Complex_Real_Conversion,
140 ICR_Conversion,
141 ICR_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000142 };
143 return Rank[(int)Kind];
144}
145
146/// GetImplicitConversionName - Return the name of this kind of
147/// implicit conversion.
148const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000149 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000150 "No conversion",
151 "Lvalue-to-rvalue",
152 "Array-to-pointer",
153 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000154 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000155 "Qualification",
156 "Integral promotion",
157 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000158 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000159 "Integral conversion",
160 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000161 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000162 "Floating-integral conversion",
163 "Pointer conversion",
164 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000165 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000166 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000167 "Derived-to-base conversion",
168 "Vector conversion",
169 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000170 "Complex-real conversion",
171 "Block Pointer conversion",
172 "Transparent Union Conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000173 };
174 return Name[Kind];
175}
176
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000177/// StandardConversionSequence - Set the standard conversion
178/// sequence to the identity conversion.
179void StandardConversionSequence::setAsIdentityConversion() {
180 First = ICK_Identity;
181 Second = ICK_Identity;
182 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000183 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000184 ReferenceBinding = false;
185 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000186 IsLvalueReference = true;
187 BindsToFunctionLvalue = false;
188 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000189 BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000190 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000191}
192
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000193/// getRank - Retrieve the rank of this standard conversion sequence
194/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
195/// implicit conversions.
196ImplicitConversionRank StandardConversionSequence::getRank() const {
197 ImplicitConversionRank Rank = ICR_Exact_Match;
198 if (GetConversionRank(First) > Rank)
199 Rank = GetConversionRank(First);
200 if (GetConversionRank(Second) > Rank)
201 Rank = GetConversionRank(Second);
202 if (GetConversionRank(Third) > Rank)
203 Rank = GetConversionRank(Third);
204 return Rank;
205}
206
207/// isPointerConversionToBool - Determines whether this conversion is
208/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000209/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000210/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000211bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000212 // Note that FromType has not necessarily been transformed by the
213 // array-to-pointer or function-to-pointer implicit conversions, so
214 // check for their presence as well as checking whether FromType is
215 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000216 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000217 (getFromType()->isPointerType() ||
218 getFromType()->isObjCObjectPointerType() ||
219 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000220 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
222 return true;
223
224 return false;
225}
226
Douglas Gregor5c407d92008-10-23 00:40:37 +0000227/// isPointerConversionToVoidPointer - Determines whether this
228/// conversion is a conversion of a pointer to a void pointer. This is
229/// used as part of the ranking of standard conversion sequences (C++
230/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000231bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000232StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000233isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000234 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000235 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000236
237 // Note that FromType has not necessarily been transformed by the
238 // array-to-pointer implicit conversion, so check for its presence
239 // and redo the conversion to get a pointer.
240 if (First == ICK_Array_To_Pointer)
241 FromType = Context.getArrayDecayedType(FromType);
242
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000243 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000244 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000245 return ToPtrType->getPointeeType()->isVoidType();
246
247 return false;
248}
249
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000250/// DebugPrint - Print this standard conversion sequence to standard
251/// error. Useful for debugging overloading issues.
252void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000254 bool PrintedSomething = false;
255 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000256 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000257 PrintedSomething = true;
258 }
259
260 if (Second != ICK_Identity) {
261 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000262 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000263 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000264 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000265
266 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000267 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000268 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000269 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000270 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000271 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000272 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000273 PrintedSomething = true;
274 }
275
276 if (Third != ICK_Identity) {
277 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000278 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000279 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000280 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000281 PrintedSomething = true;
282 }
283
284 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000285 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000286 }
287}
288
289/// DebugPrint - Print this user-defined conversion sequence to standard
290/// error. Useful for debugging overloading issues.
291void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000292 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000293 if (Before.First || Before.Second || Before.Third) {
294 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000295 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000296 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000297 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000298 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000299 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000300 After.DebugPrint();
301 }
302}
303
304/// DebugPrint - Print this implicit conversion sequence to standard
305/// error. Useful for debugging overloading issues.
306void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000307 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000308 switch (ConversionKind) {
309 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000310 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000311 Standard.DebugPrint();
312 break;
313 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000314 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000315 UserDefined.DebugPrint();
316 break;
317 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000318 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000319 break;
John McCall0d1da222010-01-12 00:44:57 +0000320 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000321 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000322 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000323 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000324 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000325 break;
326 }
327
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000328 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000329}
330
John McCall0d1da222010-01-12 00:44:57 +0000331void AmbiguousConversionSequence::construct() {
332 new (&conversions()) ConversionSet();
333}
334
335void AmbiguousConversionSequence::destruct() {
336 conversions().~ConversionSet();
337}
338
339void
340AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
341 FromTypePtr = O.FromTypePtr;
342 ToTypePtr = O.ToTypePtr;
343 new (&conversions()) ConversionSet(O.conversions());
344}
345
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000346namespace {
347 // Structure used by OverloadCandidate::DeductionFailureInfo to store
348 // template parameter and template argument information.
349 struct DFIParamWithArguments {
350 TemplateParameter Param;
351 TemplateArgument FirstArg;
352 TemplateArgument SecondArg;
353 };
354}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000355
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000356/// \brief Convert from Sema's representation of template deduction information
357/// to the form used in overload-candidate information.
358OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000359static MakeDeductionFailureInfo(ASTContext &Context,
360 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000361 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000362 OverloadCandidate::DeductionFailureInfo Result;
363 Result.Result = static_cast<unsigned>(TDK);
364 Result.Data = 0;
365 switch (TDK) {
366 case Sema::TDK_Success:
367 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000368 case Sema::TDK_TooManyArguments:
369 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000370 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000371
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000372 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000373 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000374 Result.Data = Info.Param.getOpaqueValue();
375 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000376
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000377 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000378 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000379 // FIXME: Should allocate from normal heap so that we can free this later.
380 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000381 Saved->Param = Info.Param;
382 Saved->FirstArg = Info.FirstArg;
383 Saved->SecondArg = Info.SecondArg;
384 Result.Data = Saved;
385 break;
386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000387
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000388 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000389 Result.Data = Info.take();
390 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000391
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000392 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000393 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000394 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000395 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000396
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000397 return Result;
398}
John McCall0d1da222010-01-12 00:44:57 +0000399
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000400void OverloadCandidate::DeductionFailureInfo::Destroy() {
401 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
402 case Sema::TDK_Success:
403 case Sema::TDK_InstantiationDepth:
404 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000405 case Sema::TDK_TooManyArguments:
406 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000407 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000408 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000409
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000410 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000411 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000412 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000413 Data = 0;
414 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000415
416 case Sema::TDK_SubstitutionFailure:
417 // FIXME: Destroy the template arugment list?
418 Data = 0;
419 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000420
Douglas Gregor461761d2010-05-08 18:20:53 +0000421 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000422 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000423 case Sema::TDK_FailedOverloadResolution:
424 break;
425 }
426}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000427
428TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000429OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
430 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
431 case Sema::TDK_Success:
432 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000433 case Sema::TDK_TooManyArguments:
434 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000435 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000436 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000437
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000438 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000439 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000440 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000441
442 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000443 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000444 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000445
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000446 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000447 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000448 case Sema::TDK_FailedOverloadResolution:
449 break;
450 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000451
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000452 return TemplateParameter();
453}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000454
Douglas Gregord09efd42010-05-08 20:07:26 +0000455TemplateArgumentList *
456OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
457 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
458 case Sema::TDK_Success:
459 case Sema::TDK_InstantiationDepth:
460 case Sema::TDK_TooManyArguments:
461 case Sema::TDK_TooFewArguments:
462 case Sema::TDK_Incomplete:
463 case Sema::TDK_InvalidExplicitArguments:
464 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000465 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000466 return 0;
467
468 case Sema::TDK_SubstitutionFailure:
469 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000470
Douglas Gregord09efd42010-05-08 20:07:26 +0000471 // Unhandled
472 case Sema::TDK_NonDeducedMismatch:
473 case Sema::TDK_FailedOverloadResolution:
474 break;
475 }
476
477 return 0;
478}
479
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000480const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
481 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
482 case Sema::TDK_Success:
483 case Sema::TDK_InstantiationDepth:
484 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000485 case Sema::TDK_TooManyArguments:
486 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000487 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000488 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000489 return 0;
490
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000491 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000492 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000493 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000494
Douglas Gregor461761d2010-05-08 18:20:53 +0000495 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000496 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000497 case Sema::TDK_FailedOverloadResolution:
498 break;
499 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000500
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000501 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000502}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000503
504const TemplateArgument *
505OverloadCandidate::DeductionFailureInfo::getSecondArg() {
506 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
507 case Sema::TDK_Success:
508 case Sema::TDK_InstantiationDepth:
509 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000510 case Sema::TDK_TooManyArguments:
511 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000512 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000513 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000514 return 0;
515
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000516 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000517 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000518 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
519
Douglas Gregor461761d2010-05-08 18:20:53 +0000520 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000521 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000522 case Sema::TDK_FailedOverloadResolution:
523 break;
524 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000525
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000526 return 0;
527}
528
529void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000530 inherited::clear();
531 Functions.clear();
532}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000534// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000535// overload of the declarations in Old. This routine returns false if
536// New and Old cannot be overloaded, e.g., if New has the same
537// signature as some function in Old (C++ 1.3.10) or if the Old
538// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000539// it does return false, MatchedDecl will point to the decl that New
540// cannot be overloaded with. This decl may be a UsingShadowDecl on
541// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000542//
543// Example: Given the following input:
544//
545// void f(int, float); // #1
546// void f(int, int); // #2
547// int f(int, int); // #3
548//
549// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000550// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000551//
John McCall3d988d92009-12-02 08:47:38 +0000552// When we process #2, Old contains only the FunctionDecl for #1. By
553// comparing the parameter types, we see that #1 and #2 are overloaded
554// (since they have different signatures), so this routine returns
555// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000556//
John McCall3d988d92009-12-02 08:47:38 +0000557// When we process #3, Old is an overload set containing #1 and #2. We
558// compare the signatures of #3 to #1 (they're overloaded, so we do
559// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
560// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000561// signature), IsOverload returns false and MatchedDecl will be set to
562// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000563//
564// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
565// into a class by a using declaration. The rules for whether to hide
566// shadow declarations ignore some properties which otherwise figure
567// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000568Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000569Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
570 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000571 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000572 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000573 NamedDecl *OldD = *I;
574
575 bool OldIsUsingDecl = false;
576 if (isa<UsingShadowDecl>(OldD)) {
577 OldIsUsingDecl = true;
578
579 // We can always introduce two using declarations into the same
580 // context, even if they have identical signatures.
581 if (NewIsUsingDecl) continue;
582
583 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
584 }
585
586 // If either declaration was introduced by a using declaration,
587 // we'll need to use slightly different rules for matching.
588 // Essentially, these rules are the normal rules, except that
589 // function templates hide function templates with different
590 // return types or template parameter lists.
591 bool UseMemberUsingDeclRules =
592 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
593
John McCall3d988d92009-12-02 08:47:38 +0000594 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000595 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
596 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
597 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
598 continue;
599 }
600
John McCalldaa3d6b2009-12-09 03:35:25 +0000601 Match = *I;
602 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000603 }
John McCall3d988d92009-12-02 08:47:38 +0000604 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000605 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
606 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
607 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
608 continue;
609 }
610
John McCalldaa3d6b2009-12-09 03:35:25 +0000611 Match = *I;
612 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000613 }
John McCalla8987a2942010-11-10 03:01:53 +0000614 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000615 // We can overload with these, which can show up when doing
616 // redeclaration checks for UsingDecls.
617 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000618 } else if (isa<TagDecl>(OldD)) {
619 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000620 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
621 // Optimistically assume that an unresolved using decl will
622 // overload; if it doesn't, we'll have to diagnose during
623 // template instantiation.
624 } else {
John McCall1f82f242009-11-18 22:49:29 +0000625 // (C++ 13p1):
626 // Only function declarations can be overloaded; object and type
627 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000628 Match = *I;
629 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000630 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000631 }
John McCall1f82f242009-11-18 22:49:29 +0000632
John McCalldaa3d6b2009-12-09 03:35:25 +0000633 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000634}
635
John McCalle9cccd82010-06-16 08:42:20 +0000636bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
637 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000638 // If both of the functions are extern "C", then they are not
639 // overloads.
640 if (Old->isExternC() && New->isExternC())
641 return false;
642
John McCall1f82f242009-11-18 22:49:29 +0000643 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
644 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
645
646 // C++ [temp.fct]p2:
647 // A function template can be overloaded with other function templates
648 // and with normal (non-template) functions.
649 if ((OldTemplate == 0) != (NewTemplate == 0))
650 return true;
651
652 // Is the function New an overload of the function Old?
653 QualType OldQType = Context.getCanonicalType(Old->getType());
654 QualType NewQType = Context.getCanonicalType(New->getType());
655
656 // Compare the signatures (C++ 1.3.10) of the two functions to
657 // determine whether they are overloads. If we find any mismatch
658 // in the signature, they are overloads.
659
660 // If either of these functions is a K&R-style function (no
661 // prototype), then we consider them to have matching signatures.
662 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
663 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
664 return false;
665
John McCall424cec92011-01-19 06:33:43 +0000666 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
667 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000668
669 // The signature of a function includes the types of its
670 // parameters (C++ 1.3.10), which includes the presence or absence
671 // of the ellipsis; see C++ DR 357).
672 if (OldQType != NewQType &&
673 (OldType->getNumArgs() != NewType->getNumArgs() ||
674 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000675 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000676 return true;
677
678 // C++ [temp.over.link]p4:
679 // The signature of a function template consists of its function
680 // signature, its return type and its template parameter list. The names
681 // of the template parameters are significant only for establishing the
682 // relationship between the template parameters and the rest of the
683 // signature.
684 //
685 // We check the return type and template parameter lists for function
686 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000687 //
688 // However, we don't consider either of these when deciding whether
689 // a member introduced by a shadow declaration is hidden.
690 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000691 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
692 OldTemplate->getTemplateParameters(),
693 false, TPL_TemplateMatch) ||
694 OldType->getResultType() != NewType->getResultType()))
695 return true;
696
697 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000698 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000699 //
700 // As part of this, also check whether one of the member functions
701 // is static, in which case they are not overloads (C++
702 // 13.1p2). While not part of the definition of the signature,
703 // this check is important to determine whether these functions
704 // can be overloaded.
705 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
706 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
707 if (OldMethod && NewMethod &&
708 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000709 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000710 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
711 if (!UseUsingDeclRules &&
712 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
713 (OldMethod->getRefQualifier() == RQ_None ||
714 NewMethod->getRefQualifier() == RQ_None)) {
715 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000716 // - Member function declarations with the same name and the same
717 // parameter-type-list as well as member function template
718 // declarations with the same name, the same parameter-type-list, and
719 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000720 // them, but not all, have a ref-qualifier (8.3.5).
721 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
722 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
723 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
724 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000725
John McCall1f82f242009-11-18 22:49:29 +0000726 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000727 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000728
John McCall1f82f242009-11-18 22:49:29 +0000729 // The signatures match; this is not an overload.
730 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000731}
732
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000733/// TryImplicitConversion - Attempt to perform an implicit conversion
734/// from the given expression (Expr) to the given type (ToType). This
735/// function returns an implicit conversion sequence that can be used
736/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000737///
738/// void f(float f);
739/// void g(int i) { f(i); }
740///
741/// this routine would produce an implicit conversion sequence to
742/// describe the initialization of f from i, which will be a standard
743/// conversion sequence containing an lvalue-to-rvalue conversion (C++
744/// 4.1) followed by a floating-integral conversion (C++ 4.9).
745//
746/// Note that this routine only determines how the conversion can be
747/// performed; it does not actually perform the conversion. As such,
748/// it will not produce any diagnostics if no conversion is available,
749/// but will instead return an implicit conversion sequence of kind
750/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000751///
752/// If @p SuppressUserConversions, then user-defined conversions are
753/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000754/// If @p AllowExplicit, then explicit user-defined conversions are
755/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000756static ImplicitConversionSequence
757TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
758 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000759 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000760 bool InOverloadResolution,
761 bool CStyle) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000762 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000763 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +0000764 ICS.Standard, CStyle)) {
John McCall0d1da222010-01-12 00:44:57 +0000765 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000766 return ICS;
767 }
768
John McCall5c32be02010-08-24 20:38:10 +0000769 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000770 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000771 return ICS;
772 }
773
Douglas Gregor836a7e82010-08-11 02:15:33 +0000774 // C++ [over.ics.user]p4:
775 // A conversion of an expression of class type to the same class
776 // type is given Exact Match rank, and a conversion of an
777 // expression of class type to a base class of that type is
778 // given Conversion rank, in spite of the fact that a copy/move
779 // constructor (i.e., a user-defined conversion function) is
780 // called for those cases.
781 QualType FromType = From->getType();
782 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000783 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
784 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000785 ICS.setStandard();
786 ICS.Standard.setAsIdentityConversion();
787 ICS.Standard.setFromType(FromType);
788 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000789
Douglas Gregor5ab11652010-04-17 22:01:05 +0000790 // We don't actually check at this point whether there is a valid
791 // copy/move constructor, since overloading just assumes that it
792 // exists. When we actually perform initialization, we'll find the
793 // appropriate constructor to copy the returned object, if needed.
794 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000795
Douglas Gregor5ab11652010-04-17 22:01:05 +0000796 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000797 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000798 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000799
Douglas Gregor836a7e82010-08-11 02:15:33 +0000800 return ICS;
801 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000802
Douglas Gregor836a7e82010-08-11 02:15:33 +0000803 if (SuppressUserConversions) {
804 // We're not in the case above, so there is no conversion that
805 // we can perform.
806 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000807 return ICS;
808 }
809
810 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000811 OverloadCandidateSet Conversions(From->getExprLoc());
812 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000813 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000814 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000815
816 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000817 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000818 // C++ [over.ics.user]p4:
819 // A conversion of an expression of class type to the same class
820 // type is given Exact Match rank, and a conversion of an
821 // expression of class type to a base class of that type is
822 // given Conversion rank, in spite of the fact that a copy
823 // constructor (i.e., a user-defined conversion function) is
824 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000825 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000826 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000827 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000828 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
829 QualType ToCanon
830 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000831 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000832 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000833 // Turn this into a "standard" conversion sequence, so that it
834 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000835 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000836 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000837 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000838 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000839 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000840 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000841 ICS.Standard.Second = ICK_Derived_To_Base;
842 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000843 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000844
845 // C++ [over.best.ics]p4:
846 // However, when considering the argument of a user-defined
847 // conversion function that is a candidate by 13.3.1.3 when
848 // invoked for the copying of the temporary in the second step
849 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
850 // 13.3.1.6 in all cases, only standard conversion sequences and
851 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000852 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000853 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000854 }
John McCalle8c8cd22010-01-13 22:30:33 +0000855 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000856 ICS.setAmbiguous();
857 ICS.Ambiguous.setFromType(From->getType());
858 ICS.Ambiguous.setToType(ToType);
859 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
860 Cand != Conversions.end(); ++Cand)
861 if (Cand->Viable)
862 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000863 } else {
John McCall65eb8792010-02-25 01:37:24 +0000864 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000865 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000866
867 return ICS;
868}
869
John McCall5c32be02010-08-24 20:38:10 +0000870bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
871 const InitializedEntity &Entity,
872 Expr *Initializer,
873 bool SuppressUserConversions,
874 bool AllowExplicitConversions,
Douglas Gregor58281352011-01-27 00:58:17 +0000875 bool InOverloadResolution,
876 bool CStyle) {
John McCall5c32be02010-08-24 20:38:10 +0000877 ImplicitConversionSequence ICS
878 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
879 SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000880 AllowExplicitConversions,
Douglas Gregor58281352011-01-27 00:58:17 +0000881 InOverloadResolution,
882 CStyle);
John McCall5c32be02010-08-24 20:38:10 +0000883 if (ICS.isBad()) return true;
884
885 // Perform the actual conversion.
886 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
887 return false;
888}
889
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000890/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +0000891/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000892/// converted expression. Flavor is the kind of conversion we're
893/// performing, used in the error message. If @p AllowExplicit,
894/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +0000895ExprResult
896Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000897 AssignmentAction Action, bool AllowExplicit) {
898 ImplicitConversionSequence ICS;
899 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
900}
901
John Wiegley01296292011-04-08 18:41:53 +0000902ExprResult
903Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000904 AssignmentAction Action, bool AllowExplicit,
905 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000906 ICS = clang::TryImplicitConversion(*this, From, ToType,
907 /*SuppressUserConversions=*/false,
908 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000909 /*InOverloadResolution=*/false,
910 /*CStyle=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000911 return PerformImplicitConversion(From, ToType, ICS, Action);
912}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000913
914/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000915/// conversion that strips "noreturn" off the nested function type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000916static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000917 QualType ToType, QualType &ResultTy) {
918 if (Context.hasSameUnqualifiedType(FromType, ToType))
919 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000920
John McCall991eb4b2010-12-21 00:44:39 +0000921 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
922 // where F adds one of the following at most once:
923 // - a pointer
924 // - a member pointer
925 // - a block pointer
926 CanQualType CanTo = Context.getCanonicalType(ToType);
927 CanQualType CanFrom = Context.getCanonicalType(FromType);
928 Type::TypeClass TyClass = CanTo->getTypeClass();
929 if (TyClass != CanFrom->getTypeClass()) return false;
930 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
931 if (TyClass == Type::Pointer) {
932 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
933 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
934 } else if (TyClass == Type::BlockPointer) {
935 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
936 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
937 } else if (TyClass == Type::MemberPointer) {
938 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
939 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
940 } else {
941 return false;
942 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000943
John McCall991eb4b2010-12-21 00:44:39 +0000944 TyClass = CanTo->getTypeClass();
945 if (TyClass != CanFrom->getTypeClass()) return false;
946 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
947 return false;
948 }
949
950 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
951 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
952 if (!EInfo.getNoReturn()) return false;
953
954 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
955 assert(QualType(FromFn, 0).isCanonical());
956 if (QualType(FromFn, 0) != CanTo) return false;
957
958 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000959 return true;
960}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000961
Douglas Gregor46188682010-05-18 22:42:18 +0000962/// \brief Determine whether the conversion from FromType to ToType is a valid
963/// vector conversion.
964///
965/// \param ICK Will be set to the vector conversion kind, if this is a vector
966/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000967static bool IsVectorConversion(ASTContext &Context, QualType FromType,
968 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +0000969 // We need at least one of these types to be a vector type to have a vector
970 // conversion.
971 if (!ToType->isVectorType() && !FromType->isVectorType())
972 return false;
973
974 // Identical types require no conversions.
975 if (Context.hasSameUnqualifiedType(FromType, ToType))
976 return false;
977
978 // There are no conversions between extended vector types, only identity.
979 if (ToType->isExtVectorType()) {
980 // There are no conversions between extended vector types other than the
981 // identity conversion.
982 if (FromType->isExtVectorType())
983 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000984
Douglas Gregor46188682010-05-18 22:42:18 +0000985 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000986 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000987 ICK = ICK_Vector_Splat;
988 return true;
989 }
990 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000991
992 // We can perform the conversion between vector types in the following cases:
993 // 1)vector types are equivalent AltiVec and GCC vector types
994 // 2)lax vector conversions are permitted and the vector types are of the
995 // same size
996 if (ToType->isVectorType() && FromType->isVectorType()) {
997 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000998 (Context.getLangOptions().LaxVectorConversions &&
999 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001000 ICK = ICK_Vector_Conversion;
1001 return true;
1002 }
Douglas Gregor46188682010-05-18 22:42:18 +00001003 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001004
Douglas Gregor46188682010-05-18 22:42:18 +00001005 return false;
1006}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001007
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001008/// IsStandardConversion - Determines whether there is a standard
1009/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1010/// expression From to the type ToType. Standard conversion sequences
1011/// only consider non-class types; for conversions that involve class
1012/// types, use TryImplicitConversion. If a conversion exists, SCS will
1013/// contain the standard conversion sequence required to perform this
1014/// conversion and this routine will return true. Otherwise, this
1015/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001016static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1017 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001018 StandardConversionSequence &SCS,
1019 bool CStyle) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001020 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001021
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001022 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001023 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001024 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001025 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001026 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001027 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001028
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001029 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001030 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001031 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001032 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001033 return false;
1034
Mike Stump11289f42009-09-09 15:08:12 +00001035 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001036 }
1037
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001038 // The first conversion can be an lvalue-to-rvalue conversion,
1039 // array-to-pointer conversion, or function-to-pointer conversion
1040 // (C++ 4p1).
1041
John McCall5c32be02010-08-24 20:38:10 +00001042 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001043 DeclAccessPair AccessPair;
1044 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001045 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001046 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001047 // We were able to resolve the address of the overloaded function,
1048 // so we can convert to the type of that function.
1049 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001050
1051 // we can sometimes resolve &foo<int> regardless of ToType, so check
1052 // if the type matches (identity) or we are converting to bool
1053 if (!S.Context.hasSameUnqualifiedType(
1054 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1055 QualType resultTy;
1056 // if the function type matches except for [[noreturn]], it's ok
1057 if (!IsNoReturnConversion(S.Context, FromType,
1058 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1059 // otherwise, only a boolean conversion is standard
1060 if (!ToType->isBooleanType())
1061 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001062 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001063
Chandler Carruthffce2452011-03-29 08:08:18 +00001064 // Check if the "from" expression is taking the address of an overloaded
1065 // function and recompute the FromType accordingly. Take advantage of the
1066 // fact that non-static member functions *must* have such an address-of
1067 // expression.
1068 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1069 if (Method && !Method->isStatic()) {
1070 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1071 "Non-unary operator on non-static member address");
1072 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1073 == UO_AddrOf &&
1074 "Non-address-of operator on non-static member address");
1075 const Type *ClassType
1076 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1077 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001078 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1079 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1080 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001081 "Non-address-of operator for overloaded function expression");
1082 FromType = S.Context.getPointerType(FromType);
1083 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001084
Douglas Gregor980fb162010-04-29 18:24:40 +00001085 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001086 assert(S.Context.hasSameType(
1087 FromType,
1088 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001089 } else {
1090 return false;
1091 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001092 }
Mike Stump11289f42009-09-09 15:08:12 +00001093 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001094 // An lvalue (3.10) of a non-function, non-array type T can be
1095 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001096 bool argIsLValue = From->isLValue();
1097 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001098 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001099 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001100 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001101
1102 // If T is a non-class type, the type of the rvalue is the
1103 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001104 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1105 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001106 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001107 } else if (FromType->isArrayType()) {
1108 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001109 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001110
1111 // An lvalue or rvalue of type "array of N T" or "array of unknown
1112 // bound of T" can be converted to an rvalue of type "pointer to
1113 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001114 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001115
John McCall5c32be02010-08-24 20:38:10 +00001116 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001117 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001118 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001119
1120 // For the purpose of ranking in overload resolution
1121 // (13.3.3.1.1), this conversion is considered an
1122 // array-to-pointer conversion followed by a qualification
1123 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001124 SCS.Second = ICK_Identity;
1125 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001126 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001127 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001128 }
John McCall086a4642010-11-24 05:12:34 +00001129 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001130 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001131 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001132
1133 // An lvalue of function type T can be converted to an rvalue of
1134 // type "pointer to T." The result is a pointer to the
1135 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001136 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001137 } else {
1138 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001139 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001140 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001141 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001142
1143 // The second conversion can be an integral promotion, floating
1144 // point promotion, integral conversion, floating point conversion,
1145 // floating-integral conversion, pointer conversion,
1146 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001147 // For overloading in C, this can also be a "compatible-type"
1148 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001149 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001150 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001151 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001152 // The unqualified versions of the types are the same: there's no
1153 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001154 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001155 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001156 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001157 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001158 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001159 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001160 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001161 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001162 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001163 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001164 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001165 SCS.Second = ICK_Complex_Promotion;
1166 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001167 } else if (ToType->isBooleanType() &&
1168 (FromType->isArithmeticType() ||
1169 FromType->isAnyPointerType() ||
1170 FromType->isBlockPointerType() ||
1171 FromType->isMemberPointerType() ||
1172 FromType->isNullPtrType())) {
1173 // Boolean conversions (C++ 4.12).
1174 SCS.Second = ICK_Boolean_Conversion;
1175 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001176 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001177 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001178 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001179 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001180 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001181 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001182 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001183 SCS.Second = ICK_Complex_Conversion;
1184 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001185 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1186 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001187 // Complex-real conversions (C99 6.3.1.7)
1188 SCS.Second = ICK_Complex_Real;
1189 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001190 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001191 // Floating point conversions (C++ 4.8).
1192 SCS.Second = ICK_Floating_Conversion;
1193 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001194 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001195 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001196 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001197 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001198 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001199 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001200 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001201 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
1202 SCS.Second = ICK_Block_Pointer_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001203 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1204 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001205 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001206 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001207 SCS.IncompatibleObjC = IncompatibleObjC;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001208 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001209 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001210 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001211 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001212 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001213 SCS.Second = SecondICK;
1214 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001215 } else if (!S.getLangOptions().CPlusPlus &&
1216 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001217 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001218 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001219 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001220 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001221 // Treat a conversion that strips "noreturn" as an identity conversion.
1222 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001223 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1224 InOverloadResolution,
1225 SCS, CStyle)) {
1226 SCS.Second = ICK_TransparentUnionConversion;
1227 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001228 } else {
1229 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001230 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001231 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001232 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001233
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001234 QualType CanonFrom;
1235 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001236 // The third conversion can be a qualification conversion (C++ 4p1).
Douglas Gregor58281352011-01-27 00:58:17 +00001237 if (S.IsQualificationConversion(FromType, ToType, CStyle)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001238 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001239 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001240 CanonFrom = S.Context.getCanonicalType(FromType);
1241 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001242 } else {
1243 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001244 SCS.Third = ICK_Identity;
1245
Mike Stump11289f42009-09-09 15:08:12 +00001246 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001247 // [...] Any difference in top-level cv-qualification is
1248 // subsumed by the initialization itself and does not constitute
1249 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001250 CanonFrom = S.Context.getCanonicalType(FromType);
1251 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001252 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001253 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001254 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1255 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001256 FromType = ToType;
1257 CanonFrom = CanonTo;
1258 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001259 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001260 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001261
1262 // If we have not converted the argument type to the parameter type,
1263 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001264 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001265 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001266
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001267 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001268}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001269
1270static bool
1271IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1272 QualType &ToType,
1273 bool InOverloadResolution,
1274 StandardConversionSequence &SCS,
1275 bool CStyle) {
1276
1277 const RecordType *UT = ToType->getAsUnionType();
1278 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1279 return false;
1280 // The field to initialize within the transparent union.
1281 RecordDecl *UD = UT->getDecl();
1282 // It's compatible if the expression matches any of the fields.
1283 for (RecordDecl::field_iterator it = UD->field_begin(),
1284 itend = UD->field_end();
1285 it != itend; ++it) {
1286 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS, CStyle)) {
1287 ToType = it->getType();
1288 return true;
1289 }
1290 }
1291 return false;
1292}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001293
1294/// IsIntegralPromotion - Determines whether the conversion from the
1295/// expression From (whose potentially-adjusted type is FromType) to
1296/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1297/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001298bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001299 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001300 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001301 if (!To) {
1302 return false;
1303 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001304
1305 // An rvalue of type char, signed char, unsigned char, short int, or
1306 // unsigned short int can be converted to an rvalue of type int if
1307 // int can represent all the values of the source type; otherwise,
1308 // the source rvalue can be converted to an rvalue of type unsigned
1309 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001310 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1311 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001312 if (// We can promote any signed, promotable integer type to an int
1313 (FromType->isSignedIntegerType() ||
1314 // We can promote any unsigned integer type whose size is
1315 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001316 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001317 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001318 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001319 }
1320
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001321 return To->getKind() == BuiltinType::UInt;
1322 }
1323
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001324 // C++0x [conv.prom]p3:
1325 // A prvalue of an unscoped enumeration type whose underlying type is not
1326 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1327 // following types that can represent all the values of the enumeration
1328 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1329 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001330 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001331 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001332 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001333 // with lowest integer conversion rank (4.13) greater than the rank of long
1334 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001335 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001336 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1337 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1338 // provided for a scoped enumeration.
1339 if (FromEnumType->getDecl()->isScoped())
1340 return false;
1341
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001342 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001343 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001344 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001345 return Context.hasSameUnqualifiedType(ToType,
1346 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001347 }
John McCall56774992009-12-09 09:09:27 +00001348
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001349 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001350 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1351 // to an rvalue a prvalue of the first of the following types that can
1352 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001353 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001354 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001355 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001356 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001357 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001358 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001359 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001360 // Determine whether the type we're converting from is signed or
1361 // unsigned.
1362 bool FromIsSigned;
1363 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001364
John McCall56774992009-12-09 09:09:27 +00001365 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1366 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001367
1368 // The types we'll try to promote to, in the appropriate
1369 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001370 QualType PromoteTypes[6] = {
1371 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001372 Context.LongTy, Context.UnsignedLongTy ,
1373 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001374 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001375 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001376 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1377 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001378 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001379 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1380 // We found the type that we can promote to. If this is the
1381 // type we wanted, we have a promotion. Otherwise, no
1382 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001383 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001384 }
1385 }
1386 }
1387
1388 // An rvalue for an integral bit-field (9.6) can be converted to an
1389 // rvalue of type int if int can represent all the values of the
1390 // bit-field; otherwise, it can be converted to unsigned int if
1391 // unsigned int can represent all the values of the bit-field. If
1392 // the bit-field is larger yet, no integral promotion applies to
1393 // it. If the bit-field has an enumerated type, it is treated as any
1394 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001395 // FIXME: We should delay checking of bit-fields until we actually perform the
1396 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001397 using llvm::APSInt;
1398 if (From)
1399 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001400 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001401 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001402 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1403 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1404 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001405
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001406 // Are we promoting to an int from a bitfield that fits in an int?
1407 if (BitWidth < ToSize ||
1408 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1409 return To->getKind() == BuiltinType::Int;
1410 }
Mike Stump11289f42009-09-09 15:08:12 +00001411
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001412 // Are we promoting to an unsigned int from an unsigned bitfield
1413 // that fits into an unsigned int?
1414 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1415 return To->getKind() == BuiltinType::UInt;
1416 }
Mike Stump11289f42009-09-09 15:08:12 +00001417
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001418 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001419 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001420 }
Mike Stump11289f42009-09-09 15:08:12 +00001421
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001422 // An rvalue of type bool can be converted to an rvalue of type int,
1423 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001424 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001425 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001426 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001427
1428 return false;
1429}
1430
1431/// IsFloatingPointPromotion - Determines whether the conversion from
1432/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1433/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001434bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001435 /// An rvalue of type float can be converted to an rvalue of type
1436 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001437 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1438 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001439 if (FromBuiltin->getKind() == BuiltinType::Float &&
1440 ToBuiltin->getKind() == BuiltinType::Double)
1441 return true;
1442
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001443 // C99 6.3.1.5p1:
1444 // When a float is promoted to double or long double, or a
1445 // double is promoted to long double [...].
1446 if (!getLangOptions().CPlusPlus &&
1447 (FromBuiltin->getKind() == BuiltinType::Float ||
1448 FromBuiltin->getKind() == BuiltinType::Double) &&
1449 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1450 return true;
1451 }
1452
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001453 return false;
1454}
1455
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001456/// \brief Determine if a conversion is a complex promotion.
1457///
1458/// A complex promotion is defined as a complex -> complex conversion
1459/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001460/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001461bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001462 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001463 if (!FromComplex)
1464 return false;
1465
John McCall9dd450b2009-09-21 23:43:11 +00001466 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001467 if (!ToComplex)
1468 return false;
1469
1470 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001471 ToComplex->getElementType()) ||
1472 IsIntegralPromotion(0, FromComplex->getElementType(),
1473 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001474}
1475
Douglas Gregor237f96c2008-11-26 23:31:11 +00001476/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1477/// the pointer type FromPtr to a pointer to type ToPointee, with the
1478/// same type qualifiers as FromPtr has on its pointee type. ToType,
1479/// if non-empty, will be a pointer to ToType that may or may not have
1480/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001481static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001482BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001483 QualType ToPointee, QualType ToType,
1484 ASTContext &Context) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001485 assert((FromPtr->getTypeClass() == Type::Pointer ||
1486 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1487 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001488
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001489 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1490 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1491 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001492
1493 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001494 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001495 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001496 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001497
1498 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001499 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001500 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001501 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001502 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001503
1504 // Build a pointer to ToPointee. It has the right qualifiers
1505 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001506 if (isa<ObjCObjectPointerType>(ToType))
1507 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001508 return Context.getPointerType(ToPointee);
1509 }
1510
1511 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001512 QualType QualifiedCanonToPointee
1513 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001514
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001515 if (isa<ObjCObjectPointerType>(ToType))
1516 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1517 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001518}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001519
Mike Stump11289f42009-09-09 15:08:12 +00001520static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001521 bool InOverloadResolution,
1522 ASTContext &Context) {
1523 // Handle value-dependent integral null pointer constants correctly.
1524 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1525 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001526 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001527 return !InOverloadResolution;
1528
Douglas Gregor56751b52009-09-25 04:25:58 +00001529 return Expr->isNullPointerConstant(Context,
1530 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1531 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001532}
Mike Stump11289f42009-09-09 15:08:12 +00001533
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001534/// IsPointerConversion - Determines whether the conversion of the
1535/// expression From, which has the (possibly adjusted) type FromType,
1536/// can be converted to the type ToType via a pointer conversion (C++
1537/// 4.10). If so, returns true and places the converted type (that
1538/// might differ from ToType in its cv-qualifiers at some level) into
1539/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001540///
Douglas Gregora29dc052008-11-27 01:19:21 +00001541/// This routine also supports conversions to and from block pointers
1542/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1543/// pointers to interfaces. FIXME: Once we've determined the
1544/// appropriate overloading rules for Objective-C, we may want to
1545/// split the Objective-C checks into a different routine; however,
1546/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001547/// conversions, so for now they live here. IncompatibleObjC will be
1548/// set if the conversion is an allowed Objective-C conversion that
1549/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001550bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001551 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001552 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001553 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001554 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001555 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1556 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001557 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001558
Mike Stump11289f42009-09-09 15:08:12 +00001559 // Conversion from a null pointer constant to any Objective-C pointer type.
1560 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001561 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001562 ConvertedType = ToType;
1563 return true;
1564 }
1565
Douglas Gregor231d1c62008-11-27 00:15:41 +00001566 // Blocks: Block pointers can be converted to void*.
1567 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001568 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001569 ConvertedType = ToType;
1570 return true;
1571 }
1572 // Blocks: A null pointer constant can be converted to a block
1573 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001574 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001575 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001576 ConvertedType = ToType;
1577 return true;
1578 }
1579
Sebastian Redl576fd422009-05-10 18:38:11 +00001580 // If the left-hand-side is nullptr_t, the right side can be a null
1581 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001582 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001583 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001584 ConvertedType = ToType;
1585 return true;
1586 }
1587
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001588 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001589 if (!ToTypePtr)
1590 return false;
1591
1592 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001593 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001594 ConvertedType = ToType;
1595 return true;
1596 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001597
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001598 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001599 // , including objective-c pointers.
1600 QualType ToPointeeType = ToTypePtr->getPointeeType();
1601 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001602 ConvertedType = BuildSimilarlyQualifiedPointerType(
1603 FromType->getAs<ObjCObjectPointerType>(),
1604 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001605 ToType, Context);
1606 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001607 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001608 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001609 if (!FromTypePtr)
1610 return false;
1611
1612 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001613
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001614 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001615 // pointer conversion, so don't do all of the work below.
1616 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1617 return false;
1618
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001619 // An rvalue of type "pointer to cv T," where T is an object type,
1620 // can be converted to an rvalue of type "pointer to cv void" (C++
1621 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001622 if (FromPointeeType->isIncompleteOrObjectType() &&
1623 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001624 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001625 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001626 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001627 return true;
1628 }
1629
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001630 // When we're overloading in C, we allow a special kind of pointer
1631 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001632 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001633 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001634 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001635 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001636 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001637 return true;
1638 }
1639
Douglas Gregor5c407d92008-10-23 00:40:37 +00001640 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001641 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001642 // An rvalue of type "pointer to cv D," where D is a class type,
1643 // can be converted to an rvalue of type "pointer to cv B," where
1644 // B is a base class (clause 10) of D. If B is an inaccessible
1645 // (clause 11) or ambiguous (10.2) base class of D, a program that
1646 // necessitates this conversion is ill-formed. The result of the
1647 // conversion is a pointer to the base class sub-object of the
1648 // derived class object. The null pointer value is converted to
1649 // the null pointer value of the destination type.
1650 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001651 // Note that we do not check for ambiguity or inaccessibility
1652 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001653 if (getLangOptions().CPlusPlus &&
1654 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001655 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001656 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001657 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001658 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001659 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001660 ToType, Context);
1661 return true;
1662 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001663
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001664 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1665 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1666 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1667 ToPointeeType,
1668 ToType, Context);
1669 return true;
1670 }
1671
Douglas Gregora119f102008-12-19 19:13:09 +00001672 return false;
1673}
1674
1675/// isObjCPointerConversion - Determines whether this is an
1676/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1677/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001678bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001679 QualType& ConvertedType,
1680 bool &IncompatibleObjC) {
1681 if (!getLangOptions().ObjC1)
1682 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001683
Steve Naroff7cae42b2009-07-10 23:34:53 +00001684 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001685 const ObjCObjectPointerType* ToObjCPtr =
1686 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001687 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001688 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001689
Steve Naroff7cae42b2009-07-10 23:34:53 +00001690 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001691 // If the pointee types are the same (ignoring qualifications),
1692 // then this is not a pointer conversion.
1693 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1694 FromObjCPtr->getPointeeType()))
1695 return false;
1696
Steve Naroff1329fa02009-07-15 18:40:39 +00001697 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001698 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001699 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001700 ConvertedType = ToType;
1701 return true;
1702 }
1703 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001704 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001705 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001706 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001707 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001708 ConvertedType = ToType;
1709 return true;
1710 }
1711 // Objective C++: We're able to convert from a pointer to an
1712 // interface to a pointer to a different interface.
1713 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001714 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1715 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1716 if (getLangOptions().CPlusPlus && LHS && RHS &&
1717 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1718 FromObjCPtr->getPointeeType()))
1719 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001720 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001721 ToObjCPtr->getPointeeType(),
1722 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001723 return true;
1724 }
1725
1726 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1727 // Okay: this is some kind of implicit downcast of Objective-C
1728 // interfaces, which is permitted. However, we're going to
1729 // complain about it.
1730 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001731 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001732 ToObjCPtr->getPointeeType(),
1733 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001734 return true;
1735 }
Mike Stump11289f42009-09-09 15:08:12 +00001736 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001737 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001738 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001739 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001740 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001741 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001742 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001743 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001744 // to a block pointer type.
1745 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1746 ConvertedType = ToType;
1747 return true;
1748 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001749 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001750 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001751 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001752 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001753 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001754 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001755 ConvertedType = ToType;
1756 return true;
1757 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001758 else
Douglas Gregora119f102008-12-19 19:13:09 +00001759 return false;
1760
Douglas Gregor033f56d2008-12-23 00:53:59 +00001761 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001762 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001763 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001764 else if (const BlockPointerType *FromBlockPtr =
1765 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001766 FromPointeeType = FromBlockPtr->getPointeeType();
1767 else
Douglas Gregora119f102008-12-19 19:13:09 +00001768 return false;
1769
Douglas Gregora119f102008-12-19 19:13:09 +00001770 // If we have pointers to pointers, recursively check whether this
1771 // is an Objective-C conversion.
1772 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1773 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1774 IncompatibleObjC)) {
1775 // We always complain about this conversion.
1776 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001777 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregora119f102008-12-19 19:13:09 +00001778 return true;
1779 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001780 // Allow conversion of pointee being objective-c pointer to another one;
1781 // as in I* to id.
1782 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1783 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1784 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1785 IncompatibleObjC)) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001786 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001787 return true;
1788 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001789
Douglas Gregor033f56d2008-12-23 00:53:59 +00001790 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001791 // differences in the argument and result types are in Objective-C
1792 // pointer conversions. If so, we permit the conversion (but
1793 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001794 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001795 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001796 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001797 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001798 if (FromFunctionType && ToFunctionType) {
1799 // If the function types are exactly the same, this isn't an
1800 // Objective-C pointer conversion.
1801 if (Context.getCanonicalType(FromPointeeType)
1802 == Context.getCanonicalType(ToPointeeType))
1803 return false;
1804
1805 // Perform the quick checks that will tell us whether these
1806 // function types are obviously different.
1807 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1808 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1809 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1810 return false;
1811
1812 bool HasObjCConversion = false;
1813 if (Context.getCanonicalType(FromFunctionType->getResultType())
1814 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1815 // Okay, the types match exactly. Nothing to do.
1816 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1817 ToFunctionType->getResultType(),
1818 ConvertedType, IncompatibleObjC)) {
1819 // Okay, we have an Objective-C pointer conversion.
1820 HasObjCConversion = true;
1821 } else {
1822 // Function types are too different. Abort.
1823 return false;
1824 }
Mike Stump11289f42009-09-09 15:08:12 +00001825
Douglas Gregora119f102008-12-19 19:13:09 +00001826 // Check argument types.
1827 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1828 ArgIdx != NumArgs; ++ArgIdx) {
1829 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1830 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1831 if (Context.getCanonicalType(FromArgType)
1832 == Context.getCanonicalType(ToArgType)) {
1833 // Okay, the types match exactly. Nothing to do.
1834 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1835 ConvertedType, IncompatibleObjC)) {
1836 // Okay, we have an Objective-C pointer conversion.
1837 HasObjCConversion = true;
1838 } else {
1839 // Argument types are too different. Abort.
1840 return false;
1841 }
1842 }
1843
1844 if (HasObjCConversion) {
1845 // We had an Objective-C conversion. Allow this pointer
1846 // conversion, but complain about it.
1847 ConvertedType = ToType;
1848 IncompatibleObjC = true;
1849 return true;
1850 }
1851 }
1852
Sebastian Redl72b597d2009-01-25 19:43:20 +00001853 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001854}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001855
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001856bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1857 QualType& ConvertedType) {
1858 QualType ToPointeeType;
1859 if (const BlockPointerType *ToBlockPtr =
1860 ToType->getAs<BlockPointerType>())
1861 ToPointeeType = ToBlockPtr->getPointeeType();
1862 else
1863 return false;
1864
1865 QualType FromPointeeType;
1866 if (const BlockPointerType *FromBlockPtr =
1867 FromType->getAs<BlockPointerType>())
1868 FromPointeeType = FromBlockPtr->getPointeeType();
1869 else
1870 return false;
1871 // We have pointer to blocks, check whether the only
1872 // differences in the argument and result types are in Objective-C
1873 // pointer conversions. If so, we permit the conversion.
1874
1875 const FunctionProtoType *FromFunctionType
1876 = FromPointeeType->getAs<FunctionProtoType>();
1877 const FunctionProtoType *ToFunctionType
1878 = ToPointeeType->getAs<FunctionProtoType>();
1879
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001880 if (!FromFunctionType || !ToFunctionType)
1881 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001882
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001883 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001884 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001885
1886 // Perform the quick checks that will tell us whether these
1887 // function types are obviously different.
1888 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1889 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
1890 return false;
1891
1892 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
1893 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
1894 if (FromEInfo != ToEInfo)
1895 return false;
1896
1897 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00001898 if (Context.hasSameType(FromFunctionType->getResultType(),
1899 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00001900 // Okay, the types match exactly. Nothing to do.
1901 } else {
1902 QualType RHS = FromFunctionType->getResultType();
1903 QualType LHS = ToFunctionType->getResultType();
1904 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
1905 !RHS.hasQualifiers() && LHS.hasQualifiers())
1906 LHS = LHS.getUnqualifiedType();
1907
1908 if (Context.hasSameType(RHS,LHS)) {
1909 // OK exact match.
1910 } else if (isObjCPointerConversion(RHS, LHS,
1911 ConvertedType, IncompatibleObjC)) {
1912 if (IncompatibleObjC)
1913 return false;
1914 // Okay, we have an Objective-C pointer conversion.
1915 }
1916 else
1917 return false;
1918 }
1919
1920 // Check argument types.
1921 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1922 ArgIdx != NumArgs; ++ArgIdx) {
1923 IncompatibleObjC = false;
1924 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1925 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1926 if (Context.hasSameType(FromArgType, ToArgType)) {
1927 // Okay, the types match exactly. Nothing to do.
1928 } else if (isObjCPointerConversion(ToArgType, FromArgType,
1929 ConvertedType, IncompatibleObjC)) {
1930 if (IncompatibleObjC)
1931 return false;
1932 // Okay, we have an Objective-C pointer conversion.
1933 } else
1934 // Argument types are too different. Abort.
1935 return false;
1936 }
1937 ConvertedType = ToType;
1938 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001939}
1940
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001941/// FunctionArgTypesAreEqual - This routine checks two function proto types
1942/// for equlity of their argument types. Caller has already checked that
1943/// they have same number of arguments. This routine assumes that Objective-C
1944/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001945bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00001946 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001947 if (!getLangOptions().ObjC1)
1948 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1949 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001950
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001951 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1952 N = NewType->arg_type_begin(),
1953 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1954 QualType ToType = (*O);
1955 QualType FromType = (*N);
1956 if (ToType != FromType) {
1957 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1958 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001959 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1960 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1961 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1962 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001963 continue;
1964 }
John McCall8b07ec22010-05-15 11:32:37 +00001965 else if (const ObjCObjectPointerType *PTTo =
1966 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001967 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00001968 FromType->getAs<ObjCObjectPointerType>())
1969 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1970 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001971 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001972 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001973 }
1974 }
1975 return true;
1976}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001977
Douglas Gregor39c16d42008-10-24 04:54:22 +00001978/// CheckPointerConversion - Check the pointer conversion from the
1979/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001980/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001981/// conversions for which IsPointerConversion has already returned
1982/// true. It returns true and produces a diagnostic if there was an
1983/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001984bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001985 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001986 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001987 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001988 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001989 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001990
John McCall8cb679e2010-11-15 09:13:47 +00001991 Kind = CK_BitCast;
1992
Chandler Carruthffab8732011-04-09 07:32:05 +00001993 if (!IsCStyleOrFunctionalCast &&
1994 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
1995 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
1996 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00001997 PDiag(diag::warn_impcast_bool_to_null_pointer)
1998 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00001999
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002000 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
2001 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002002 QualType FromPointeeType = FromPtrType->getPointeeType(),
2003 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002004
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002005 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2006 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002007 // We must have a derived-to-base conversion. Check an
2008 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002009 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2010 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002011 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002012 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002013 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002014
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002015 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002016 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002017 }
2018 }
Mike Stump11289f42009-09-09 15:08:12 +00002019 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00002020 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002021 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00002022 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002023 // Objective-C++ conversions are always okay.
2024 // FIXME: We should have a different class of conversions for the
2025 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002026 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002027 return false;
John McCall8cb679e2010-11-15 09:13:47 +00002028 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00002029 }
John McCall8cb679e2010-11-15 09:13:47 +00002030
2031 // We shouldn't fall into this case unless it's valid for other
2032 // reasons.
2033 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2034 Kind = CK_NullToPointer;
2035
Douglas Gregor39c16d42008-10-24 04:54:22 +00002036 return false;
2037}
2038
Sebastian Redl72b597d2009-01-25 19:43:20 +00002039/// IsMemberPointerConversion - Determines whether the conversion of the
2040/// expression From, which has the (possibly adjusted) type FromType, can be
2041/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2042/// If so, returns true and places the converted type (that might differ from
2043/// ToType in its cv-qualifiers at some level) into ConvertedType.
2044bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002045 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002046 bool InOverloadResolution,
2047 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002048 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002049 if (!ToTypePtr)
2050 return false;
2051
2052 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002053 if (From->isNullPointerConstant(Context,
2054 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2055 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002056 ConvertedType = ToType;
2057 return true;
2058 }
2059
2060 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002061 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002062 if (!FromTypePtr)
2063 return false;
2064
2065 // A pointer to member of B can be converted to a pointer to member of D,
2066 // where D is derived from B (C++ 4.11p2).
2067 QualType FromClass(FromTypePtr->getClass(), 0);
2068 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002069
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002070 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2071 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2072 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002073 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2074 ToClass.getTypePtr());
2075 return true;
2076 }
2077
2078 return false;
2079}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002080
Sebastian Redl72b597d2009-01-25 19:43:20 +00002081/// CheckMemberPointerConversion - Check the member pointer conversion from the
2082/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002083/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002084/// for which IsMemberPointerConversion has already returned true. It returns
2085/// true and produces a diagnostic if there was an error, or returns false
2086/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002087bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002088 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002089 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002090 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002091 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002092 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002093 if (!FromPtrType) {
2094 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002095 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002096 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002097 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002098 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002099 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002100 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002101
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002102 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002103 assert(ToPtrType && "No member pointer cast has a target type "
2104 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002105
Sebastian Redled8f2002009-01-28 18:33:18 +00002106 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2107 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002108
Sebastian Redled8f2002009-01-28 18:33:18 +00002109 // FIXME: What about dependent types?
2110 assert(FromClass->isRecordType() && "Pointer into non-class.");
2111 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002112
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002113 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002114 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002115 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2116 assert(DerivationOkay &&
2117 "Should not have been called if derivation isn't OK.");
2118 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002119
Sebastian Redled8f2002009-01-28 18:33:18 +00002120 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2121 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002122 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2123 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2124 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2125 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002126 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002127
Douglas Gregor89ee6822009-02-28 01:32:25 +00002128 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002129 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2130 << FromClass << ToClass << QualType(VBase, 0)
2131 << From->getSourceRange();
2132 return true;
2133 }
2134
John McCall5b0829a2010-02-10 09:31:12 +00002135 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002136 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2137 Paths.front(),
2138 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002139
Anders Carlssond7923c62009-08-22 23:33:40 +00002140 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002141 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002142 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002143 return false;
2144}
2145
Douglas Gregor9a657932008-10-21 23:43:52 +00002146/// IsQualificationConversion - Determines whether the conversion from
2147/// an rvalue of type FromType to ToType is a qualification conversion
2148/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00002149bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002150Sema::IsQualificationConversion(QualType FromType, QualType ToType,
Douglas Gregor58281352011-01-27 00:58:17 +00002151 bool CStyle) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002152 FromType = Context.getCanonicalType(FromType);
2153 ToType = Context.getCanonicalType(ToType);
2154
2155 // If FromType and ToType are the same type, this is not a
2156 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002157 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002158 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002159
Douglas Gregor9a657932008-10-21 23:43:52 +00002160 // (C++ 4.4p4):
2161 // A conversion can add cv-qualifiers at levels other than the first
2162 // in multi-level pointers, subject to the following rules: [...]
2163 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002164 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002165 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002166 // Within each iteration of the loop, we check the qualifiers to
2167 // determine if this still looks like a qualification
2168 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002169 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002170 // until there are no more pointers or pointers-to-members left to
2171 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002172 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002173
2174 // -- for every j > 0, if const is in cv 1,j then const is in cv
2175 // 2,j, and similarly for volatile.
Douglas Gregor58281352011-01-27 00:58:17 +00002176 if (!CStyle && !ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00002177 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002178
Douglas Gregor9a657932008-10-21 23:43:52 +00002179 // -- if the cv 1,j and cv 2,j are different, then const is in
2180 // every cv for 0 < k < j.
Douglas Gregor58281352011-01-27 00:58:17 +00002181 if (!CStyle && FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002182 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002183 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002184
Douglas Gregor9a657932008-10-21 23:43:52 +00002185 // Keep track of whether all prior cv-qualifiers in the "to" type
2186 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002187 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00002188 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002189 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002190
2191 // We are left with FromType and ToType being the pointee types
2192 // after unwrapping the original FromType and ToType the same number
2193 // of types. If we unwrapped any pointers, and if FromType and
2194 // ToType have the same unqualified type (since we checked
2195 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002196 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002197}
2198
Douglas Gregor576e98c2009-01-30 23:27:23 +00002199/// Determines whether there is a user-defined conversion sequence
2200/// (C++ [over.ics.user]) that converts expression From to the type
2201/// ToType. If such a conversion exists, User will contain the
2202/// user-defined conversion sequence that performs such a conversion
2203/// and this routine will return true. Otherwise, this routine returns
2204/// false and User is unspecified.
2205///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002206/// \param AllowExplicit true if the conversion should consider C++0x
2207/// "explicit" conversion functions as well as non-explicit conversion
2208/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002209static OverloadingResult
2210IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2211 UserDefinedConversionSequence& User,
2212 OverloadCandidateSet& CandidateSet,
2213 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002214 // Whether we will only visit constructors.
2215 bool ConstructorsOnly = false;
2216
2217 // If the type we are conversion to is a class type, enumerate its
2218 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002219 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002220 // C++ [over.match.ctor]p1:
2221 // When objects of class type are direct-initialized (8.5), or
2222 // copy-initialized from an expression of the same or a
2223 // derived class type (8.5), overload resolution selects the
2224 // constructor. [...] For copy-initialization, the candidate
2225 // functions are all the converting constructors (12.3.1) of
2226 // that class. The argument list is the expression-list within
2227 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002228 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002229 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002230 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002231 ConstructorsOnly = true;
2232
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002233 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2234 // RequireCompleteType may have returned true due to some invalid decl
2235 // during template instantiation, but ToType may be complete enough now
2236 // to try to recover.
2237 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002238 // We're not going to find any constructors.
2239 } else if (CXXRecordDecl *ToRecordDecl
2240 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002241 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002242 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002243 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002244 NamedDecl *D = *Con;
2245 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2246
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002247 // Find the constructor (which may be a template).
2248 CXXConstructorDecl *Constructor = 0;
2249 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002250 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002251 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002252 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002253 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2254 else
John McCalla0296f72010-03-19 07:35:19 +00002255 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002256
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002257 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002258 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002259 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002260 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2261 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002262 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002263 /*SuppressUserConversions=*/
2264 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002265 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002266 // Allow one user-defined conversion when user specifies a
2267 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002268 S.AddOverloadCandidate(Constructor, FoundDecl,
2269 &From, 1, CandidateSet,
2270 /*SuppressUserConversions=*/
2271 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002272 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002273 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002274 }
2275 }
2276
Douglas Gregor5ab11652010-04-17 22:01:05 +00002277 // Enumerate conversion functions, if we're allowed to.
2278 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002279 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2280 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002281 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002282 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002283 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002284 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002285 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2286 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002287 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002288 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002289 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002290 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002291 DeclAccessPair FoundDecl = I.getPair();
2292 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002293 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2294 if (isa<UsingShadowDecl>(D))
2295 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2296
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002297 CXXConversionDecl *Conv;
2298 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002299 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2300 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002301 else
John McCallda4458e2010-03-31 01:36:47 +00002302 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002303
2304 if (AllowExplicit || !Conv->isExplicit()) {
2305 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002306 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2307 ActingContext, From, ToType,
2308 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002309 else
John McCall5c32be02010-08-24 20:38:10 +00002310 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2311 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002312 }
2313 }
2314 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002315 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002316
2317 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002318 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002319 case OR_Success:
2320 // Record the standard conversion we used and the conversion function.
2321 if (CXXConstructorDecl *Constructor
2322 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002323 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2324
John McCall5c32be02010-08-24 20:38:10 +00002325 // C++ [over.ics.user]p1:
2326 // If the user-defined conversion is specified by a
2327 // constructor (12.3.1), the initial standard conversion
2328 // sequence converts the source type to the type required by
2329 // the argument of the constructor.
2330 //
2331 QualType ThisType = Constructor->getThisType(S.Context);
2332 if (Best->Conversions[0].isEllipsis())
2333 User.EllipsisConversion = true;
2334 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002335 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002336 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002337 }
John McCall5c32be02010-08-24 20:38:10 +00002338 User.ConversionFunction = Constructor;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002339 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002340 User.After.setAsIdentityConversion();
2341 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2342 User.After.setAllToTypes(ToType);
2343 return OR_Success;
2344 } else if (CXXConversionDecl *Conversion
2345 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002346 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2347
John McCall5c32be02010-08-24 20:38:10 +00002348 // C++ [over.ics.user]p1:
2349 //
2350 // [...] If the user-defined conversion is specified by a
2351 // conversion function (12.3.2), the initial standard
2352 // conversion sequence converts the source type to the
2353 // implicit object parameter of the conversion function.
2354 User.Before = Best->Conversions[0].Standard;
2355 User.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002356 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002357 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002358
John McCall5c32be02010-08-24 20:38:10 +00002359 // C++ [over.ics.user]p2:
2360 // The second standard conversion sequence converts the
2361 // result of the user-defined conversion to the target type
2362 // for the sequence. Since an implicit conversion sequence
2363 // is an initialization, the special rules for
2364 // initialization by user-defined conversion apply when
2365 // selecting the best user-defined conversion for a
2366 // user-defined conversion sequence (see 13.3.3 and
2367 // 13.3.3.1).
2368 User.After = Best->FinalConversion;
2369 return OR_Success;
2370 } else {
2371 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002372 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002373 }
2374
John McCall5c32be02010-08-24 20:38:10 +00002375 case OR_No_Viable_Function:
2376 return OR_No_Viable_Function;
2377 case OR_Deleted:
2378 // No conversion here! We're done.
2379 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002380
John McCall5c32be02010-08-24 20:38:10 +00002381 case OR_Ambiguous:
2382 return OR_Ambiguous;
2383 }
2384
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002385 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002386}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002387
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002388bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002389Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002390 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002391 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002392 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002393 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002394 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002395 if (OvResult == OR_Ambiguous)
2396 Diag(From->getSourceRange().getBegin(),
2397 diag::err_typecheck_ambiguous_condition)
2398 << From->getType() << ToType << From->getSourceRange();
2399 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2400 Diag(From->getSourceRange().getBegin(),
2401 diag::err_typecheck_nonviable_condition)
2402 << From->getType() << ToType << From->getSourceRange();
2403 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002404 return false;
John McCall5c32be02010-08-24 20:38:10 +00002405 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002406 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002407}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002408
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002409/// CompareImplicitConversionSequences - Compare two implicit
2410/// conversion sequences to determine whether one is better than the
2411/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002412static ImplicitConversionSequence::CompareKind
2413CompareImplicitConversionSequences(Sema &S,
2414 const ImplicitConversionSequence& ICS1,
2415 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002416{
2417 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2418 // conversion sequences (as defined in 13.3.3.1)
2419 // -- a standard conversion sequence (13.3.3.1.1) is a better
2420 // conversion sequence than a user-defined conversion sequence or
2421 // an ellipsis conversion sequence, and
2422 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2423 // conversion sequence than an ellipsis conversion sequence
2424 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002425 //
John McCall0d1da222010-01-12 00:44:57 +00002426 // C++0x [over.best.ics]p10:
2427 // For the purpose of ranking implicit conversion sequences as
2428 // described in 13.3.3.2, the ambiguous conversion sequence is
2429 // treated as a user-defined sequence that is indistinguishable
2430 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002431 if (ICS1.getKindRank() < ICS2.getKindRank())
2432 return ImplicitConversionSequence::Better;
2433 else if (ICS2.getKindRank() < ICS1.getKindRank())
2434 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002435
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002436 // The following checks require both conversion sequences to be of
2437 // the same kind.
2438 if (ICS1.getKind() != ICS2.getKind())
2439 return ImplicitConversionSequence::Indistinguishable;
2440
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002441 // Two implicit conversion sequences of the same form are
2442 // indistinguishable conversion sequences unless one of the
2443 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002444 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002445 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002446 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002447 // User-defined conversion sequence U1 is a better conversion
2448 // sequence than another user-defined conversion sequence U2 if
2449 // they contain the same user-defined conversion function or
2450 // constructor and if the second standard conversion sequence of
2451 // U1 is better than the second standard conversion sequence of
2452 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002453 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002454 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002455 return CompareStandardConversionSequences(S,
2456 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002457 ICS2.UserDefined.After);
2458 }
2459
2460 return ImplicitConversionSequence::Indistinguishable;
2461}
2462
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002463static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2464 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2465 Qualifiers Quals;
2466 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002467 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002468 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002469
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002470 return Context.hasSameUnqualifiedType(T1, T2);
2471}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002472
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002473// Per 13.3.3.2p3, compare the given standard conversion sequences to
2474// determine if one is a proper subset of the other.
2475static ImplicitConversionSequence::CompareKind
2476compareStandardConversionSubsets(ASTContext &Context,
2477 const StandardConversionSequence& SCS1,
2478 const StandardConversionSequence& SCS2) {
2479 ImplicitConversionSequence::CompareKind Result
2480 = ImplicitConversionSequence::Indistinguishable;
2481
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002482 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002483 // any non-identity conversion sequence
2484 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2485 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2486 return ImplicitConversionSequence::Better;
2487 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2488 return ImplicitConversionSequence::Worse;
2489 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002490
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002491 if (SCS1.Second != SCS2.Second) {
2492 if (SCS1.Second == ICK_Identity)
2493 Result = ImplicitConversionSequence::Better;
2494 else if (SCS2.Second == ICK_Identity)
2495 Result = ImplicitConversionSequence::Worse;
2496 else
2497 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002498 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002499 return ImplicitConversionSequence::Indistinguishable;
2500
2501 if (SCS1.Third == SCS2.Third) {
2502 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2503 : ImplicitConversionSequence::Indistinguishable;
2504 }
2505
2506 if (SCS1.Third == ICK_Identity)
2507 return Result == ImplicitConversionSequence::Worse
2508 ? ImplicitConversionSequence::Indistinguishable
2509 : ImplicitConversionSequence::Better;
2510
2511 if (SCS2.Third == ICK_Identity)
2512 return Result == ImplicitConversionSequence::Better
2513 ? ImplicitConversionSequence::Indistinguishable
2514 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002515
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002516 return ImplicitConversionSequence::Indistinguishable;
2517}
2518
Douglas Gregore696ebb2011-01-26 14:52:12 +00002519/// \brief Determine whether one of the given reference bindings is better
2520/// than the other based on what kind of bindings they are.
2521static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2522 const StandardConversionSequence &SCS2) {
2523 // C++0x [over.ics.rank]p3b4:
2524 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2525 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002526 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002527 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002528 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002529 // reference*.
2530 //
2531 // FIXME: Rvalue references. We're going rogue with the above edits,
2532 // because the semantics in the current C++0x working paper (N3225 at the
2533 // time of this writing) break the standard definition of std::forward
2534 // and std::reference_wrapper when dealing with references to functions.
2535 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002536 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2537 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2538 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002539
Douglas Gregore696ebb2011-01-26 14:52:12 +00002540 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2541 SCS2.IsLvalueReference) ||
2542 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2543 !SCS2.IsLvalueReference);
2544}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002545
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002546/// CompareStandardConversionSequences - Compare two standard
2547/// conversion sequences to determine whether one is better than the
2548/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002549static ImplicitConversionSequence::CompareKind
2550CompareStandardConversionSequences(Sema &S,
2551 const StandardConversionSequence& SCS1,
2552 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002553{
2554 // Standard conversion sequence S1 is a better conversion sequence
2555 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2556
2557 // -- S1 is a proper subsequence of S2 (comparing the conversion
2558 // sequences in the canonical form defined by 13.3.3.1.1,
2559 // excluding any Lvalue Transformation; the identity conversion
2560 // sequence is considered to be a subsequence of any
2561 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002562 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002563 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002564 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002565
2566 // -- the rank of S1 is better than the rank of S2 (by the rules
2567 // defined below), or, if not that,
2568 ImplicitConversionRank Rank1 = SCS1.getRank();
2569 ImplicitConversionRank Rank2 = SCS2.getRank();
2570 if (Rank1 < Rank2)
2571 return ImplicitConversionSequence::Better;
2572 else if (Rank2 < Rank1)
2573 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002574
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002575 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2576 // are indistinguishable unless one of the following rules
2577 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002578
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002579 // A conversion that is not a conversion of a pointer, or
2580 // pointer to member, to bool is better than another conversion
2581 // that is such a conversion.
2582 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2583 return SCS2.isPointerConversionToBool()
2584 ? ImplicitConversionSequence::Better
2585 : ImplicitConversionSequence::Worse;
2586
Douglas Gregor5c407d92008-10-23 00:40:37 +00002587 // C++ [over.ics.rank]p4b2:
2588 //
2589 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002590 // conversion of B* to A* is better than conversion of B* to
2591 // void*, and conversion of A* to void* is better than conversion
2592 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002593 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002594 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002595 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002596 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002597 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2598 // Exactly one of the conversion sequences is a conversion to
2599 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002600 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2601 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002602 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2603 // Neither conversion sequence converts to a void pointer; compare
2604 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002605 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002606 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002607 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002608 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2609 // Both conversion sequences are conversions to void
2610 // pointers. Compare the source types to determine if there's an
2611 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002612 QualType FromType1 = SCS1.getFromType();
2613 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002614
2615 // Adjust the types we're converting from via the array-to-pointer
2616 // conversion, if we need to.
2617 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002618 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002619 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002620 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002621
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002622 QualType FromPointee1
2623 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2624 QualType FromPointee2
2625 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002626
John McCall5c32be02010-08-24 20:38:10 +00002627 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002628 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002629 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002630 return ImplicitConversionSequence::Worse;
2631
2632 // Objective-C++: If one interface is more specific than the
2633 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002634 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2635 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002636 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002637 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002638 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002639 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002640 return ImplicitConversionSequence::Worse;
2641 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002642 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002643
2644 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2645 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002646 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002647 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002648 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002649
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002650 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002651 // Check for a better reference binding based on the kind of bindings.
2652 if (isBetterReferenceBindingKind(SCS1, SCS2))
2653 return ImplicitConversionSequence::Better;
2654 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2655 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002656
Sebastian Redlb28b4072009-03-22 23:49:27 +00002657 // C++ [over.ics.rank]p3b4:
2658 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2659 // which the references refer are the same type except for
2660 // top-level cv-qualifiers, and the type to which the reference
2661 // initialized by S2 refers is more cv-qualified than the type
2662 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002663 QualType T1 = SCS1.getToType(2);
2664 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002665 T1 = S.Context.getCanonicalType(T1);
2666 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002667 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002668 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2669 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002670 if (UnqualT1 == UnqualT2) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00002671 // If the type is an array type, promote the element qualifiers to the
2672 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002673 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002674 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002675 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002676 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002677 if (T2.isMoreQualifiedThan(T1))
2678 return ImplicitConversionSequence::Better;
2679 else if (T1.isMoreQualifiedThan(T2))
2680 return ImplicitConversionSequence::Worse;
2681 }
2682 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002683
2684 return ImplicitConversionSequence::Indistinguishable;
2685}
2686
2687/// CompareQualificationConversions - Compares two standard conversion
2688/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002689/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2690ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002691CompareQualificationConversions(Sema &S,
2692 const StandardConversionSequence& SCS1,
2693 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002694 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002695 // -- S1 and S2 differ only in their qualification conversion and
2696 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2697 // cv-qualification signature of type T1 is a proper subset of
2698 // the cv-qualification signature of type T2, and S1 is not the
2699 // deprecated string literal array-to-pointer conversion (4.2).
2700 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2701 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2702 return ImplicitConversionSequence::Indistinguishable;
2703
2704 // FIXME: the example in the standard doesn't use a qualification
2705 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002706 QualType T1 = SCS1.getToType(2);
2707 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002708 T1 = S.Context.getCanonicalType(T1);
2709 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002710 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002711 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2712 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002713
2714 // If the types are the same, we won't learn anything by unwrapped
2715 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002716 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002717 return ImplicitConversionSequence::Indistinguishable;
2718
Chandler Carruth607f38e2009-12-29 07:16:59 +00002719 // If the type is an array type, promote the element qualifiers to the type
2720 // for comparison.
2721 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002722 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002723 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002724 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002725
Mike Stump11289f42009-09-09 15:08:12 +00002726 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002727 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002728 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002729 // Within each iteration of the loop, we check the qualifiers to
2730 // determine if this still looks like a qualification
2731 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002732 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002733 // until there are no more pointers or pointers-to-members left
2734 // to unwrap. This essentially mimics what
2735 // IsQualificationConversion does, but here we're checking for a
2736 // strict subset of qualifiers.
2737 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2738 // The qualifiers are the same, so this doesn't tell us anything
2739 // about how the sequences rank.
2740 ;
2741 else if (T2.isMoreQualifiedThan(T1)) {
2742 // T1 has fewer qualifiers, so it could be the better sequence.
2743 if (Result == ImplicitConversionSequence::Worse)
2744 // Neither has qualifiers that are a subset of the other's
2745 // qualifiers.
2746 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002747
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002748 Result = ImplicitConversionSequence::Better;
2749 } else if (T1.isMoreQualifiedThan(T2)) {
2750 // T2 has fewer qualifiers, so it could be the better sequence.
2751 if (Result == ImplicitConversionSequence::Better)
2752 // Neither has qualifiers that are a subset of the other's
2753 // qualifiers.
2754 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002755
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002756 Result = ImplicitConversionSequence::Worse;
2757 } else {
2758 // Qualifiers are disjoint.
2759 return ImplicitConversionSequence::Indistinguishable;
2760 }
2761
2762 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002763 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002764 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002765 }
2766
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002767 // Check that the winning standard conversion sequence isn't using
2768 // the deprecated string literal array to pointer conversion.
2769 switch (Result) {
2770 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002771 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002772 Result = ImplicitConversionSequence::Indistinguishable;
2773 break;
2774
2775 case ImplicitConversionSequence::Indistinguishable:
2776 break;
2777
2778 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002779 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002780 Result = ImplicitConversionSequence::Indistinguishable;
2781 break;
2782 }
2783
2784 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002785}
2786
Douglas Gregor5c407d92008-10-23 00:40:37 +00002787/// CompareDerivedToBaseConversions - Compares two standard conversion
2788/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002789/// various kinds of derived-to-base conversions (C++
2790/// [over.ics.rank]p4b3). As part of these checks, we also look at
2791/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002792ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002793CompareDerivedToBaseConversions(Sema &S,
2794 const StandardConversionSequence& SCS1,
2795 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002796 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002797 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002798 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002799 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002800
2801 // Adjust the types we're converting from via the array-to-pointer
2802 // conversion, if we need to.
2803 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002804 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002805 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002806 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002807
2808 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002809 FromType1 = S.Context.getCanonicalType(FromType1);
2810 ToType1 = S.Context.getCanonicalType(ToType1);
2811 FromType2 = S.Context.getCanonicalType(FromType2);
2812 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002813
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002814 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002815 //
2816 // If class B is derived directly or indirectly from class A and
2817 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002818 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002819 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002820 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002821 SCS2.Second == ICK_Pointer_Conversion &&
2822 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2823 FromType1->isPointerType() && FromType2->isPointerType() &&
2824 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002825 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002826 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002827 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002828 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002829 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002830 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002831 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002832 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002833
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002834 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002835 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002836 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002837 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002838 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002839 return ImplicitConversionSequence::Worse;
2840 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002841
2842 // -- conversion of B* to A* is better than conversion of C* to A*,
2843 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002844 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002845 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002846 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002847 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00002848 }
2849 } else if (SCS1.Second == ICK_Pointer_Conversion &&
2850 SCS2.Second == ICK_Pointer_Conversion) {
2851 const ObjCObjectPointerType *FromPtr1
2852 = FromType1->getAs<ObjCObjectPointerType>();
2853 const ObjCObjectPointerType *FromPtr2
2854 = FromType2->getAs<ObjCObjectPointerType>();
2855 const ObjCObjectPointerType *ToPtr1
2856 = ToType1->getAs<ObjCObjectPointerType>();
2857 const ObjCObjectPointerType *ToPtr2
2858 = ToType2->getAs<ObjCObjectPointerType>();
2859
2860 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
2861 // Apply the same conversion ranking rules for Objective-C pointer types
2862 // that we do for C++ pointers to class types. However, we employ the
2863 // Objective-C pseudo-subtyping relationship used for assignment of
2864 // Objective-C pointer types.
2865 bool FromAssignLeft
2866 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
2867 bool FromAssignRight
2868 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
2869 bool ToAssignLeft
2870 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
2871 bool ToAssignRight
2872 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
2873
2874 // A conversion to an a non-id object pointer type or qualified 'id'
2875 // type is better than a conversion to 'id'.
2876 if (ToPtr1->isObjCIdType() &&
2877 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
2878 return ImplicitConversionSequence::Worse;
2879 if (ToPtr2->isObjCIdType() &&
2880 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
2881 return ImplicitConversionSequence::Better;
2882
2883 // A conversion to a non-id object pointer type is better than a
2884 // conversion to a qualified 'id' type
2885 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
2886 return ImplicitConversionSequence::Worse;
2887 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
2888 return ImplicitConversionSequence::Better;
2889
2890 // A conversion to an a non-Class object pointer type or qualified 'Class'
2891 // type is better than a conversion to 'Class'.
2892 if (ToPtr1->isObjCClassType() &&
2893 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
2894 return ImplicitConversionSequence::Worse;
2895 if (ToPtr2->isObjCClassType() &&
2896 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
2897 return ImplicitConversionSequence::Better;
2898
2899 // A conversion to a non-Class object pointer type is better than a
2900 // conversion to a qualified 'Class' type.
2901 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
2902 return ImplicitConversionSequence::Worse;
2903 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
2904 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00002905
Douglas Gregor058d3de2011-01-31 18:51:41 +00002906 // -- "conversion of C* to B* is better than conversion of C* to A*,"
2907 if (S.Context.hasSameType(FromType1, FromType2) &&
2908 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
2909 (ToAssignLeft != ToAssignRight))
2910 return ToAssignLeft? ImplicitConversionSequence::Worse
2911 : ImplicitConversionSequence::Better;
2912
2913 // -- "conversion of B* to A* is better than conversion of C* to A*,"
2914 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
2915 (FromAssignLeft != FromAssignRight))
2916 return FromAssignLeft? ImplicitConversionSequence::Better
2917 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002918 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002919 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00002920
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002921 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002922 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2923 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2924 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002925 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002926 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002927 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002928 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002929 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002930 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002931 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002932 ToType2->getAs<MemberPointerType>();
2933 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2934 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2935 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2936 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2937 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2938 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2939 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2940 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002941 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002942 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002943 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002944 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002945 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002946 return ImplicitConversionSequence::Better;
2947 }
2948 // conversion of B::* to C::* is better than conversion of A::* to C::*
2949 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002950 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002951 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002952 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002953 return ImplicitConversionSequence::Worse;
2954 }
2955 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002956
Douglas Gregor5ab11652010-04-17 22:01:05 +00002957 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002958 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002959 // -- binding of an expression of type C to a reference of type
2960 // B& is better than binding an expression of type C to a
2961 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002962 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2963 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2964 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002965 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002966 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002967 return ImplicitConversionSequence::Worse;
2968 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002969
Douglas Gregor2fe98832008-11-03 19:09:14 +00002970 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002971 // -- binding of an expression of type B to a reference of type
2972 // A& is better than binding an expression of type C to a
2973 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002974 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2975 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2976 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002977 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002978 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002979 return ImplicitConversionSequence::Worse;
2980 }
2981 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002982
Douglas Gregor5c407d92008-10-23 00:40:37 +00002983 return ImplicitConversionSequence::Indistinguishable;
2984}
2985
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002986/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2987/// determine whether they are reference-related,
2988/// reference-compatible, reference-compatible with added
2989/// qualification, or incompatible, for use in C++ initialization by
2990/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2991/// type, and the first type (T1) is the pointee type of the reference
2992/// type being initialized.
2993Sema::ReferenceCompareResult
2994Sema::CompareReferenceRelationship(SourceLocation Loc,
2995 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002996 bool &DerivedToBase,
2997 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002998 assert(!OrigT1->isReferenceType() &&
2999 "T1 must be the pointee type of the reference type");
3000 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3001
3002 QualType T1 = Context.getCanonicalType(OrigT1);
3003 QualType T2 = Context.getCanonicalType(OrigT2);
3004 Qualifiers T1Quals, T2Quals;
3005 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3006 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3007
3008 // C++ [dcl.init.ref]p4:
3009 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3010 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3011 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003012 DerivedToBase = false;
3013 ObjCConversion = false;
3014 if (UnqualT1 == UnqualT2) {
3015 // Nothing to do.
3016 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003017 IsDerivedFrom(UnqualT2, UnqualT1))
3018 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003019 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3020 UnqualT2->isObjCObjectOrInterfaceType() &&
3021 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3022 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003023 else
3024 return Ref_Incompatible;
3025
3026 // At this point, we know that T1 and T2 are reference-related (at
3027 // least).
3028
3029 // If the type is an array type, promote the element qualifiers to the type
3030 // for comparison.
3031 if (isa<ArrayType>(T1) && T1Quals)
3032 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3033 if (isa<ArrayType>(T2) && T2Quals)
3034 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3035
3036 // C++ [dcl.init.ref]p4:
3037 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3038 // reference-related to T2 and cv1 is the same cv-qualification
3039 // as, or greater cv-qualification than, cv2. For purposes of
3040 // overload resolution, cases for which cv1 is greater
3041 // cv-qualification than cv2 are identified as
3042 // reference-compatible with added qualification (see 13.3.3.2).
3043 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
3044 return Ref_Compatible;
3045 else if (T1.isMoreQualifiedThan(T2))
3046 return Ref_Compatible_With_Added_Qualification;
3047 else
3048 return Ref_Related;
3049}
3050
Douglas Gregor836a7e82010-08-11 02:15:33 +00003051/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003052/// with DeclType. Return true if something definite is found.
3053static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003054FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3055 QualType DeclType, SourceLocation DeclLoc,
3056 Expr *Init, QualType T2, bool AllowRvalues,
3057 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003058 assert(T2->isRecordType() && "Can only find conversions of record types.");
3059 CXXRecordDecl *T2RecordDecl
3060 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3061
3062 OverloadCandidateSet CandidateSet(DeclLoc);
3063 const UnresolvedSetImpl *Conversions
3064 = T2RecordDecl->getVisibleConversionFunctions();
3065 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3066 E = Conversions->end(); I != E; ++I) {
3067 NamedDecl *D = *I;
3068 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3069 if (isa<UsingShadowDecl>(D))
3070 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3071
3072 FunctionTemplateDecl *ConvTemplate
3073 = dyn_cast<FunctionTemplateDecl>(D);
3074 CXXConversionDecl *Conv;
3075 if (ConvTemplate)
3076 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3077 else
3078 Conv = cast<CXXConversionDecl>(D);
3079
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003080 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003081 // explicit conversions, skip it.
3082 if (!AllowExplicit && Conv->isExplicit())
3083 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003084
Douglas Gregor836a7e82010-08-11 02:15:33 +00003085 if (AllowRvalues) {
3086 bool DerivedToBase = false;
3087 bool ObjCConversion = false;
3088 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003089 S.CompareReferenceRelationship(
3090 DeclLoc,
3091 Conv->getConversionType().getNonReferenceType()
3092 .getUnqualifiedType(),
3093 DeclType.getNonReferenceType().getUnqualifiedType(),
3094 DerivedToBase, ObjCConversion) ==
3095 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003096 continue;
3097 } else {
3098 // If the conversion function doesn't return a reference type,
3099 // it can't be considered for this conversion. An rvalue reference
3100 // is only acceptable if its referencee is a function type.
3101
3102 const ReferenceType *RefType =
3103 Conv->getConversionType()->getAs<ReferenceType>();
3104 if (!RefType ||
3105 (!RefType->isLValueReferenceType() &&
3106 !RefType->getPointeeType()->isFunctionType()))
3107 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003108 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003109
Douglas Gregor836a7e82010-08-11 02:15:33 +00003110 if (ConvTemplate)
3111 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003112 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003113 else
3114 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003115 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003116 }
3117
3118 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003119 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003120 case OR_Success:
3121 // C++ [over.ics.ref]p1:
3122 //
3123 // [...] If the parameter binds directly to the result of
3124 // applying a conversion function to the argument
3125 // expression, the implicit conversion sequence is a
3126 // user-defined conversion sequence (13.3.3.1.2), with the
3127 // second standard conversion sequence either an identity
3128 // conversion or, if the conversion function returns an
3129 // entity of a type that is a derived class of the parameter
3130 // type, a derived-to-base Conversion.
3131 if (!Best->FinalConversion.DirectBinding)
3132 return false;
3133
Chandler Carruth30141632011-02-25 19:41:05 +00003134 if (Best->Function)
3135 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003136 ICS.setUserDefined();
3137 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3138 ICS.UserDefined.After = Best->FinalConversion;
3139 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003140 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redld92badf2010-06-30 18:13:39 +00003141 ICS.UserDefined.EllipsisConversion = false;
3142 assert(ICS.UserDefined.After.ReferenceBinding &&
3143 ICS.UserDefined.After.DirectBinding &&
3144 "Expected a direct reference binding!");
3145 return true;
3146
3147 case OR_Ambiguous:
3148 ICS.setAmbiguous();
3149 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3150 Cand != CandidateSet.end(); ++Cand)
3151 if (Cand->Viable)
3152 ICS.Ambiguous.addConversion(Cand->Function);
3153 return true;
3154
3155 case OR_No_Viable_Function:
3156 case OR_Deleted:
3157 // There was no suitable conversion, or we found a deleted
3158 // conversion; continue with other checks.
3159 return false;
3160 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003161
Eric Christopheraba9fb22010-06-30 18:36:32 +00003162 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003163}
3164
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003165/// \brief Compute an implicit conversion sequence for reference
3166/// initialization.
3167static ImplicitConversionSequence
3168TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3169 SourceLocation DeclLoc,
3170 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003171 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003172 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3173
3174 // Most paths end in a failed conversion.
3175 ImplicitConversionSequence ICS;
3176 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3177
3178 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3179 QualType T2 = Init->getType();
3180
3181 // If the initializer is the address of an overloaded function, try
3182 // to resolve the overloaded function. If all goes well, T2 is the
3183 // type of the resulting function.
3184 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3185 DeclAccessPair Found;
3186 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3187 false, Found))
3188 T2 = Fn->getType();
3189 }
3190
3191 // Compute some basic properties of the types and the initializer.
3192 bool isRValRef = DeclType->isRValueReferenceType();
3193 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003194 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003195 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003196 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003197 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
3198 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003199
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003200
Sebastian Redld92badf2010-06-30 18:13:39 +00003201 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003202 // A reference to type "cv1 T1" is initialized by an expression
3203 // of type "cv2 T2" as follows:
3204
Sebastian Redld92badf2010-06-30 18:13:39 +00003205 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003206 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003207 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3208 // reference-compatible with "cv2 T2," or
3209 //
3210 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3211 if (InitCategory.isLValue() &&
3212 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003213 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003214 // When a parameter of reference type binds directly (8.5.3)
3215 // to an argument expression, the implicit conversion sequence
3216 // is the identity conversion, unless the argument expression
3217 // has a type that is a derived class of the parameter type,
3218 // in which case the implicit conversion sequence is a
3219 // derived-to-base Conversion (13.3.3.1).
3220 ICS.setStandard();
3221 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003222 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3223 : ObjCConversion? ICK_Compatible_Conversion
3224 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003225 ICS.Standard.Third = ICK_Identity;
3226 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3227 ICS.Standard.setToType(0, T2);
3228 ICS.Standard.setToType(1, T1);
3229 ICS.Standard.setToType(2, T1);
3230 ICS.Standard.ReferenceBinding = true;
3231 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003232 ICS.Standard.IsLvalueReference = !isRValRef;
3233 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3234 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003235 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003236 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003237
Sebastian Redld92badf2010-06-30 18:13:39 +00003238 // Nothing more to do: the inaccessibility/ambiguity check for
3239 // derived-to-base conversions is suppressed when we're
3240 // computing the implicit conversion sequence (C++
3241 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003242 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003243 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003244
Sebastian Redld92badf2010-06-30 18:13:39 +00003245 // -- has a class type (i.e., T2 is a class type), where T1 is
3246 // not reference-related to T2, and can be implicitly
3247 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3248 // is reference-compatible with "cv3 T3" 92) (this
3249 // conversion is selected by enumerating the applicable
3250 // conversion functions (13.3.1.6) and choosing the best
3251 // one through overload resolution (13.3)),
3252 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003253 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003254 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003255 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3256 Init, T2, /*AllowRvalues=*/false,
3257 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003258 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003259 }
3260 }
3261
Sebastian Redld92badf2010-06-30 18:13:39 +00003262 // -- Otherwise, the reference shall be an lvalue reference to a
3263 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003264 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003265 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003266 // We actually handle one oddity of C++ [over.ics.ref] at this
3267 // point, which is that, due to p2 (which short-circuits reference
3268 // binding by only attempting a simple conversion for non-direct
3269 // bindings) and p3's strange wording, we allow a const volatile
3270 // reference to bind to an rvalue. Hence the check for the presence
3271 // of "const" rather than checking for "const" being the only
3272 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003273 // This is also the point where rvalue references and lvalue inits no longer
3274 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003275 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003276 return ICS;
3277
Douglas Gregorf143cd52011-01-24 16:14:37 +00003278 // -- If the initializer expression
3279 //
3280 // -- is an xvalue, class prvalue, array prvalue or function
3281 // lvalue and "cv1T1" is reference-compatible with "cv2 T2", or
3282 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3283 (InitCategory.isXValue() ||
3284 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3285 (InitCategory.isLValue() && T2->isFunctionType()))) {
3286 ICS.setStandard();
3287 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003288 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003289 : ObjCConversion? ICK_Compatible_Conversion
3290 : ICK_Identity;
3291 ICS.Standard.Third = ICK_Identity;
3292 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3293 ICS.Standard.setToType(0, T2);
3294 ICS.Standard.setToType(1, T1);
3295 ICS.Standard.setToType(2, T1);
3296 ICS.Standard.ReferenceBinding = true;
3297 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3298 // binding unless we're binding to a class prvalue.
3299 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3300 // allow the use of rvalue references in C++98/03 for the benefit of
3301 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003302 ICS.Standard.DirectBinding =
3303 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003304 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003305 ICS.Standard.IsLvalueReference = !isRValRef;
3306 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003307 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003308 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003309 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003310 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003311 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003312
Douglas Gregorf143cd52011-01-24 16:14:37 +00003313 // -- has a class type (i.e., T2 is a class type), where T1 is not
3314 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003315 // an xvalue, class prvalue, or function lvalue of type
3316 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003317 // "cv3 T3",
3318 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003319 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003320 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003321 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003322 // class subobject).
3323 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003324 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003325 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3326 Init, T2, /*AllowRvalues=*/true,
3327 AllowExplicit)) {
3328 // In the second case, if the reference is an rvalue reference
3329 // and the second standard conversion sequence of the
3330 // user-defined conversion sequence includes an lvalue-to-rvalue
3331 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003332 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003333 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3334 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3335
Douglas Gregor95273c32011-01-21 16:36:05 +00003336 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003337 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003338
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003339 // -- Otherwise, a temporary of type "cv1 T1" is created and
3340 // initialized from the initializer expression using the
3341 // rules for a non-reference copy initialization (8.5). The
3342 // reference is then bound to the temporary. If T1 is
3343 // reference-related to T2, cv1 must be the same
3344 // cv-qualification as, or greater cv-qualification than,
3345 // cv2; otherwise, the program is ill-formed.
3346 if (RefRelationship == Sema::Ref_Related) {
3347 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3348 // we would be reference-compatible or reference-compatible with
3349 // added qualification. But that wasn't the case, so the reference
3350 // initialization fails.
3351 return ICS;
3352 }
3353
3354 // If at least one of the types is a class type, the types are not
3355 // related, and we aren't allowed any user conversions, the
3356 // reference binding fails. This case is important for breaking
3357 // recursion, since TryImplicitConversion below will attempt to
3358 // create a temporary through the use of a copy constructor.
3359 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3360 (T1->isRecordType() || T2->isRecordType()))
3361 return ICS;
3362
Douglas Gregorcba72b12011-01-21 05:18:22 +00003363 // If T1 is reference-related to T2 and the reference is an rvalue
3364 // reference, the initializer expression shall not be an lvalue.
3365 if (RefRelationship >= Sema::Ref_Related &&
3366 isRValRef && Init->Classify(S.Context).isLValue())
3367 return ICS;
3368
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003369 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003370 // When a parameter of reference type is not bound directly to
3371 // an argument expression, the conversion sequence is the one
3372 // required to convert the argument expression to the
3373 // underlying type of the reference according to
3374 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3375 // to copy-initializing a temporary of the underlying type with
3376 // the argument expression. Any difference in top-level
3377 // cv-qualification is subsumed by the initialization itself
3378 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003379 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3380 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003381 /*InOverloadResolution=*/false,
3382 /*CStyle=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003383
3384 // Of course, that's still a reference binding.
3385 if (ICS.isStandard()) {
3386 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003387 ICS.Standard.IsLvalueReference = !isRValRef;
3388 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3389 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003390 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003391 } else if (ICS.isUserDefined()) {
3392 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003393 ICS.Standard.IsLvalueReference = !isRValRef;
3394 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3395 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003396 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003397 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003398
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003399 return ICS;
3400}
3401
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003402/// TryCopyInitialization - Try to copy-initialize a value of type
3403/// ToType from the expression From. Return the implicit conversion
3404/// sequence required to pass this argument, which may be a bad
3405/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003406/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003407/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003408static ImplicitConversionSequence
3409TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003410 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003411 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003412 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003413 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003414 /*FIXME:*/From->getLocStart(),
3415 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003416 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003417
John McCall5c32be02010-08-24 20:38:10 +00003418 return TryImplicitConversion(S, From, ToType,
3419 SuppressUserConversions,
3420 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003421 InOverloadResolution,
3422 /*CStyle=*/false);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003423}
3424
Douglas Gregor436424c2008-11-18 23:14:02 +00003425/// TryObjectArgumentInitialization - Try to initialize the object
3426/// parameter of the given member function (@c Method) from the
3427/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003428static ImplicitConversionSequence
3429TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003430 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003431 CXXMethodDecl *Method,
3432 CXXRecordDecl *ActingContext) {
3433 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003434 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3435 // const volatile object.
3436 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3437 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003438 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003439
3440 // Set up the conversion sequence as a "bad" conversion, to allow us
3441 // to exit early.
3442 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003443
3444 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003445 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003446 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003447 FromType = PT->getPointeeType();
3448
Douglas Gregor02824322011-01-26 19:30:28 +00003449 // When we had a pointer, it's implicitly dereferenced, so we
3450 // better have an lvalue.
3451 assert(FromClassification.isLValue());
3452 }
3453
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003454 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003455
Douglas Gregor02824322011-01-26 19:30:28 +00003456 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003457 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003458 // parameter is
3459 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003460 // - "lvalue reference to cv X" for functions declared without a
3461 // ref-qualifier or with the & ref-qualifier
3462 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003463 // ref-qualifier
3464 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003465 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003466 // cv-qualification on the member function declaration.
3467 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003468 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003469 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003470 // (C++ [over.match.funcs]p5). We perform a simplified version of
3471 // reference binding here, that allows class rvalues to bind to
3472 // non-constant references.
3473
Douglas Gregor02824322011-01-26 19:30:28 +00003474 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003475 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003476 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003477 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003478 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003479 ICS.setBad(BadConversionSequence::bad_qualifiers,
3480 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003481 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003482 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003483
3484 // Check that we have either the same type or a derived type. It
3485 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003486 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003487 ImplicitConversionKind SecondKind;
3488 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3489 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003490 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003491 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003492 else {
John McCall65eb8792010-02-25 01:37:24 +00003493 ICS.setBad(BadConversionSequence::unrelated_class,
3494 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003495 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003496 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003497
Douglas Gregor02824322011-01-26 19:30:28 +00003498 // Check the ref-qualifier.
3499 switch (Method->getRefQualifier()) {
3500 case RQ_None:
3501 // Do nothing; we don't care about lvalueness or rvalueness.
3502 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003503
Douglas Gregor02824322011-01-26 19:30:28 +00003504 case RQ_LValue:
3505 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3506 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003507 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003508 ImplicitParamType);
3509 return ICS;
3510 }
3511 break;
3512
3513 case RQ_RValue:
3514 if (!FromClassification.isRValue()) {
3515 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003516 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003517 ImplicitParamType);
3518 return ICS;
3519 }
3520 break;
3521 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003522
Douglas Gregor436424c2008-11-18 23:14:02 +00003523 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003524 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003525 ICS.Standard.setAsIdentityConversion();
3526 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003527 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003528 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003529 ICS.Standard.ReferenceBinding = true;
3530 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003531 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003532 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003533 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3534 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3535 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003536 return ICS;
3537}
3538
3539/// PerformObjectArgumentInitialization - Perform initialization of
3540/// the implicit object parameter for the given Method with the given
3541/// expression.
John Wiegley01296292011-04-08 18:41:53 +00003542ExprResult
3543Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003544 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003545 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003546 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003547 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003548 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003549 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003550
Douglas Gregor02824322011-01-26 19:30:28 +00003551 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003552 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003553 FromRecordType = PT->getPointeeType();
3554 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003555 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003556 } else {
3557 FromRecordType = From->getType();
3558 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003559 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003560 }
3561
John McCall6e9f8f62009-12-03 04:06:58 +00003562 // Note that we always use the true parent context when performing
3563 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003564 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003565 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3566 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003567 if (ICS.isBad()) {
3568 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3569 Qualifiers FromQs = FromRecordType.getQualifiers();
3570 Qualifiers ToQs = DestType.getQualifiers();
3571 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3572 if (CVR) {
3573 Diag(From->getSourceRange().getBegin(),
3574 diag::err_member_function_call_bad_cvr)
3575 << Method->getDeclName() << FromRecordType << (CVR - 1)
3576 << From->getSourceRange();
3577 Diag(Method->getLocation(), diag::note_previous_decl)
3578 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00003579 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003580 }
3581 }
3582
Douglas Gregor436424c2008-11-18 23:14:02 +00003583 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003584 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003585 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003586 }
Mike Stump11289f42009-09-09 15:08:12 +00003587
John Wiegley01296292011-04-08 18:41:53 +00003588 if (ICS.Standard.Second == ICK_Derived_To_Base) {
3589 ExprResult FromRes =
3590 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3591 if (FromRes.isInvalid())
3592 return ExprError();
3593 From = FromRes.take();
3594 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003595
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003596 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00003597 From = ImpCastExprToType(From, DestType, CK_NoOp,
3598 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3599 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00003600}
3601
Douglas Gregor5fb53972009-01-14 15:45:31 +00003602/// TryContextuallyConvertToBool - Attempt to contextually convert the
3603/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003604static ImplicitConversionSequence
3605TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003606 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003607 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003608 // FIXME: Are these flags correct?
3609 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003610 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003611 /*InOverloadResolution=*/false,
3612 /*CStyle=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003613}
3614
3615/// PerformContextuallyConvertToBool - Perform a contextual conversion
3616/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00003617ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00003618 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003619 if (!ICS.isBad())
3620 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003621
Fariborz Jahanian76197412009-11-18 18:26:29 +00003622 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003623 return Diag(From->getSourceRange().getBegin(),
3624 diag::err_typecheck_bool_condition)
3625 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003626 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00003627}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003628
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003629/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3630/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003631static ImplicitConversionSequence
3632TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3633 QualType Ty = S.Context.getObjCIdType();
3634 return TryImplicitConversion(S, From, Ty,
3635 // FIXME: Are these flags correct?
3636 /*SuppressUserConversions=*/false,
3637 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003638 /*InOverloadResolution=*/false,
3639 /*CStyle=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003640}
John McCall5c32be02010-08-24 20:38:10 +00003641
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003642/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3643/// of the expression From to 'id'.
John Wiegley01296292011-04-08 18:41:53 +00003644ExprResult Sema::PerformContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003645 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003646 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003647 if (!ICS.isBad())
3648 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00003649 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003650}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003651
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003652/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003653/// enumeration type.
3654///
3655/// This routine will attempt to convert an expression of class type to an
3656/// integral or enumeration type, if that class type only has a single
3657/// conversion to an integral or enumeration type.
3658///
Douglas Gregor4799d032010-06-30 00:20:43 +00003659/// \param Loc The source location of the construct that requires the
3660/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003661///
Douglas Gregor4799d032010-06-30 00:20:43 +00003662/// \param FromE The expression we're converting from.
3663///
3664/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3665/// have integral or enumeration type.
3666///
3667/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3668/// incomplete class type.
3669///
3670/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3671/// explicit conversion function (because no implicit conversion functions
3672/// were available). This is a recovery mode.
3673///
3674/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3675/// showing which conversion was picked.
3676///
3677/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3678/// conversion function that could convert to integral or enumeration type.
3679///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003680/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00003681/// usable conversion function.
3682///
3683/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3684/// function, which may be an extension in this case.
3685///
3686/// \returns The expression, converted to an integral or enumeration type if
3687/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003688ExprResult
John McCallb268a282010-08-23 23:25:46 +00003689Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003690 const PartialDiagnostic &NotIntDiag,
3691 const PartialDiagnostic &IncompleteDiag,
3692 const PartialDiagnostic &ExplicitConvDiag,
3693 const PartialDiagnostic &ExplicitConvNote,
3694 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003695 const PartialDiagnostic &AmbigNote,
3696 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003697 // We can't perform any more checking for type-dependent expressions.
3698 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003699 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003700
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003701 // If the expression already has integral or enumeration type, we're golden.
3702 QualType T = From->getType();
3703 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003704 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003705
3706 // FIXME: Check for missing '()' if T is a function type?
3707
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003708 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003709 // expression of integral or enumeration type.
3710 const RecordType *RecordTy = T->getAs<RecordType>();
3711 if (!RecordTy || !getLangOptions().CPlusPlus) {
3712 Diag(Loc, NotIntDiag)
3713 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003714 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003715 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003716
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003717 // We must have a complete class type.
3718 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003719 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003720
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003721 // Look for a conversion to an integral or enumeration type.
3722 UnresolvedSet<4> ViableConversions;
3723 UnresolvedSet<4> ExplicitConversions;
3724 const UnresolvedSetImpl *Conversions
3725 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003726
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003727 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003728 E = Conversions->end();
3729 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003730 ++I) {
3731 if (CXXConversionDecl *Conversion
3732 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3733 if (Conversion->getConversionType().getNonReferenceType()
3734 ->isIntegralOrEnumerationType()) {
3735 if (Conversion->isExplicit())
3736 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3737 else
3738 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3739 }
3740 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003741
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003742 switch (ViableConversions.size()) {
3743 case 0:
3744 if (ExplicitConversions.size() == 1) {
3745 DeclAccessPair Found = ExplicitConversions[0];
3746 CXXConversionDecl *Conversion
3747 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003748
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003749 // The user probably meant to invoke the given explicit
3750 // conversion; use it.
3751 QualType ConvTy
3752 = Conversion->getConversionType().getNonReferenceType();
3753 std::string TypeStr;
3754 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003755
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003756 Diag(Loc, ExplicitConvDiag)
3757 << T << ConvTy
3758 << FixItHint::CreateInsertion(From->getLocStart(),
3759 "static_cast<" + TypeStr + ">(")
3760 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3761 ")");
3762 Diag(Conversion->getLocation(), ExplicitConvNote)
3763 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003764
3765 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003766 // explicit conversion function.
3767 if (isSFINAEContext())
3768 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003769
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003770 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00003771 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3772 if (Result.isInvalid())
3773 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003774
Douglas Gregor668443e2011-01-20 00:18:04 +00003775 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003776 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003777
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003778 // We'll complain below about a non-integral condition type.
3779 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003780
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003781 case 1: {
3782 // Apply this conversion.
3783 DeclAccessPair Found = ViableConversions[0];
3784 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003785
Douglas Gregor4799d032010-06-30 00:20:43 +00003786 CXXConversionDecl *Conversion
3787 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3788 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003789 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00003790 if (ConvDiag.getDiagID()) {
3791 if (isSFINAEContext())
3792 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003793
Douglas Gregor4799d032010-06-30 00:20:43 +00003794 Diag(Loc, ConvDiag)
3795 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3796 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003797
Douglas Gregor668443e2011-01-20 00:18:04 +00003798 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003799 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00003800 if (Result.isInvalid())
3801 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003802
Douglas Gregor668443e2011-01-20 00:18:04 +00003803 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003804 break;
3805 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003806
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003807 default:
3808 Diag(Loc, AmbigDiag)
3809 << T << From->getSourceRange();
3810 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3811 CXXConversionDecl *Conv
3812 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3813 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3814 Diag(Conv->getLocation(), AmbigNote)
3815 << ConvTy->isEnumeralType() << ConvTy;
3816 }
John McCallb268a282010-08-23 23:25:46 +00003817 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003818 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003819
Douglas Gregor5823da32010-06-29 23:25:20 +00003820 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003821 Diag(Loc, NotIntDiag)
3822 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003823
John McCallb268a282010-08-23 23:25:46 +00003824 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003825}
3826
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003827/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003828/// candidate functions, using the given function call arguments. If
3829/// @p SuppressUserConversions, then don't allow user-defined
3830/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003831///
3832/// \para PartialOverloading true if we are performing "partial" overloading
3833/// based on an incomplete set of function arguments. This feature is used by
3834/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003835void
3836Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003837 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003838 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003839 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003840 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003841 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003842 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003843 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003844 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003845 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003846 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003847
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003848 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003849 if (!isa<CXXConstructorDecl>(Method)) {
3850 // If we get here, it's because we're calling a member function
3851 // that is named without a member access expression (e.g.,
3852 // "this->f") that was either written explicitly or created
3853 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003854 // function, e.g., X::f(). We use an empty type for the implied
3855 // object argument (C++ [over.call.func]p3), and the acting context
3856 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003857 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003858 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00003859 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003860 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003861 return;
3862 }
3863 // We treat a constructor like a non-member function, since its object
3864 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003865 }
3866
Douglas Gregorff7028a2009-11-13 23:59:09 +00003867 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003868 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003869
Douglas Gregor27381f32009-11-23 12:27:39 +00003870 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003871 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003872
Douglas Gregorffe14e32009-11-14 01:20:54 +00003873 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3874 // C++ [class.copy]p3:
3875 // A member function template is never instantiated to perform the copy
3876 // of a class object to an object of its class type.
3877 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003878 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003879 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003880 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3881 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003882 return;
3883 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003884
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003885 // Add this candidate
3886 CandidateSet.push_back(OverloadCandidate());
3887 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003888 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003889 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003890 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003891 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003892 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003893 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003894
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003895 unsigned NumArgsInProto = Proto->getNumArgs();
3896
3897 // (C++ 13.3.2p2): A candidate function having fewer than m
3898 // parameters is viable only if it has an ellipsis in its parameter
3899 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003900 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00003901 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003902 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003903 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003904 return;
3905 }
3906
3907 // (C++ 13.3.2p2): A candidate function having more than m parameters
3908 // is viable only if the (m+1)st parameter has a default argument
3909 // (8.3.6). For the purposes of overload resolution, the
3910 // parameter list is truncated on the right, so that there are
3911 // exactly m parameters.
3912 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003913 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003914 // Not enough arguments.
3915 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003916 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003917 return;
3918 }
3919
3920 // Determine the implicit conversion sequences for each of the
3921 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003922 Candidate.Conversions.resize(NumArgs);
3923 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3924 if (ArgIdx < NumArgsInProto) {
3925 // (C++ 13.3.2p3): for F to be a viable function, there shall
3926 // exist for each argument an implicit conversion sequence
3927 // (13.3.3.1) that converts that argument to the corresponding
3928 // parameter of F.
3929 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003930 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003931 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003932 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003933 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003934 if (Candidate.Conversions[ArgIdx].isBad()) {
3935 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003936 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003937 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003938 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003939 } else {
3940 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3941 // argument for which there is no corresponding parameter is
3942 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003943 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003944 }
3945 }
3946}
3947
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003948/// \brief Add all of the function declarations in the given function set to
3949/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003950void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003951 Expr **Args, unsigned NumArgs,
3952 OverloadCandidateSet& CandidateSet,
3953 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003954 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003955 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3956 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003957 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003958 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003959 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00003960 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003961 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003962 CandidateSet, SuppressUserConversions);
3963 else
John McCalla0296f72010-03-19 07:35:19 +00003964 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003965 SuppressUserConversions);
3966 } else {
John McCalla0296f72010-03-19 07:35:19 +00003967 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003968 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3969 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003970 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003971 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003972 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003973 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00003974 Args[0]->Classify(Context),
3975 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003976 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003977 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003978 else
John McCalla0296f72010-03-19 07:35:19 +00003979 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003980 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003981 Args, NumArgs, CandidateSet,
3982 SuppressUserConversions);
3983 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003984 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003985}
3986
John McCallf0f1cf02009-11-17 07:50:12 +00003987/// AddMethodCandidate - Adds a named decl (which is some kind of
3988/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003989void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003990 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00003991 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00003992 Expr **Args, unsigned NumArgs,
3993 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003994 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003995 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003996 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003997
3998 if (isa<UsingShadowDecl>(Decl))
3999 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004000
John McCallf0f1cf02009-11-17 07:50:12 +00004001 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4002 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4003 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004004 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4005 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004006 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004007 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004008 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004009 } else {
John McCalla0296f72010-03-19 07:35:19 +00004010 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004011 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004012 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004013 }
4014}
4015
Douglas Gregor436424c2008-11-18 23:14:02 +00004016/// AddMethodCandidate - Adds the given C++ member function to the set
4017/// of candidate functions, using the given function call arguments
4018/// and the object argument (@c Object). For example, in a call
4019/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4020/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4021/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004022/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004023void
John McCalla0296f72010-03-19 07:35:19 +00004024Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004025 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004026 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004027 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004028 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004029 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004030 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004031 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004032 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004033 assert(!isa<CXXConstructorDecl>(Method) &&
4034 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004035
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004036 if (!CandidateSet.isNewCandidate(Method))
4037 return;
4038
Douglas Gregor27381f32009-11-23 12:27:39 +00004039 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004040 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004041
Douglas Gregor436424c2008-11-18 23:14:02 +00004042 // Add this candidate
4043 CandidateSet.push_back(OverloadCandidate());
4044 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004045 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004046 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004047 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004048 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004049 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004050
4051 unsigned NumArgsInProto = Proto->getNumArgs();
4052
4053 // (C++ 13.3.2p2): A candidate function having fewer than m
4054 // parameters is viable only if it has an ellipsis in its parameter
4055 // list (8.3.5).
4056 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4057 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004058 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004059 return;
4060 }
4061
4062 // (C++ 13.3.2p2): A candidate function having more than m parameters
4063 // is viable only if the (m+1)st parameter has a default argument
4064 // (8.3.6). For the purposes of overload resolution, the
4065 // parameter list is truncated on the right, so that there are
4066 // exactly m parameters.
4067 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4068 if (NumArgs < MinRequiredArgs) {
4069 // Not enough arguments.
4070 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004071 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004072 return;
4073 }
4074
4075 Candidate.Viable = true;
4076 Candidate.Conversions.resize(NumArgs + 1);
4077
John McCall6e9f8f62009-12-03 04:06:58 +00004078 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004079 // The implicit object argument is ignored.
4080 Candidate.IgnoreObjectArgument = true;
4081 else {
4082 // Determine the implicit conversion sequence for the object
4083 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004084 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004085 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4086 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004087 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004088 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004089 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004090 return;
4091 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004092 }
4093
4094 // Determine the implicit conversion sequences for each of the
4095 // arguments.
4096 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4097 if (ArgIdx < NumArgsInProto) {
4098 // (C++ 13.3.2p3): for F to be a viable function, there shall
4099 // exist for each argument an implicit conversion sequence
4100 // (13.3.3.1) that converts that argument to the corresponding
4101 // parameter of F.
4102 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004103 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004104 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004105 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00004106 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00004107 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004108 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004109 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004110 break;
4111 }
4112 } else {
4113 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4114 // argument for which there is no corresponding parameter is
4115 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004116 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004117 }
4118 }
4119}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004120
Douglas Gregor97628d62009-08-21 00:16:32 +00004121/// \brief Add a C++ member function template as a candidate to the candidate
4122/// set, using template argument deduction to produce an appropriate member
4123/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004124void
Douglas Gregor97628d62009-08-21 00:16:32 +00004125Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004126 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004127 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004128 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004129 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004130 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004131 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004132 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004133 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004134 if (!CandidateSet.isNewCandidate(MethodTmpl))
4135 return;
4136
Douglas Gregor97628d62009-08-21 00:16:32 +00004137 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004138 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004139 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004140 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004141 // candidate functions in the usual way.113) A given name can refer to one
4142 // or more function templates and also to a set of overloaded non-template
4143 // functions. In such a case, the candidate functions generated from each
4144 // function template are combined with the set of non-template candidate
4145 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004146 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004147 FunctionDecl *Specialization = 0;
4148 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004149 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004150 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004151 CandidateSet.push_back(OverloadCandidate());
4152 OverloadCandidate &Candidate = CandidateSet.back();
4153 Candidate.FoundDecl = FoundDecl;
4154 Candidate.Function = MethodTmpl->getTemplatedDecl();
4155 Candidate.Viable = false;
4156 Candidate.FailureKind = ovl_fail_bad_deduction;
4157 Candidate.IsSurrogate = false;
4158 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004159 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004160 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004161 Info);
4162 return;
4163 }
Mike Stump11289f42009-09-09 15:08:12 +00004164
Douglas Gregor97628d62009-08-21 00:16:32 +00004165 // Add the function template specialization produced by template argument
4166 // deduction as a candidate.
4167 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004168 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004169 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004170 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004171 ActingContext, ObjectType, ObjectClassification,
4172 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004173}
4174
Douglas Gregor05155d82009-08-21 23:19:43 +00004175/// \brief Add a C++ function template specialization as a candidate
4176/// in the candidate set, using template argument deduction to produce
4177/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004178void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004179Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004180 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004181 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004182 Expr **Args, unsigned NumArgs,
4183 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004184 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004185 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4186 return;
4187
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004188 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004189 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004190 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004191 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004192 // candidate functions in the usual way.113) A given name can refer to one
4193 // or more function templates and also to a set of overloaded non-template
4194 // functions. In such a case, the candidate functions generated from each
4195 // function template are combined with the set of non-template candidate
4196 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004197 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004198 FunctionDecl *Specialization = 0;
4199 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004200 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004201 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004202 CandidateSet.push_back(OverloadCandidate());
4203 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004204 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004205 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4206 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004207 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004208 Candidate.IsSurrogate = false;
4209 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004210 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004211 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004212 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004213 return;
4214 }
Mike Stump11289f42009-09-09 15:08:12 +00004215
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004216 // Add the function template specialization produced by template argument
4217 // deduction as a candidate.
4218 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004219 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004220 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004221}
Mike Stump11289f42009-09-09 15:08:12 +00004222
Douglas Gregora1f013e2008-11-07 22:36:19 +00004223/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004224/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004225/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004226/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004227/// (which may or may not be the same type as the type that the
4228/// conversion function produces).
4229void
4230Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004231 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004232 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004233 Expr *From, QualType ToType,
4234 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004235 assert(!Conversion->getDescribedFunctionTemplate() &&
4236 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004237 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004238 if (!CandidateSet.isNewCandidate(Conversion))
4239 return;
4240
Douglas Gregor27381f32009-11-23 12:27:39 +00004241 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004242 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004243
Douglas Gregora1f013e2008-11-07 22:36:19 +00004244 // Add this candidate
4245 CandidateSet.push_back(OverloadCandidate());
4246 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004247 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004248 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004249 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004250 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004251 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004252 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004253 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004254 Candidate.Viable = true;
4255 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004256 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004257
Douglas Gregor6affc782010-08-19 15:37:02 +00004258 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004259 // For conversion functions, the function is considered to be a member of
4260 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004261 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004262 //
4263 // Determine the implicit conversion sequence for the implicit
4264 // object parameter.
4265 QualType ImplicitParamType = From->getType();
4266 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4267 ImplicitParamType = FromPtrType->getPointeeType();
4268 CXXRecordDecl *ConversionContext
4269 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004270
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004271 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004272 = TryObjectArgumentInitialization(*this, From->getType(),
4273 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004274 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275
John McCall0d1da222010-01-12 00:44:57 +00004276 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004277 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004278 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004279 return;
4280 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004281
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004282 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004283 // derived to base as such conversions are given Conversion Rank. They only
4284 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4285 QualType FromCanon
4286 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4287 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4288 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4289 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004290 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004291 return;
4292 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004293
Douglas Gregora1f013e2008-11-07 22:36:19 +00004294 // To determine what the conversion from the result of calling the
4295 // conversion function to the type we're eventually trying to
4296 // convert to (ToType), we need to synthesize a call to the
4297 // conversion function and attempt copy initialization from it. This
4298 // makes sure that we get the right semantics with respect to
4299 // lvalues/rvalues and the type. Fortunately, we can allocate this
4300 // call on the stack and we don't need its arguments to be
4301 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004302 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004303 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004304 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4305 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004306 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004307 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004308
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004309 QualType CallResultType
4310 = Conversion->getConversionType().getNonLValueExprType(Context);
4311 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
4312 Candidate.Viable = false;
4313 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4314 return;
4315 }
4316
John McCall7decc9e2010-11-18 06:31:45 +00004317 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
4318
Mike Stump11289f42009-09-09 15:08:12 +00004319 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004320 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4321 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00004322 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004323 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004324 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004325 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004326 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00004327 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004328
John McCall0d1da222010-01-12 00:44:57 +00004329 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004330 case ImplicitConversionSequence::StandardConversion:
4331 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004332
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004333 // C++ [over.ics.user]p3:
4334 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004335 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004336 // shall have exact match rank.
4337 if (Conversion->getPrimaryTemplate() &&
4338 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4339 Candidate.Viable = false;
4340 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4341 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004342
Douglas Gregorcba72b12011-01-21 05:18:22 +00004343 // C++0x [dcl.init.ref]p5:
4344 // In the second case, if the reference is an rvalue reference and
4345 // the second standard conversion sequence of the user-defined
4346 // conversion sequence includes an lvalue-to-rvalue conversion, the
4347 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004348 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004349 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4350 Candidate.Viable = false;
4351 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4352 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004353 break;
4354
4355 case ImplicitConversionSequence::BadConversion:
4356 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004357 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004358 break;
4359
4360 default:
Mike Stump11289f42009-09-09 15:08:12 +00004361 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004362 "Can only end up with a standard conversion sequence or failure");
4363 }
4364}
4365
Douglas Gregor05155d82009-08-21 23:19:43 +00004366/// \brief Adds a conversion function template specialization
4367/// candidate to the overload set, using template argument deduction
4368/// to deduce the template arguments of the conversion function
4369/// template from the type that we are converting to (C++
4370/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004371void
Douglas Gregor05155d82009-08-21 23:19:43 +00004372Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004373 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004374 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004375 Expr *From, QualType ToType,
4376 OverloadCandidateSet &CandidateSet) {
4377 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4378 "Only conversion function templates permitted here");
4379
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004380 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4381 return;
4382
John McCallbc077cf2010-02-08 23:07:23 +00004383 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004384 CXXConversionDecl *Specialization = 0;
4385 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004386 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004387 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004388 CandidateSet.push_back(OverloadCandidate());
4389 OverloadCandidate &Candidate = CandidateSet.back();
4390 Candidate.FoundDecl = FoundDecl;
4391 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4392 Candidate.Viable = false;
4393 Candidate.FailureKind = ovl_fail_bad_deduction;
4394 Candidate.IsSurrogate = false;
4395 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004396 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004397 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004398 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004399 return;
4400 }
Mike Stump11289f42009-09-09 15:08:12 +00004401
Douglas Gregor05155d82009-08-21 23:19:43 +00004402 // Add the conversion function template specialization produced by
4403 // template argument deduction as a candidate.
4404 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004405 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004406 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004407}
4408
Douglas Gregorab7897a2008-11-19 22:57:39 +00004409/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4410/// converts the given @c Object to a function pointer via the
4411/// conversion function @c Conversion, and then attempts to call it
4412/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4413/// the type of function that we'll eventually be calling.
4414void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004415 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004416 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004417 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004418 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004419 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004420 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004421 if (!CandidateSet.isNewCandidate(Conversion))
4422 return;
4423
Douglas Gregor27381f32009-11-23 12:27:39 +00004424 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004425 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004426
Douglas Gregorab7897a2008-11-19 22:57:39 +00004427 CandidateSet.push_back(OverloadCandidate());
4428 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004429 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004430 Candidate.Function = 0;
4431 Candidate.Surrogate = Conversion;
4432 Candidate.Viable = true;
4433 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004434 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004435 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004436 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004437
4438 // Determine the implicit conversion sequence for the implicit
4439 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004440 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004441 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004442 Object->Classify(Context),
4443 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004444 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004445 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004446 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004447 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004448 return;
4449 }
4450
4451 // The first conversion is actually a user-defined conversion whose
4452 // first conversion is ObjectInit's standard conversion (which is
4453 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004454 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004455 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004456 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004457 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004458 Candidate.Conversions[0].UserDefined.FoundConversionFunction
Douglas Gregor2bbfba02011-01-20 01:32:05 +00004459 = FoundDecl.getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004460 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004461 = Candidate.Conversions[0].UserDefined.Before;
4462 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4463
Mike Stump11289f42009-09-09 15:08:12 +00004464 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004465 unsigned NumArgsInProto = Proto->getNumArgs();
4466
4467 // (C++ 13.3.2p2): A candidate function having fewer than m
4468 // parameters is viable only if it has an ellipsis in its parameter
4469 // list (8.3.5).
4470 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4471 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004472 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004473 return;
4474 }
4475
4476 // Function types don't have any default arguments, so just check if
4477 // we have enough arguments.
4478 if (NumArgs < NumArgsInProto) {
4479 // Not enough arguments.
4480 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004481 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004482 return;
4483 }
4484
4485 // Determine the implicit conversion sequences for each of the
4486 // arguments.
4487 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4488 if (ArgIdx < NumArgsInProto) {
4489 // (C++ 13.3.2p3): for F to be a viable function, there shall
4490 // exist for each argument an implicit conversion sequence
4491 // (13.3.3.1) that converts that argument to the corresponding
4492 // parameter of F.
4493 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004494 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004495 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004496 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004497 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004498 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004499 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004500 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004501 break;
4502 }
4503 } else {
4504 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4505 // argument for which there is no corresponding parameter is
4506 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004507 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004508 }
4509 }
4510}
4511
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004512/// \brief Add overload candidates for overloaded operators that are
4513/// member functions.
4514///
4515/// Add the overloaded operator candidates that are member functions
4516/// for the operator Op that was used in an operator expression such
4517/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4518/// CandidateSet will store the added overload candidates. (C++
4519/// [over.match.oper]).
4520void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4521 SourceLocation OpLoc,
4522 Expr **Args, unsigned NumArgs,
4523 OverloadCandidateSet& CandidateSet,
4524 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004525 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4526
4527 // C++ [over.match.oper]p3:
4528 // For a unary operator @ with an operand of a type whose
4529 // cv-unqualified version is T1, and for a binary operator @ with
4530 // a left operand of a type whose cv-unqualified version is T1 and
4531 // a right operand of a type whose cv-unqualified version is T2,
4532 // three sets of candidate functions, designated member
4533 // candidates, non-member candidates and built-in candidates, are
4534 // constructed as follows:
4535 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004536
4537 // -- If T1 is a class type, the set of member candidates is the
4538 // result of the qualified lookup of T1::operator@
4539 // (13.3.1.1.1); otherwise, the set of member candidates is
4540 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004541 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004542 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004543 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004544 return;
Mike Stump11289f42009-09-09 15:08:12 +00004545
John McCall27b18f82009-11-17 02:14:36 +00004546 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4547 LookupQualifiedName(Operators, T1Rec->getDecl());
4548 Operators.suppressDiagnostics();
4549
Mike Stump11289f42009-09-09 15:08:12 +00004550 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004551 OperEnd = Operators.end();
4552 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004553 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004554 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004555 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00004556 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004557 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004558 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004559}
4560
Douglas Gregora11693b2008-11-12 17:17:38 +00004561/// AddBuiltinCandidate - Add a candidate for a built-in
4562/// operator. ResultTy and ParamTys are the result and parameter types
4563/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004564/// arguments being passed to the candidate. IsAssignmentOperator
4565/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004566/// operator. NumContextualBoolArguments is the number of arguments
4567/// (at the beginning of the argument list) that will be contextually
4568/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004569void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004570 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004571 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004572 bool IsAssignmentOperator,
4573 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004574 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004575 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004576
Douglas Gregora11693b2008-11-12 17:17:38 +00004577 // Add this candidate
4578 CandidateSet.push_back(OverloadCandidate());
4579 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004580 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004581 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004582 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004583 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004584 Candidate.BuiltinTypes.ResultTy = ResultTy;
4585 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4586 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4587
4588 // Determine the implicit conversion sequences for each of the
4589 // arguments.
4590 Candidate.Viable = true;
4591 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004592 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004593 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004594 // C++ [over.match.oper]p4:
4595 // For the built-in assignment operators, conversions of the
4596 // left operand are restricted as follows:
4597 // -- no temporaries are introduced to hold the left operand, and
4598 // -- no user-defined conversions are applied to the left
4599 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004600 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004601 //
4602 // We block these conversions by turning off user-defined
4603 // conversions, since that is the only way that initialization of
4604 // a reference to a non-class type can occur from something that
4605 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004606 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004607 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004608 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004609 Candidate.Conversions[ArgIdx]
4610 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004611 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004612 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004613 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004614 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004615 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004616 }
John McCall0d1da222010-01-12 00:44:57 +00004617 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004618 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004619 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004620 break;
4621 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004622 }
4623}
4624
4625/// BuiltinCandidateTypeSet - A set of types that will be used for the
4626/// candidate operator functions for built-in operators (C++
4627/// [over.built]). The types are separated into pointer types and
4628/// enumeration types.
4629class BuiltinCandidateTypeSet {
4630 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004631 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004632
4633 /// PointerTypes - The set of pointer types that will be used in the
4634 /// built-in candidates.
4635 TypeSet PointerTypes;
4636
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004637 /// MemberPointerTypes - The set of member pointer types that will be
4638 /// used in the built-in candidates.
4639 TypeSet MemberPointerTypes;
4640
Douglas Gregora11693b2008-11-12 17:17:38 +00004641 /// EnumerationTypes - The set of enumeration types that will be
4642 /// used in the built-in candidates.
4643 TypeSet EnumerationTypes;
4644
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004645 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004646 /// candidates.
4647 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004648
4649 /// \brief A flag indicating non-record types are viable candidates
4650 bool HasNonRecordTypes;
4651
4652 /// \brief A flag indicating whether either arithmetic or enumeration types
4653 /// were present in the candidate set.
4654 bool HasArithmeticOrEnumeralTypes;
4655
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004656 /// Sema - The semantic analysis instance where we are building the
4657 /// candidate type set.
4658 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004659
Douglas Gregora11693b2008-11-12 17:17:38 +00004660 /// Context - The AST context in which we will build the type sets.
4661 ASTContext &Context;
4662
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004663 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4664 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004665 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004666
4667public:
4668 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004669 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004670
Mike Stump11289f42009-09-09 15:08:12 +00004671 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004672 : HasNonRecordTypes(false),
4673 HasArithmeticOrEnumeralTypes(false),
4674 SemaRef(SemaRef),
4675 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004676
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004677 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004678 SourceLocation Loc,
4679 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004680 bool AllowExplicitConversions,
4681 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004682
4683 /// pointer_begin - First pointer type found;
4684 iterator pointer_begin() { return PointerTypes.begin(); }
4685
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004686 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004687 iterator pointer_end() { return PointerTypes.end(); }
4688
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004689 /// member_pointer_begin - First member pointer type found;
4690 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4691
4692 /// member_pointer_end - Past the last member pointer type found;
4693 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4694
Douglas Gregora11693b2008-11-12 17:17:38 +00004695 /// enumeration_begin - First enumeration type found;
4696 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4697
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004698 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004699 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004700
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004701 iterator vector_begin() { return VectorTypes.begin(); }
4702 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00004703
4704 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4705 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregora11693b2008-11-12 17:17:38 +00004706};
4707
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004708/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004709/// the set of pointer types along with any more-qualified variants of
4710/// that type. For example, if @p Ty is "int const *", this routine
4711/// will add "int const *", "int const volatile *", "int const
4712/// restrict *", and "int const volatile restrict *" to the set of
4713/// pointer types. Returns true if the add of @p Ty itself succeeded,
4714/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004715///
4716/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004717bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004718BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4719 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004720
Douglas Gregora11693b2008-11-12 17:17:38 +00004721 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004722 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004723 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004724
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004725 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004726 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004727 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004728 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004729 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004730 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004731 buildObjCPtr = true;
4732 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004733 else
4734 assert(false && "type was not a pointer type!");
4735 }
4736 else
4737 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004738
Sebastian Redl4990a632009-11-18 20:39:26 +00004739 // Don't add qualified variants of arrays. For one, they're not allowed
4740 // (the qualifier would sink to the element type), and for another, the
4741 // only overload situation where it matters is subscript or pointer +- int,
4742 // and those shouldn't have qualifier variants anyway.
4743 if (PointeeTy->isArrayType())
4744 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004745 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004746 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004747 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004748 bool hasVolatile = VisibleQuals.hasVolatile();
4749 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004750
John McCall8ccfcb52009-09-24 19:53:00 +00004751 // Iterate through all strict supersets of BaseCVR.
4752 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4753 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004754 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4755 // in the types.
4756 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4757 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004758 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004759 if (!buildObjCPtr)
4760 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4761 else
4762 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004763 }
4764
4765 return true;
4766}
4767
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004768/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4769/// to the set of pointer types along with any more-qualified variants of
4770/// that type. For example, if @p Ty is "int const *", this routine
4771/// will add "int const *", "int const volatile *", "int const
4772/// restrict *", and "int const volatile restrict *" to the set of
4773/// pointer types. Returns true if the add of @p Ty itself succeeded,
4774/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004775///
4776/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004777bool
4778BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4779 QualType Ty) {
4780 // Insert this type.
4781 if (!MemberPointerTypes.insert(Ty))
4782 return false;
4783
John McCall8ccfcb52009-09-24 19:53:00 +00004784 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4785 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004786
John McCall8ccfcb52009-09-24 19:53:00 +00004787 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004788 // Don't add qualified variants of arrays. For one, they're not allowed
4789 // (the qualifier would sink to the element type), and for another, the
4790 // only overload situation where it matters is subscript or pointer +- int,
4791 // and those shouldn't have qualifier variants anyway.
4792 if (PointeeTy->isArrayType())
4793 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004794 const Type *ClassTy = PointerTy->getClass();
4795
4796 // Iterate through all strict supersets of the pointee type's CVR
4797 // qualifiers.
4798 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4799 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4800 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004801
John McCall8ccfcb52009-09-24 19:53:00 +00004802 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00004803 MemberPointerTypes.insert(
4804 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004805 }
4806
4807 return true;
4808}
4809
Douglas Gregora11693b2008-11-12 17:17:38 +00004810/// AddTypesConvertedFrom - Add each of the types to which the type @p
4811/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004812/// primarily interested in pointer types and enumeration types. We also
4813/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004814/// AllowUserConversions is true if we should look at the conversion
4815/// functions of a class type, and AllowExplicitConversions if we
4816/// should also include the explicit conversion functions of a class
4817/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004818void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004819BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004820 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004821 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004822 bool AllowExplicitConversions,
4823 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004824 // Only deal with canonical types.
4825 Ty = Context.getCanonicalType(Ty);
4826
4827 // Look through reference types; they aren't part of the type of an
4828 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004829 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004830 Ty = RefTy->getPointeeType();
4831
John McCall33ddac02011-01-19 10:06:00 +00004832 // If we're dealing with an array type, decay to the pointer.
4833 if (Ty->isArrayType())
4834 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4835
4836 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004837 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004838
Chandler Carruth00a38332010-12-13 01:44:01 +00004839 // Flag if we ever add a non-record type.
4840 const RecordType *TyRec = Ty->getAs<RecordType>();
4841 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4842
Chandler Carruth00a38332010-12-13 01:44:01 +00004843 // Flag if we encounter an arithmetic type.
4844 HasArithmeticOrEnumeralTypes =
4845 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4846
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004847 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4848 PointerTypes.insert(Ty);
4849 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004850 // Insert our type, and its more-qualified variants, into the set
4851 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004852 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004853 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004854 } else if (Ty->isMemberPointerType()) {
4855 // Member pointers are far easier, since the pointee can't be converted.
4856 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4857 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004858 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004859 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00004860 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004861 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004862 // We treat vector types as arithmetic types in many contexts as an
4863 // extension.
4864 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004865 VectorTypes.insert(Ty);
Chandler Carruth00a38332010-12-13 01:44:01 +00004866 } else if (AllowUserConversions && TyRec) {
4867 // No conversion functions in incomplete types.
4868 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4869 return;
Mike Stump11289f42009-09-09 15:08:12 +00004870
Chandler Carruth00a38332010-12-13 01:44:01 +00004871 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4872 const UnresolvedSetImpl *Conversions
4873 = ClassDecl->getVisibleConversionFunctions();
4874 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4875 E = Conversions->end(); I != E; ++I) {
4876 NamedDecl *D = I.getDecl();
4877 if (isa<UsingShadowDecl>(D))
4878 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004879
Chandler Carruth00a38332010-12-13 01:44:01 +00004880 // Skip conversion function templates; they don't tell us anything
4881 // about which builtin types we can convert to.
4882 if (isa<FunctionTemplateDecl>(D))
4883 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00004884
Chandler Carruth00a38332010-12-13 01:44:01 +00004885 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4886 if (AllowExplicitConversions || !Conv->isExplicit()) {
4887 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4888 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004889 }
4890 }
4891 }
4892}
4893
Douglas Gregor84605ae2009-08-24 13:43:27 +00004894/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4895/// the volatile- and non-volatile-qualified assignment operators for the
4896/// given type to the candidate set.
4897static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4898 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004899 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004900 unsigned NumArgs,
4901 OverloadCandidateSet &CandidateSet) {
4902 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004903
Douglas Gregor84605ae2009-08-24 13:43:27 +00004904 // T& operator=(T&, T)
4905 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4906 ParamTypes[1] = T;
4907 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4908 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004909
Douglas Gregor84605ae2009-08-24 13:43:27 +00004910 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4911 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004912 ParamTypes[0]
4913 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004914 ParamTypes[1] = T;
4915 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004916 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004917 }
4918}
Mike Stump11289f42009-09-09 15:08:12 +00004919
Sebastian Redl1054fae2009-10-25 17:03:50 +00004920/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4921/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004922static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4923 Qualifiers VRQuals;
4924 const RecordType *TyRec;
4925 if (const MemberPointerType *RHSMPType =
4926 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004927 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004928 else
4929 TyRec = ArgExpr->getType()->getAs<RecordType>();
4930 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004931 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004932 VRQuals.addVolatile();
4933 VRQuals.addRestrict();
4934 return VRQuals;
4935 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004936
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004937 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004938 if (!ClassDecl->hasDefinition())
4939 return VRQuals;
4940
John McCallad371252010-01-20 00:46:10 +00004941 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004942 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004943
John McCallad371252010-01-20 00:46:10 +00004944 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004945 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004946 NamedDecl *D = I.getDecl();
4947 if (isa<UsingShadowDecl>(D))
4948 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4949 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004950 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4951 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4952 CanTy = ResTypeRef->getPointeeType();
4953 // Need to go down the pointer/mempointer chain and add qualifiers
4954 // as see them.
4955 bool done = false;
4956 while (!done) {
4957 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4958 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004959 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004960 CanTy->getAs<MemberPointerType>())
4961 CanTy = ResTypeMPtr->getPointeeType();
4962 else
4963 done = true;
4964 if (CanTy.isVolatileQualified())
4965 VRQuals.addVolatile();
4966 if (CanTy.isRestrictQualified())
4967 VRQuals.addRestrict();
4968 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4969 return VRQuals;
4970 }
4971 }
4972 }
4973 return VRQuals;
4974}
John McCall52872982010-11-13 05:51:15 +00004975
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004976namespace {
John McCall52872982010-11-13 05:51:15 +00004977
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004978/// \brief Helper class to manage the addition of builtin operator overload
4979/// candidates. It provides shared state and utility methods used throughout
4980/// the process, as well as a helper method to add each group of builtin
4981/// operator overloads from the standard to a candidate set.
4982class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004983 // Common instance state available to all overload candidate addition methods.
4984 Sema &S;
4985 Expr **Args;
4986 unsigned NumArgs;
4987 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00004988 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruthc6586e52010-12-12 10:35:00 +00004989 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4990 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004991
Chandler Carruthc6586e52010-12-12 10:35:00 +00004992 // Define some constants used to index and iterate over the arithemetic types
4993 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00004994 // The "promoted arithmetic types" are the arithmetic
4995 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00004996 static const unsigned FirstIntegralType = 3;
4997 static const unsigned LastIntegralType = 18;
4998 static const unsigned FirstPromotedIntegralType = 3,
4999 LastPromotedIntegralType = 9;
5000 static const unsigned FirstPromotedArithmeticType = 0,
5001 LastPromotedArithmeticType = 9;
5002 static const unsigned NumArithmeticTypes = 18;
5003
Chandler Carruthc6586e52010-12-12 10:35:00 +00005004 /// \brief Get the canonical type for a given arithmetic type index.
5005 CanQualType getArithmeticType(unsigned index) {
5006 assert(index < NumArithmeticTypes);
5007 static CanQualType ASTContext::* const
5008 ArithmeticTypes[NumArithmeticTypes] = {
5009 // Start of promoted types.
5010 &ASTContext::FloatTy,
5011 &ASTContext::DoubleTy,
5012 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005013
Chandler Carruthc6586e52010-12-12 10:35:00 +00005014 // Start of integral types.
5015 &ASTContext::IntTy,
5016 &ASTContext::LongTy,
5017 &ASTContext::LongLongTy,
5018 &ASTContext::UnsignedIntTy,
5019 &ASTContext::UnsignedLongTy,
5020 &ASTContext::UnsignedLongLongTy,
5021 // End of promoted types.
5022
5023 &ASTContext::BoolTy,
5024 &ASTContext::CharTy,
5025 &ASTContext::WCharTy,
5026 &ASTContext::Char16Ty,
5027 &ASTContext::Char32Ty,
5028 &ASTContext::SignedCharTy,
5029 &ASTContext::ShortTy,
5030 &ASTContext::UnsignedCharTy,
5031 &ASTContext::UnsignedShortTy,
5032 // End of integral types.
5033 // FIXME: What about complex?
5034 };
5035 return S.Context.*ArithmeticTypes[index];
5036 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005037
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005038 /// \brief Gets the canonical type resulting from the usual arithemetic
5039 /// converions for the given arithmetic types.
5040 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5041 // Accelerator table for performing the usual arithmetic conversions.
5042 // The rules are basically:
5043 // - if either is floating-point, use the wider floating-point
5044 // - if same signedness, use the higher rank
5045 // - if same size, use unsigned of the higher rank
5046 // - use the larger type
5047 // These rules, together with the axiom that higher ranks are
5048 // never smaller, are sufficient to precompute all of these results
5049 // *except* when dealing with signed types of higher rank.
5050 // (we could precompute SLL x UI for all known platforms, but it's
5051 // better not to make any assumptions).
5052 enum PromotedType {
5053 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5054 };
5055 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5056 [LastPromotedArithmeticType] = {
5057 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5058 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5059 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5060 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5061 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5062 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5063 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5064 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5065 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5066 };
5067
5068 assert(L < LastPromotedArithmeticType);
5069 assert(R < LastPromotedArithmeticType);
5070 int Idx = ConversionsTable[L][R];
5071
5072 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005073 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005074
5075 // Slow path: we need to compare widths.
5076 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005077 CanQualType LT = getArithmeticType(L),
5078 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005079 unsigned LW = S.Context.getIntWidth(LT),
5080 RW = S.Context.getIntWidth(RT);
5081
5082 // If they're different widths, use the signed type.
5083 if (LW > RW) return LT;
5084 else if (LW < RW) return RT;
5085
5086 // Otherwise, use the unsigned type of the signed type's rank.
5087 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5088 assert(L == SLL || R == SLL);
5089 return S.Context.UnsignedLongLongTy;
5090 }
5091
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005092 /// \brief Helper method to factor out the common pattern of adding overloads
5093 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005094 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5095 bool HasVolatile) {
5096 QualType ParamTypes[2] = {
5097 S.Context.getLValueReferenceType(CandidateTy),
5098 S.Context.IntTy
5099 };
5100
5101 // Non-volatile version.
5102 if (NumArgs == 1)
5103 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5104 else
5105 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5106
5107 // Use a heuristic to reduce number of builtin candidates in the set:
5108 // add volatile version only if there are conversions to a volatile type.
5109 if (HasVolatile) {
5110 ParamTypes[0] =
5111 S.Context.getLValueReferenceType(
5112 S.Context.getVolatileType(CandidateTy));
5113 if (NumArgs == 1)
5114 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5115 else
5116 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5117 }
5118 }
5119
5120public:
5121 BuiltinOperatorOverloadBuilder(
5122 Sema &S, Expr **Args, unsigned NumArgs,
5123 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005124 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005125 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
5126 OverloadCandidateSet &CandidateSet)
5127 : S(S), Args(Args), NumArgs(NumArgs),
5128 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005129 HasArithmeticOrEnumeralCandidateType(
5130 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005131 CandidateTypes(CandidateTypes),
5132 CandidateSet(CandidateSet) {
5133 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005134 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005135 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005136 assert(getArithmeticType(LastPromotedIntegralType - 1)
5137 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005138 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005139 assert(getArithmeticType(FirstPromotedArithmeticType)
5140 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005141 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005142 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5143 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005144 "Invalid last promoted arithmetic type");
5145 }
5146
5147 // C++ [over.built]p3:
5148 //
5149 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5150 // is either volatile or empty, there exist candidate operator
5151 // functions of the form
5152 //
5153 // VQ T& operator++(VQ T&);
5154 // T operator++(VQ T&, int);
5155 //
5156 // C++ [over.built]p4:
5157 //
5158 // For every pair (T, VQ), where T is an arithmetic type other
5159 // than bool, and VQ is either volatile or empty, there exist
5160 // candidate operator functions of the form
5161 //
5162 // VQ T& operator--(VQ T&);
5163 // T operator--(VQ T&, int);
5164 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005165 if (!HasArithmeticOrEnumeralCandidateType)
5166 return;
5167
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005168 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5169 Arith < NumArithmeticTypes; ++Arith) {
5170 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005171 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005172 VisibleTypeConversionsQuals.hasVolatile());
5173 }
5174 }
5175
5176 // C++ [over.built]p5:
5177 //
5178 // For every pair (T, VQ), where T is a cv-qualified or
5179 // cv-unqualified object type, and VQ is either volatile or
5180 // empty, there exist candidate operator functions of the form
5181 //
5182 // T*VQ& operator++(T*VQ&);
5183 // T*VQ& operator--(T*VQ&);
5184 // T* operator++(T*VQ&, int);
5185 // T* operator--(T*VQ&, int);
5186 void addPlusPlusMinusMinusPointerOverloads() {
5187 for (BuiltinCandidateTypeSet::iterator
5188 Ptr = CandidateTypes[0].pointer_begin(),
5189 PtrEnd = CandidateTypes[0].pointer_end();
5190 Ptr != PtrEnd; ++Ptr) {
5191 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005192 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005193 continue;
5194
5195 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5196 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5197 VisibleTypeConversionsQuals.hasVolatile()));
5198 }
5199 }
5200
5201 // C++ [over.built]p6:
5202 // For every cv-qualified or cv-unqualified object type T, there
5203 // exist candidate operator functions of the form
5204 //
5205 // T& operator*(T*);
5206 //
5207 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005208 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005209 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005210 // T& operator*(T*);
5211 void addUnaryStarPointerOverloads() {
5212 for (BuiltinCandidateTypeSet::iterator
5213 Ptr = CandidateTypes[0].pointer_begin(),
5214 PtrEnd = CandidateTypes[0].pointer_end();
5215 Ptr != PtrEnd; ++Ptr) {
5216 QualType ParamTy = *Ptr;
5217 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005218 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5219 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005220
Douglas Gregor02824322011-01-26 19:30:28 +00005221 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5222 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5223 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005224
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005225 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5226 &ParamTy, Args, 1, CandidateSet);
5227 }
5228 }
5229
5230 // C++ [over.built]p9:
5231 // For every promoted arithmetic type T, there exist candidate
5232 // operator functions of the form
5233 //
5234 // T operator+(T);
5235 // T operator-(T);
5236 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005237 if (!HasArithmeticOrEnumeralCandidateType)
5238 return;
5239
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005240 for (unsigned Arith = FirstPromotedArithmeticType;
5241 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005242 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005243 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5244 }
5245
5246 // Extension: We also add these operators for vector types.
5247 for (BuiltinCandidateTypeSet::iterator
5248 Vec = CandidateTypes[0].vector_begin(),
5249 VecEnd = CandidateTypes[0].vector_end();
5250 Vec != VecEnd; ++Vec) {
5251 QualType VecTy = *Vec;
5252 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5253 }
5254 }
5255
5256 // C++ [over.built]p8:
5257 // For every type T, there exist candidate operator functions of
5258 // the form
5259 //
5260 // T* operator+(T*);
5261 void addUnaryPlusPointerOverloads() {
5262 for (BuiltinCandidateTypeSet::iterator
5263 Ptr = CandidateTypes[0].pointer_begin(),
5264 PtrEnd = CandidateTypes[0].pointer_end();
5265 Ptr != PtrEnd; ++Ptr) {
5266 QualType ParamTy = *Ptr;
5267 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5268 }
5269 }
5270
5271 // C++ [over.built]p10:
5272 // For every promoted integral type T, there exist candidate
5273 // operator functions of the form
5274 //
5275 // T operator~(T);
5276 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005277 if (!HasArithmeticOrEnumeralCandidateType)
5278 return;
5279
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005280 for (unsigned Int = FirstPromotedIntegralType;
5281 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005282 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005283 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5284 }
5285
5286 // Extension: We also add this operator for vector types.
5287 for (BuiltinCandidateTypeSet::iterator
5288 Vec = CandidateTypes[0].vector_begin(),
5289 VecEnd = CandidateTypes[0].vector_end();
5290 Vec != VecEnd; ++Vec) {
5291 QualType VecTy = *Vec;
5292 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5293 }
5294 }
5295
5296 // C++ [over.match.oper]p16:
5297 // For every pointer to member type T, there exist candidate operator
5298 // functions of the form
5299 //
5300 // bool operator==(T,T);
5301 // bool operator!=(T,T);
5302 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5303 /// Set of (canonical) types that we've already handled.
5304 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5305
5306 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5307 for (BuiltinCandidateTypeSet::iterator
5308 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5309 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5310 MemPtr != MemPtrEnd;
5311 ++MemPtr) {
5312 // Don't add the same builtin candidate twice.
5313 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5314 continue;
5315
5316 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5317 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5318 CandidateSet);
5319 }
5320 }
5321 }
5322
5323 // C++ [over.built]p15:
5324 //
5325 // For every pointer or enumeration type T, there exist
5326 // candidate operator functions of the form
5327 //
5328 // bool operator<(T, T);
5329 // bool operator>(T, T);
5330 // bool operator<=(T, T);
5331 // bool operator>=(T, T);
5332 // bool operator==(T, T);
5333 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005334 void addRelationalPointerOrEnumeralOverloads() {
5335 // C++ [over.built]p1:
5336 // If there is a user-written candidate with the same name and parameter
5337 // types as a built-in candidate operator function, the built-in operator
5338 // function is hidden and is not included in the set of candidate
5339 // functions.
5340 //
5341 // The text is actually in a note, but if we don't implement it then we end
5342 // up with ambiguities when the user provides an overloaded operator for
5343 // an enumeration type. Note that only enumeration types have this problem,
5344 // so we track which enumeration types we've seen operators for. Also, the
5345 // only other overloaded operator with enumeration argumenst, operator=,
5346 // cannot be overloaded for enumeration types, so this is the only place
5347 // where we must suppress candidates like this.
5348 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5349 UserDefinedBinaryOperators;
5350
5351 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5352 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5353 CandidateTypes[ArgIdx].enumeration_end()) {
5354 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5355 CEnd = CandidateSet.end();
5356 C != CEnd; ++C) {
5357 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5358 continue;
5359
5360 QualType FirstParamType =
5361 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5362 QualType SecondParamType =
5363 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5364
5365 // Skip if either parameter isn't of enumeral type.
5366 if (!FirstParamType->isEnumeralType() ||
5367 !SecondParamType->isEnumeralType())
5368 continue;
5369
5370 // Add this operator to the set of known user-defined operators.
5371 UserDefinedBinaryOperators.insert(
5372 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5373 S.Context.getCanonicalType(SecondParamType)));
5374 }
5375 }
5376 }
5377
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005378 /// Set of (canonical) types that we've already handled.
5379 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5380
5381 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5382 for (BuiltinCandidateTypeSet::iterator
5383 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5384 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5385 Ptr != PtrEnd; ++Ptr) {
5386 // Don't add the same builtin candidate twice.
5387 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5388 continue;
5389
5390 QualType ParamTypes[2] = { *Ptr, *Ptr };
5391 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5392 CandidateSet);
5393 }
5394 for (BuiltinCandidateTypeSet::iterator
5395 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5396 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5397 Enum != EnumEnd; ++Enum) {
5398 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5399
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005400 // Don't add the same builtin candidate twice, or if a user defined
5401 // candidate exists.
5402 if (!AddedTypes.insert(CanonType) ||
5403 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5404 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005405 continue;
5406
5407 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005408 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5409 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005410 }
5411 }
5412 }
5413
5414 // C++ [over.built]p13:
5415 //
5416 // For every cv-qualified or cv-unqualified object type T
5417 // there exist candidate operator functions of the form
5418 //
5419 // T* operator+(T*, ptrdiff_t);
5420 // T& operator[](T*, ptrdiff_t); [BELOW]
5421 // T* operator-(T*, ptrdiff_t);
5422 // T* operator+(ptrdiff_t, T*);
5423 // T& operator[](ptrdiff_t, T*); [BELOW]
5424 //
5425 // C++ [over.built]p14:
5426 //
5427 // For every T, where T is a pointer to object type, there
5428 // exist candidate operator functions of the form
5429 //
5430 // ptrdiff_t operator-(T, T);
5431 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5432 /// Set of (canonical) types that we've already handled.
5433 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5434
5435 for (int Arg = 0; Arg < 2; ++Arg) {
5436 QualType AsymetricParamTypes[2] = {
5437 S.Context.getPointerDiffType(),
5438 S.Context.getPointerDiffType(),
5439 };
5440 for (BuiltinCandidateTypeSet::iterator
5441 Ptr = CandidateTypes[Arg].pointer_begin(),
5442 PtrEnd = CandidateTypes[Arg].pointer_end();
5443 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005444 QualType PointeeTy = (*Ptr)->getPointeeType();
5445 if (!PointeeTy->isObjectType())
5446 continue;
5447
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005448 AsymetricParamTypes[Arg] = *Ptr;
5449 if (Arg == 0 || Op == OO_Plus) {
5450 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5451 // T* operator+(ptrdiff_t, T*);
5452 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5453 CandidateSet);
5454 }
5455 if (Op == OO_Minus) {
5456 // ptrdiff_t operator-(T, T);
5457 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5458 continue;
5459
5460 QualType ParamTypes[2] = { *Ptr, *Ptr };
5461 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5462 Args, 2, CandidateSet);
5463 }
5464 }
5465 }
5466 }
5467
5468 // C++ [over.built]p12:
5469 //
5470 // For every pair of promoted arithmetic types L and R, there
5471 // exist candidate operator functions of the form
5472 //
5473 // LR operator*(L, R);
5474 // LR operator/(L, R);
5475 // LR operator+(L, R);
5476 // LR operator-(L, R);
5477 // bool operator<(L, R);
5478 // bool operator>(L, R);
5479 // bool operator<=(L, R);
5480 // bool operator>=(L, R);
5481 // bool operator==(L, R);
5482 // bool operator!=(L, R);
5483 //
5484 // where LR is the result of the usual arithmetic conversions
5485 // between types L and R.
5486 //
5487 // C++ [over.built]p24:
5488 //
5489 // For every pair of promoted arithmetic types L and R, there exist
5490 // candidate operator functions of the form
5491 //
5492 // LR operator?(bool, L, R);
5493 //
5494 // where LR is the result of the usual arithmetic conversions
5495 // between types L and R.
5496 // Our candidates ignore the first parameter.
5497 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005498 if (!HasArithmeticOrEnumeralCandidateType)
5499 return;
5500
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005501 for (unsigned Left = FirstPromotedArithmeticType;
5502 Left < LastPromotedArithmeticType; ++Left) {
5503 for (unsigned Right = FirstPromotedArithmeticType;
5504 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005505 QualType LandR[2] = { getArithmeticType(Left),
5506 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005507 QualType Result =
5508 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005509 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005510 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5511 }
5512 }
5513
5514 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5515 // conditional operator for vector types.
5516 for (BuiltinCandidateTypeSet::iterator
5517 Vec1 = CandidateTypes[0].vector_begin(),
5518 Vec1End = CandidateTypes[0].vector_end();
5519 Vec1 != Vec1End; ++Vec1) {
5520 for (BuiltinCandidateTypeSet::iterator
5521 Vec2 = CandidateTypes[1].vector_begin(),
5522 Vec2End = CandidateTypes[1].vector_end();
5523 Vec2 != Vec2End; ++Vec2) {
5524 QualType LandR[2] = { *Vec1, *Vec2 };
5525 QualType Result = S.Context.BoolTy;
5526 if (!isComparison) {
5527 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5528 Result = *Vec1;
5529 else
5530 Result = *Vec2;
5531 }
5532
5533 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5534 }
5535 }
5536 }
5537
5538 // C++ [over.built]p17:
5539 //
5540 // For every pair of promoted integral types L and R, there
5541 // exist candidate operator functions of the form
5542 //
5543 // LR operator%(L, R);
5544 // LR operator&(L, R);
5545 // LR operator^(L, R);
5546 // LR operator|(L, R);
5547 // L operator<<(L, R);
5548 // L operator>>(L, R);
5549 //
5550 // where LR is the result of the usual arithmetic conversions
5551 // between types L and R.
5552 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005553 if (!HasArithmeticOrEnumeralCandidateType)
5554 return;
5555
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005556 for (unsigned Left = FirstPromotedIntegralType;
5557 Left < LastPromotedIntegralType; ++Left) {
5558 for (unsigned Right = FirstPromotedIntegralType;
5559 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005560 QualType LandR[2] = { getArithmeticType(Left),
5561 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005562 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5563 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005564 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005565 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5566 }
5567 }
5568 }
5569
5570 // C++ [over.built]p20:
5571 //
5572 // For every pair (T, VQ), where T is an enumeration or
5573 // pointer to member type and VQ is either volatile or
5574 // empty, there exist candidate operator functions of the form
5575 //
5576 // VQ T& operator=(VQ T&, T);
5577 void addAssignmentMemberPointerOrEnumeralOverloads() {
5578 /// Set of (canonical) types that we've already handled.
5579 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5580
5581 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5582 for (BuiltinCandidateTypeSet::iterator
5583 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5584 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5585 Enum != EnumEnd; ++Enum) {
5586 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5587 continue;
5588
5589 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5590 CandidateSet);
5591 }
5592
5593 for (BuiltinCandidateTypeSet::iterator
5594 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5595 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5596 MemPtr != MemPtrEnd; ++MemPtr) {
5597 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5598 continue;
5599
5600 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5601 CandidateSet);
5602 }
5603 }
5604 }
5605
5606 // C++ [over.built]p19:
5607 //
5608 // For every pair (T, VQ), where T is any type and VQ is either
5609 // volatile or empty, there exist candidate operator functions
5610 // of the form
5611 //
5612 // T*VQ& operator=(T*VQ&, T*);
5613 //
5614 // C++ [over.built]p21:
5615 //
5616 // For every pair (T, VQ), where T is a cv-qualified or
5617 // cv-unqualified object type and VQ is either volatile or
5618 // empty, there exist candidate operator functions of the form
5619 //
5620 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5621 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5622 void addAssignmentPointerOverloads(bool isEqualOp) {
5623 /// Set of (canonical) types that we've already handled.
5624 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5625
5626 for (BuiltinCandidateTypeSet::iterator
5627 Ptr = CandidateTypes[0].pointer_begin(),
5628 PtrEnd = CandidateTypes[0].pointer_end();
5629 Ptr != PtrEnd; ++Ptr) {
5630 // If this is operator=, keep track of the builtin candidates we added.
5631 if (isEqualOp)
5632 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005633 else if (!(*Ptr)->getPointeeType()->isObjectType())
5634 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005635
5636 // non-volatile version
5637 QualType ParamTypes[2] = {
5638 S.Context.getLValueReferenceType(*Ptr),
5639 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5640 };
5641 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5642 /*IsAssigmentOperator=*/ isEqualOp);
5643
5644 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5645 VisibleTypeConversionsQuals.hasVolatile()) {
5646 // volatile version
5647 ParamTypes[0] =
5648 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5649 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5650 /*IsAssigmentOperator=*/isEqualOp);
5651 }
5652 }
5653
5654 if (isEqualOp) {
5655 for (BuiltinCandidateTypeSet::iterator
5656 Ptr = CandidateTypes[1].pointer_begin(),
5657 PtrEnd = CandidateTypes[1].pointer_end();
5658 Ptr != PtrEnd; ++Ptr) {
5659 // Make sure we don't add the same candidate twice.
5660 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5661 continue;
5662
Chandler Carruth8e543b32010-12-12 08:17:55 +00005663 QualType ParamTypes[2] = {
5664 S.Context.getLValueReferenceType(*Ptr),
5665 *Ptr,
5666 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005667
5668 // non-volatile version
5669 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5670 /*IsAssigmentOperator=*/true);
5671
5672 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5673 VisibleTypeConversionsQuals.hasVolatile()) {
5674 // volatile version
5675 ParamTypes[0] =
5676 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00005677 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5678 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005679 }
5680 }
5681 }
5682 }
5683
5684 // C++ [over.built]p18:
5685 //
5686 // For every triple (L, VQ, R), where L is an arithmetic type,
5687 // VQ is either volatile or empty, and R is a promoted
5688 // arithmetic type, there exist candidate operator functions of
5689 // the form
5690 //
5691 // VQ L& operator=(VQ L&, R);
5692 // VQ L& operator*=(VQ L&, R);
5693 // VQ L& operator/=(VQ L&, R);
5694 // VQ L& operator+=(VQ L&, R);
5695 // VQ L& operator-=(VQ L&, R);
5696 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005697 if (!HasArithmeticOrEnumeralCandidateType)
5698 return;
5699
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005700 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5701 for (unsigned Right = FirstPromotedArithmeticType;
5702 Right < LastPromotedArithmeticType; ++Right) {
5703 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005704 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005705
5706 // Add this built-in operator as a candidate (VQ is empty).
5707 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005708 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005709 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5710 /*IsAssigmentOperator=*/isEqualOp);
5711
5712 // Add this built-in operator as a candidate (VQ is 'volatile').
5713 if (VisibleTypeConversionsQuals.hasVolatile()) {
5714 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005715 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005716 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005717 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5718 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005719 /*IsAssigmentOperator=*/isEqualOp);
5720 }
5721 }
5722 }
5723
5724 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5725 for (BuiltinCandidateTypeSet::iterator
5726 Vec1 = CandidateTypes[0].vector_begin(),
5727 Vec1End = CandidateTypes[0].vector_end();
5728 Vec1 != Vec1End; ++Vec1) {
5729 for (BuiltinCandidateTypeSet::iterator
5730 Vec2 = CandidateTypes[1].vector_begin(),
5731 Vec2End = CandidateTypes[1].vector_end();
5732 Vec2 != Vec2End; ++Vec2) {
5733 QualType ParamTypes[2];
5734 ParamTypes[1] = *Vec2;
5735 // Add this built-in operator as a candidate (VQ is empty).
5736 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5737 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5738 /*IsAssigmentOperator=*/isEqualOp);
5739
5740 // Add this built-in operator as a candidate (VQ is 'volatile').
5741 if (VisibleTypeConversionsQuals.hasVolatile()) {
5742 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5743 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005744 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5745 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005746 /*IsAssigmentOperator=*/isEqualOp);
5747 }
5748 }
5749 }
5750 }
5751
5752 // C++ [over.built]p22:
5753 //
5754 // For every triple (L, VQ, R), where L is an integral type, VQ
5755 // is either volatile or empty, and R is a promoted integral
5756 // type, there exist candidate operator functions of the form
5757 //
5758 // VQ L& operator%=(VQ L&, R);
5759 // VQ L& operator<<=(VQ L&, R);
5760 // VQ L& operator>>=(VQ L&, R);
5761 // VQ L& operator&=(VQ L&, R);
5762 // VQ L& operator^=(VQ L&, R);
5763 // VQ L& operator|=(VQ L&, R);
5764 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005765 if (!HasArithmeticOrEnumeralCandidateType)
5766 return;
5767
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005768 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5769 for (unsigned Right = FirstPromotedIntegralType;
5770 Right < LastPromotedIntegralType; ++Right) {
5771 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005772 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005773
5774 // Add this built-in operator as a candidate (VQ is empty).
5775 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005776 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005777 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5778 if (VisibleTypeConversionsQuals.hasVolatile()) {
5779 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00005780 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005781 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5782 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5783 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5784 CandidateSet);
5785 }
5786 }
5787 }
5788 }
5789
5790 // C++ [over.operator]p23:
5791 //
5792 // There also exist candidate operator functions of the form
5793 //
5794 // bool operator!(bool);
5795 // bool operator&&(bool, bool);
5796 // bool operator||(bool, bool);
5797 void addExclaimOverload() {
5798 QualType ParamTy = S.Context.BoolTy;
5799 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5800 /*IsAssignmentOperator=*/false,
5801 /*NumContextualBoolArguments=*/1);
5802 }
5803 void addAmpAmpOrPipePipeOverload() {
5804 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5805 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5806 /*IsAssignmentOperator=*/false,
5807 /*NumContextualBoolArguments=*/2);
5808 }
5809
5810 // C++ [over.built]p13:
5811 //
5812 // For every cv-qualified or cv-unqualified object type T there
5813 // exist candidate operator functions of the form
5814 //
5815 // T* operator+(T*, ptrdiff_t); [ABOVE]
5816 // T& operator[](T*, ptrdiff_t);
5817 // T* operator-(T*, ptrdiff_t); [ABOVE]
5818 // T* operator+(ptrdiff_t, T*); [ABOVE]
5819 // T& operator[](ptrdiff_t, T*);
5820 void addSubscriptOverloads() {
5821 for (BuiltinCandidateTypeSet::iterator
5822 Ptr = CandidateTypes[0].pointer_begin(),
5823 PtrEnd = CandidateTypes[0].pointer_end();
5824 Ptr != PtrEnd; ++Ptr) {
5825 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5826 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005827 if (!PointeeType->isObjectType())
5828 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005829
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005830 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5831
5832 // T& operator[](T*, ptrdiff_t)
5833 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5834 }
5835
5836 for (BuiltinCandidateTypeSet::iterator
5837 Ptr = CandidateTypes[1].pointer_begin(),
5838 PtrEnd = CandidateTypes[1].pointer_end();
5839 Ptr != PtrEnd; ++Ptr) {
5840 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5841 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005842 if (!PointeeType->isObjectType())
5843 continue;
5844
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005845 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5846
5847 // T& operator[](ptrdiff_t, T*)
5848 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5849 }
5850 }
5851
5852 // C++ [over.built]p11:
5853 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5854 // C1 is the same type as C2 or is a derived class of C2, T is an object
5855 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5856 // there exist candidate operator functions of the form
5857 //
5858 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5859 //
5860 // where CV12 is the union of CV1 and CV2.
5861 void addArrowStarOverloads() {
5862 for (BuiltinCandidateTypeSet::iterator
5863 Ptr = CandidateTypes[0].pointer_begin(),
5864 PtrEnd = CandidateTypes[0].pointer_end();
5865 Ptr != PtrEnd; ++Ptr) {
5866 QualType C1Ty = (*Ptr);
5867 QualType C1;
5868 QualifierCollector Q1;
5869 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5870 if (!isa<RecordType>(C1))
5871 continue;
5872 // heuristic to reduce number of builtin candidates in the set.
5873 // Add volatile/restrict version only if there are conversions to a
5874 // volatile/restrict type.
5875 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5876 continue;
5877 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5878 continue;
5879 for (BuiltinCandidateTypeSet::iterator
5880 MemPtr = CandidateTypes[1].member_pointer_begin(),
5881 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5882 MemPtr != MemPtrEnd; ++MemPtr) {
5883 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5884 QualType C2 = QualType(mptr->getClass(), 0);
5885 C2 = C2.getUnqualifiedType();
5886 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5887 break;
5888 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5889 // build CV12 T&
5890 QualType T = mptr->getPointeeType();
5891 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5892 T.isVolatileQualified())
5893 continue;
5894 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5895 T.isRestrictQualified())
5896 continue;
5897 T = Q1.apply(S.Context, T);
5898 QualType ResultTy = S.Context.getLValueReferenceType(T);
5899 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5900 }
5901 }
5902 }
5903
5904 // Note that we don't consider the first argument, since it has been
5905 // contextually converted to bool long ago. The candidates below are
5906 // therefore added as binary.
5907 //
5908 // C++ [over.built]p25:
5909 // For every type T, where T is a pointer, pointer-to-member, or scoped
5910 // enumeration type, there exist candidate operator functions of the form
5911 //
5912 // T operator?(bool, T, T);
5913 //
5914 void addConditionalOperatorOverloads() {
5915 /// Set of (canonical) types that we've already handled.
5916 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5917
5918 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5919 for (BuiltinCandidateTypeSet::iterator
5920 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5921 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5922 Ptr != PtrEnd; ++Ptr) {
5923 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5924 continue;
5925
5926 QualType ParamTypes[2] = { *Ptr, *Ptr };
5927 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5928 }
5929
5930 for (BuiltinCandidateTypeSet::iterator
5931 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5932 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5933 MemPtr != MemPtrEnd; ++MemPtr) {
5934 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5935 continue;
5936
5937 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5938 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5939 }
5940
5941 if (S.getLangOptions().CPlusPlus0x) {
5942 for (BuiltinCandidateTypeSet::iterator
5943 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5944 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5945 Enum != EnumEnd; ++Enum) {
5946 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5947 continue;
5948
5949 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5950 continue;
5951
5952 QualType ParamTypes[2] = { *Enum, *Enum };
5953 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5954 }
5955 }
5956 }
5957 }
5958};
5959
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005960} // end anonymous namespace
5961
5962/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5963/// operator overloads to the candidate set (C++ [over.built]), based
5964/// on the operator @p Op and the arguments given. For example, if the
5965/// operator is a binary '+', this routine might add "int
5966/// operator+(int, int)" to cover integer addition.
5967void
5968Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5969 SourceLocation OpLoc,
5970 Expr **Args, unsigned NumArgs,
5971 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005972 // Find all of the types that the arguments can convert to, but only
5973 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00005974 // that make use of these types. Also record whether we encounter non-record
5975 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005976 Qualifiers VisibleTypeConversionsQuals;
5977 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005978 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5979 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00005980
5981 bool HasNonRecordCandidateType = false;
5982 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005983 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5984 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5985 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5986 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5987 OpLoc,
5988 true,
5989 (Op == OO_Exclaim ||
5990 Op == OO_AmpAmp ||
5991 Op == OO_PipePipe),
5992 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00005993 HasNonRecordCandidateType = HasNonRecordCandidateType ||
5994 CandidateTypes[ArgIdx].hasNonRecordTypes();
5995 HasArithmeticOrEnumeralCandidateType =
5996 HasArithmeticOrEnumeralCandidateType ||
5997 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005998 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005999
Chandler Carruth00a38332010-12-13 01:44:01 +00006000 // Exit early when no non-record types have been added to the candidate set
6001 // for any of the arguments to the operator.
6002 if (!HasNonRecordCandidateType)
6003 return;
6004
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006005 // Setup an object to manage the common state for building overloads.
6006 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6007 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006008 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006009 CandidateTypes, CandidateSet);
6010
6011 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006012 switch (Op) {
6013 case OO_None:
6014 case NUM_OVERLOADED_OPERATORS:
6015 assert(false && "Expected an overloaded operator");
6016 break;
6017
Chandler Carruth5184de02010-12-12 08:51:33 +00006018 case OO_New:
6019 case OO_Delete:
6020 case OO_Array_New:
6021 case OO_Array_Delete:
6022 case OO_Call:
6023 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
6024 break;
6025
6026 case OO_Comma:
6027 case OO_Arrow:
6028 // C++ [over.match.oper]p3:
6029 // -- For the operator ',', the unary operator '&', or the
6030 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006031 break;
6032
6033 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006034 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006035 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006036 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006037
6038 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006039 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006040 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006041 } else {
6042 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6043 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6044 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006045 break;
6046
Chandler Carruth5184de02010-12-12 08:51:33 +00006047 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006048 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006049 OpBuilder.addUnaryStarPointerOverloads();
6050 else
6051 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6052 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006053
Chandler Carruth5184de02010-12-12 08:51:33 +00006054 case OO_Slash:
6055 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006056 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006057
6058 case OO_PlusPlus:
6059 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006060 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6061 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006062 break;
6063
Douglas Gregor84605ae2009-08-24 13:43:27 +00006064 case OO_EqualEqual:
6065 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006066 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006067 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006068
Douglas Gregora11693b2008-11-12 17:17:38 +00006069 case OO_Less:
6070 case OO_Greater:
6071 case OO_LessEqual:
6072 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006073 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006074 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6075 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006076
Douglas Gregora11693b2008-11-12 17:17:38 +00006077 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006078 case OO_Caret:
6079 case OO_Pipe:
6080 case OO_LessLess:
6081 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006082 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006083 break;
6084
Chandler Carruth5184de02010-12-12 08:51:33 +00006085 case OO_Amp: // '&' is either unary or binary
6086 if (NumArgs == 1)
6087 // C++ [over.match.oper]p3:
6088 // -- For the operator ',', the unary operator '&', or the
6089 // operator '->', the built-in candidates set is empty.
6090 break;
6091
6092 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6093 break;
6094
6095 case OO_Tilde:
6096 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6097 break;
6098
Douglas Gregora11693b2008-11-12 17:17:38 +00006099 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006100 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006101 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006102
6103 case OO_PlusEqual:
6104 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006105 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006106 // Fall through.
6107
6108 case OO_StarEqual:
6109 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006110 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006111 break;
6112
6113 case OO_PercentEqual:
6114 case OO_LessLessEqual:
6115 case OO_GreaterGreaterEqual:
6116 case OO_AmpEqual:
6117 case OO_CaretEqual:
6118 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006119 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006120 break;
6121
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006122 case OO_Exclaim:
6123 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006124 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006125
Douglas Gregora11693b2008-11-12 17:17:38 +00006126 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006127 case OO_PipePipe:
6128 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006129 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006130
6131 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006132 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006133 break;
6134
6135 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006136 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006137 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006138
6139 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006140 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006141 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6142 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006143 }
6144}
6145
Douglas Gregore254f902009-02-04 00:32:51 +00006146/// \brief Add function candidates found via argument-dependent lookup
6147/// to the set of overloading candidates.
6148///
6149/// This routine performs argument-dependent name lookup based on the
6150/// given function name (which may also be an operator name) and adds
6151/// all of the overload candidates found by ADL to the overload
6152/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006153void
Douglas Gregore254f902009-02-04 00:32:51 +00006154Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006155 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006156 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006157 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006158 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006159 bool PartialOverloading,
6160 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006161 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006162
John McCall91f61fc2010-01-26 06:04:06 +00006163 // FIXME: This approach for uniquing ADL results (and removing
6164 // redundant candidates from the set) relies on pointer-equality,
6165 // which means we need to key off the canonical decl. However,
6166 // always going back to the canonical decl might not get us the
6167 // right set of default arguments. What default arguments are
6168 // we supposed to consider on ADL candidates, anyway?
6169
Douglas Gregorcabea402009-09-22 15:41:20 +00006170 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006171 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6172 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006173
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006174 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006175 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6176 CandEnd = CandidateSet.end();
6177 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006178 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006179 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006180 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006181 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006182 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006183
6184 // For each of the ADL candidates we found, add it to the overload
6185 // set.
John McCall8fe68082010-01-26 07:16:45 +00006186 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006187 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006188 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006189 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006190 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006191
John McCalla0296f72010-03-19 07:35:19 +00006192 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006193 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006194 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006195 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006196 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006197 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006198 }
Douglas Gregore254f902009-02-04 00:32:51 +00006199}
6200
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006201/// isBetterOverloadCandidate - Determines whether the first overload
6202/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006203bool
John McCall5c32be02010-08-24 20:38:10 +00006204isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006205 const OverloadCandidate &Cand1,
6206 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006207 SourceLocation Loc,
6208 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006209 // Define viable functions to be better candidates than non-viable
6210 // functions.
6211 if (!Cand2.Viable)
6212 return Cand1.Viable;
6213 else if (!Cand1.Viable)
6214 return false;
6215
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006216 // C++ [over.match.best]p1:
6217 //
6218 // -- if F is a static member function, ICS1(F) is defined such
6219 // that ICS1(F) is neither better nor worse than ICS1(G) for
6220 // any function G, and, symmetrically, ICS1(G) is neither
6221 // better nor worse than ICS1(F).
6222 unsigned StartArg = 0;
6223 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6224 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006225
Douglas Gregord3cb3562009-07-07 23:38:56 +00006226 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006227 // A viable function F1 is defined to be a better function than another
6228 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006229 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006230 unsigned NumArgs = Cand1.Conversions.size();
6231 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6232 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006233 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006234 switch (CompareImplicitConversionSequences(S,
6235 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006236 Cand2.Conversions[ArgIdx])) {
6237 case ImplicitConversionSequence::Better:
6238 // Cand1 has a better conversion sequence.
6239 HasBetterConversion = true;
6240 break;
6241
6242 case ImplicitConversionSequence::Worse:
6243 // Cand1 can't be better than Cand2.
6244 return false;
6245
6246 case ImplicitConversionSequence::Indistinguishable:
6247 // Do nothing.
6248 break;
6249 }
6250 }
6251
Mike Stump11289f42009-09-09 15:08:12 +00006252 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006253 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006254 if (HasBetterConversion)
6255 return true;
6256
Mike Stump11289f42009-09-09 15:08:12 +00006257 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006258 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006259 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006260 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6261 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006262
6263 // -- F1 and F2 are function template specializations, and the function
6264 // template for F1 is more specialized than the template for F2
6265 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006266 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006267 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006268 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006269 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006270 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6271 Cand2.Function->getPrimaryTemplate(),
6272 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006273 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006274 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006275 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006276 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006278
Douglas Gregora1f013e2008-11-07 22:36:19 +00006279 // -- the context is an initialization by user-defined conversion
6280 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6281 // from the return type of F1 to the destination type (i.e.,
6282 // the type of the entity being initialized) is a better
6283 // conversion sequence than the standard conversion sequence
6284 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006285 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006286 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006287 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006288 switch (CompareStandardConversionSequences(S,
6289 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006290 Cand2.FinalConversion)) {
6291 case ImplicitConversionSequence::Better:
6292 // Cand1 has a better conversion sequence.
6293 return true;
6294
6295 case ImplicitConversionSequence::Worse:
6296 // Cand1 can't be better than Cand2.
6297 return false;
6298
6299 case ImplicitConversionSequence::Indistinguishable:
6300 // Do nothing
6301 break;
6302 }
6303 }
6304
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006305 return false;
6306}
6307
Mike Stump11289f42009-09-09 15:08:12 +00006308/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006309/// within an overload candidate set.
6310///
6311/// \param CandidateSet the set of candidate functions.
6312///
6313/// \param Loc the location of the function name (or operator symbol) for
6314/// which overload resolution occurs.
6315///
Mike Stump11289f42009-09-09 15:08:12 +00006316/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006317/// function, Best points to the candidate function found.
6318///
6319/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006320OverloadingResult
6321OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006322 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00006323 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006324 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006325 Best = end();
6326 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6327 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006328 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006329 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006330 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006331 }
6332
6333 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006334 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006335 return OR_No_Viable_Function;
6336
6337 // Make sure that this function is better than every other viable
6338 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006339 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006340 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006341 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006342 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006343 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006344 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006345 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006346 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006347 }
Mike Stump11289f42009-09-09 15:08:12 +00006348
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006349 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006350 if (Best->Function &&
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00006351 (Best->Function->isDeleted() || Best->Function->isUnavailable()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006352 return OR_Deleted;
6353
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006354 return OR_Success;
6355}
6356
John McCall53262c92010-01-12 02:15:36 +00006357namespace {
6358
6359enum OverloadCandidateKind {
6360 oc_function,
6361 oc_method,
6362 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006363 oc_function_template,
6364 oc_method_template,
6365 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006366 oc_implicit_default_constructor,
6367 oc_implicit_copy_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006368 oc_implicit_copy_assignment,
6369 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006370};
6371
John McCalle1ac8d12010-01-13 00:25:19 +00006372OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6373 FunctionDecl *Fn,
6374 std::string &Description) {
6375 bool isTemplate = false;
6376
6377 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6378 isTemplate = true;
6379 Description = S.getTemplateArgumentBindingsText(
6380 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6381 }
John McCallfd0b2f82010-01-06 09:43:14 +00006382
6383 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006384 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006385 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006386
Sebastian Redl08905022011-02-05 19:23:19 +00006387 if (Ctor->getInheritedConstructor())
6388 return oc_implicit_inherited_constructor;
6389
John McCall53262c92010-01-12 02:15:36 +00006390 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6391 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006392 }
6393
6394 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6395 // This actually gets spelled 'candidate function' for now, but
6396 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006397 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006398 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006399
Douglas Gregorec3bec02010-09-27 22:37:28 +00006400 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006401 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006402 return oc_implicit_copy_assignment;
6403 }
6404
John McCalle1ac8d12010-01-13 00:25:19 +00006405 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006406}
6407
Sebastian Redl08905022011-02-05 19:23:19 +00006408void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6409 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6410 if (!Ctor) return;
6411
6412 Ctor = Ctor->getInheritedConstructor();
6413 if (!Ctor) return;
6414
6415 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6416}
6417
John McCall53262c92010-01-12 02:15:36 +00006418} // end anonymous namespace
6419
6420// Notes the location of an overload candidate.
6421void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006422 std::string FnDesc;
6423 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6424 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6425 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00006426 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00006427}
6428
Douglas Gregorb491ed32011-02-19 21:32:49 +00006429//Notes the location of all overload candidates designated through
6430// OverloadedExpr
6431void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6432 assert(OverloadedExpr->getType() == Context.OverloadTy);
6433
6434 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6435 OverloadExpr *OvlExpr = Ovl.Expression;
6436
6437 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6438 IEnd = OvlExpr->decls_end();
6439 I != IEnd; ++I) {
6440 if (FunctionTemplateDecl *FunTmpl =
6441 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6442 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6443 } else if (FunctionDecl *Fun
6444 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6445 NoteOverloadCandidate(Fun);
6446 }
6447 }
6448}
6449
John McCall0d1da222010-01-12 00:44:57 +00006450/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6451/// "lead" diagnostic; it will be given two arguments, the source and
6452/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006453void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6454 Sema &S,
6455 SourceLocation CaretLoc,
6456 const PartialDiagnostic &PDiag) const {
6457 S.Diag(CaretLoc, PDiag)
6458 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006459 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006460 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6461 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006462 }
John McCall12f97bc2010-01-08 04:41:39 +00006463}
6464
John McCall0d1da222010-01-12 00:44:57 +00006465namespace {
6466
John McCall6a61b522010-01-13 09:16:55 +00006467void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6468 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6469 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006470 assert(Cand->Function && "for now, candidate must be a function");
6471 FunctionDecl *Fn = Cand->Function;
6472
6473 // There's a conversion slot for the object argument if this is a
6474 // non-constructor method. Note that 'I' corresponds the
6475 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006476 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006477 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006478 if (I == 0)
6479 isObjectArgument = true;
6480 else
6481 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006482 }
6483
John McCalle1ac8d12010-01-13 00:25:19 +00006484 std::string FnDesc;
6485 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6486
John McCall6a61b522010-01-13 09:16:55 +00006487 Expr *FromExpr = Conv.Bad.FromExpr;
6488 QualType FromTy = Conv.Bad.getFromType();
6489 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006490
John McCallfb7ad0f2010-02-02 02:42:52 +00006491 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006492 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006493 Expr *E = FromExpr->IgnoreParens();
6494 if (isa<UnaryOperator>(E))
6495 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006496 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006497
6498 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6499 << (unsigned) FnKind << FnDesc
6500 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6501 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006502 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00006503 return;
6504 }
6505
John McCall6d174642010-01-23 08:10:49 +00006506 // Do some hand-waving analysis to see if the non-viability is due
6507 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006508 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6509 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6510 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6511 CToTy = RT->getPointeeType();
6512 else {
6513 // TODO: detect and diagnose the full richness of const mismatches.
6514 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6515 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6516 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6517 }
6518
6519 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6520 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6521 // It is dumb that we have to do this here.
6522 while (isa<ArrayType>(CFromTy))
6523 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6524 while (isa<ArrayType>(CToTy))
6525 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6526
6527 Qualifiers FromQs = CFromTy.getQualifiers();
6528 Qualifiers ToQs = CToTy.getQualifiers();
6529
6530 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6531 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6532 << (unsigned) FnKind << FnDesc
6533 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6534 << FromTy
6535 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6536 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006537 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006538 return;
6539 }
6540
6541 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6542 assert(CVR && "unexpected qualifiers mismatch");
6543
6544 if (isObjectArgument) {
6545 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6546 << (unsigned) FnKind << FnDesc
6547 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6548 << FromTy << (CVR - 1);
6549 } else {
6550 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6551 << (unsigned) FnKind << FnDesc
6552 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6553 << FromTy << (CVR - 1) << I+1;
6554 }
Sebastian Redl08905022011-02-05 19:23:19 +00006555 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006556 return;
6557 }
6558
John McCall6d174642010-01-23 08:10:49 +00006559 // Diagnose references or pointers to incomplete types differently,
6560 // since it's far from impossible that the incompleteness triggered
6561 // the failure.
6562 QualType TempFromTy = FromTy.getNonReferenceType();
6563 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6564 TempFromTy = PTy->getPointeeType();
6565 if (TempFromTy->isIncompleteType()) {
6566 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6567 << (unsigned) FnKind << FnDesc
6568 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6569 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006570 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00006571 return;
6572 }
6573
Douglas Gregor56f2e342010-06-30 23:01:39 +00006574 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006575 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006576 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6577 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6578 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6579 FromPtrTy->getPointeeType()) &&
6580 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6581 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006582 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00006583 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006584 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006585 }
6586 } else if (const ObjCObjectPointerType *FromPtrTy
6587 = FromTy->getAs<ObjCObjectPointerType>()) {
6588 if (const ObjCObjectPointerType *ToPtrTy
6589 = ToTy->getAs<ObjCObjectPointerType>())
6590 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6591 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6592 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6593 FromPtrTy->getPointeeType()) &&
6594 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006595 BaseToDerivedConversion = 2;
6596 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6597 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6598 !FromTy->isIncompleteType() &&
6599 !ToRefTy->getPointeeType()->isIncompleteType() &&
6600 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6601 BaseToDerivedConversion = 3;
6602 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006603
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006604 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006605 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006606 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006607 << (unsigned) FnKind << FnDesc
6608 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006609 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006610 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006611 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00006612 return;
6613 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006614
John McCall47000992010-01-14 03:28:57 +00006615 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006616 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6617 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006618 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006619 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006620 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00006621}
6622
6623void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6624 unsigned NumFormalArgs) {
6625 // TODO: treat calls to a missing default constructor as a special case
6626
6627 FunctionDecl *Fn = Cand->Function;
6628 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6629
6630 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006631
John McCall6a61b522010-01-13 09:16:55 +00006632 // at least / at most / exactly
6633 unsigned mode, modeCount;
6634 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006635 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6636 (Cand->FailureKind == ovl_fail_bad_deduction &&
6637 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006638 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00006639 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00006640 mode = 0; // "at least"
6641 else
6642 mode = 2; // "exactly"
6643 modeCount = MinParams;
6644 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006645 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6646 (Cand->FailureKind == ovl_fail_bad_deduction &&
6647 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006648 if (MinParams != FnTy->getNumArgs())
6649 mode = 1; // "at most"
6650 else
6651 mode = 2; // "exactly"
6652 modeCount = FnTy->getNumArgs();
6653 }
6654
6655 std::string Description;
6656 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6657
6658 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006659 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00006660 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00006661 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006662}
6663
John McCall8b9ed552010-02-01 18:53:26 +00006664/// Diagnose a failed template-argument deduction.
6665void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6666 Expr **Args, unsigned NumArgs) {
6667 FunctionDecl *Fn = Cand->Function; // pattern
6668
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006669 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006670 NamedDecl *ParamD;
6671 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6672 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6673 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006674 switch (Cand->DeductionFailure.Result) {
6675 case Sema::TDK_Success:
6676 llvm_unreachable("TDK_success while diagnosing bad deduction");
6677
6678 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006679 assert(ParamD && "no parameter found for incomplete deduction result");
6680 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6681 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00006682 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00006683 return;
6684 }
6685
John McCall42d7d192010-08-05 09:05:08 +00006686 case Sema::TDK_Underqualified: {
6687 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6688 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6689
6690 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6691
6692 // Param will have been canonicalized, but it should just be a
6693 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00006694 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00006695 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00006696 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00006697 assert(S.Context.hasSameType(Param, NonCanonParam));
6698
6699 // Arg has also been canonicalized, but there's nothing we can do
6700 // about that. It also doesn't matter as much, because it won't
6701 // have any template parameters in it (because deduction isn't
6702 // done on dependent types).
6703 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6704
6705 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6706 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00006707 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00006708 return;
6709 }
6710
6711 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00006712 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006713 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006714 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006715 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006716 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006717 which = 1;
6718 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006719 which = 2;
6720 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006721
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006722 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006723 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006724 << *Cand->DeductionFailure.getFirstArg()
6725 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00006726 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006727 return;
6728 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006729
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006730 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006731 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006732 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006733 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006734 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6735 << ParamD->getDeclName();
6736 else {
6737 int index = 0;
6738 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6739 index = TTP->getIndex();
6740 else if (NonTypeTemplateParmDecl *NTTP
6741 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6742 index = NTTP->getIndex();
6743 else
6744 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006745 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006746 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6747 << (index + 1);
6748 }
Sebastian Redl08905022011-02-05 19:23:19 +00006749 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006750 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006751
Douglas Gregor02eb4832010-05-08 18:13:28 +00006752 case Sema::TDK_TooManyArguments:
6753 case Sema::TDK_TooFewArguments:
6754 DiagnoseArityMismatch(S, Cand, NumArgs);
6755 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006756
6757 case Sema::TDK_InstantiationDepth:
6758 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00006759 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00006760 return;
6761
6762 case Sema::TDK_SubstitutionFailure: {
6763 std::string ArgString;
6764 if (TemplateArgumentList *Args
6765 = Cand->DeductionFailure.getTemplateArgumentList())
6766 ArgString = S.getTemplateArgumentBindingsText(
6767 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6768 *Args);
6769 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6770 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00006771 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00006772 return;
6773 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006774
John McCall8b9ed552010-02-01 18:53:26 +00006775 // TODO: diagnose these individually, then kill off
6776 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006777 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006778 case Sema::TDK_FailedOverloadResolution:
6779 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00006780 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00006781 return;
6782 }
6783}
6784
6785/// Generates a 'note' diagnostic for an overload candidate. We've
6786/// already generated a primary error at the call site.
6787///
6788/// It really does need to be a single diagnostic with its caret
6789/// pointed at the candidate declaration. Yes, this creates some
6790/// major challenges of technical writing. Yes, this makes pointing
6791/// out problems with specific arguments quite awkward. It's still
6792/// better than generating twenty screens of text for every failed
6793/// overload.
6794///
6795/// It would be great to be able to express per-candidate problems
6796/// more richly for those diagnostic clients that cared, but we'd
6797/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006798void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6799 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006800 FunctionDecl *Fn = Cand->Function;
6801
John McCall12f97bc2010-01-08 04:41:39 +00006802 // Note deleted candidates, but only if they're viable.
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00006803 if (Cand->Viable && (Fn->isDeleted() || Fn->isUnavailable())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006804 std::string FnDesc;
6805 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006806
6807 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006808 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00006809 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00006810 return;
John McCall12f97bc2010-01-08 04:41:39 +00006811 }
6812
John McCalle1ac8d12010-01-13 00:25:19 +00006813 // We don't really have anything else to say about viable candidates.
6814 if (Cand->Viable) {
6815 S.NoteOverloadCandidate(Fn);
6816 return;
6817 }
John McCall0d1da222010-01-12 00:44:57 +00006818
John McCall6a61b522010-01-13 09:16:55 +00006819 switch (Cand->FailureKind) {
6820 case ovl_fail_too_many_arguments:
6821 case ovl_fail_too_few_arguments:
6822 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006823
John McCall6a61b522010-01-13 09:16:55 +00006824 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006825 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6826
John McCallfe796dd2010-01-23 05:17:32 +00006827 case ovl_fail_trivial_conversion:
6828 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006829 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006830 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006831
John McCall65eb8792010-02-25 01:37:24 +00006832 case ovl_fail_bad_conversion: {
6833 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6834 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006835 if (Cand->Conversions[I].isBad())
6836 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006837
John McCall6a61b522010-01-13 09:16:55 +00006838 // FIXME: this currently happens when we're called from SemaInit
6839 // when user-conversion overload fails. Figure out how to handle
6840 // those conditions and diagnose them well.
6841 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006842 }
John McCall65eb8792010-02-25 01:37:24 +00006843 }
John McCalld3224162010-01-08 00:58:21 +00006844}
6845
6846void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6847 // Desugar the type of the surrogate down to a function type,
6848 // retaining as many typedefs as possible while still showing
6849 // the function type (and, therefore, its parameter types).
6850 QualType FnType = Cand->Surrogate->getConversionType();
6851 bool isLValueReference = false;
6852 bool isRValueReference = false;
6853 bool isPointer = false;
6854 if (const LValueReferenceType *FnTypeRef =
6855 FnType->getAs<LValueReferenceType>()) {
6856 FnType = FnTypeRef->getPointeeType();
6857 isLValueReference = true;
6858 } else if (const RValueReferenceType *FnTypeRef =
6859 FnType->getAs<RValueReferenceType>()) {
6860 FnType = FnTypeRef->getPointeeType();
6861 isRValueReference = true;
6862 }
6863 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6864 FnType = FnTypePtr->getPointeeType();
6865 isPointer = true;
6866 }
6867 // Desugar down to a function type.
6868 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6869 // Reconstruct the pointer/reference as appropriate.
6870 if (isPointer) FnType = S.Context.getPointerType(FnType);
6871 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6872 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6873
6874 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6875 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00006876 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00006877}
6878
6879void NoteBuiltinOperatorCandidate(Sema &S,
6880 const char *Opc,
6881 SourceLocation OpLoc,
6882 OverloadCandidate *Cand) {
6883 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6884 std::string TypeStr("operator");
6885 TypeStr += Opc;
6886 TypeStr += "(";
6887 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6888 if (Cand->Conversions.size() == 1) {
6889 TypeStr += ")";
6890 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6891 } else {
6892 TypeStr += ", ";
6893 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6894 TypeStr += ")";
6895 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6896 }
6897}
6898
6899void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6900 OverloadCandidate *Cand) {
6901 unsigned NoOperands = Cand->Conversions.size();
6902 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6903 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006904 if (ICS.isBad()) break; // all meaningless after first invalid
6905 if (!ICS.isAmbiguous()) continue;
6906
John McCall5c32be02010-08-24 20:38:10 +00006907 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006908 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006909 }
6910}
6911
John McCall3712d9e2010-01-15 23:32:50 +00006912SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6913 if (Cand->Function)
6914 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006915 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006916 return Cand->Surrogate->getLocation();
6917 return SourceLocation();
6918}
6919
John McCallad2587a2010-01-12 00:48:53 +00006920struct CompareOverloadCandidatesForDisplay {
6921 Sema &S;
6922 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006923
6924 bool operator()(const OverloadCandidate *L,
6925 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006926 // Fast-path this check.
6927 if (L == R) return false;
6928
John McCall12f97bc2010-01-08 04:41:39 +00006929 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006930 if (L->Viable) {
6931 if (!R->Viable) return true;
6932
6933 // TODO: introduce a tri-valued comparison for overload
6934 // candidates. Would be more worthwhile if we had a sort
6935 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006936 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6937 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006938 } else if (R->Viable)
6939 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006940
John McCall3712d9e2010-01-15 23:32:50 +00006941 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006942
John McCall3712d9e2010-01-15 23:32:50 +00006943 // Criteria by which we can sort non-viable candidates:
6944 if (!L->Viable) {
6945 // 1. Arity mismatches come after other candidates.
6946 if (L->FailureKind == ovl_fail_too_many_arguments ||
6947 L->FailureKind == ovl_fail_too_few_arguments)
6948 return false;
6949 if (R->FailureKind == ovl_fail_too_many_arguments ||
6950 R->FailureKind == ovl_fail_too_few_arguments)
6951 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006952
John McCallfe796dd2010-01-23 05:17:32 +00006953 // 2. Bad conversions come first and are ordered by the number
6954 // of bad conversions and quality of good conversions.
6955 if (L->FailureKind == ovl_fail_bad_conversion) {
6956 if (R->FailureKind != ovl_fail_bad_conversion)
6957 return true;
6958
6959 // If there's any ordering between the defined conversions...
6960 // FIXME: this might not be transitive.
6961 assert(L->Conversions.size() == R->Conversions.size());
6962
6963 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006964 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6965 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006966 switch (CompareImplicitConversionSequences(S,
6967 L->Conversions[I],
6968 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006969 case ImplicitConversionSequence::Better:
6970 leftBetter++;
6971 break;
6972
6973 case ImplicitConversionSequence::Worse:
6974 leftBetter--;
6975 break;
6976
6977 case ImplicitConversionSequence::Indistinguishable:
6978 break;
6979 }
6980 }
6981 if (leftBetter > 0) return true;
6982 if (leftBetter < 0) return false;
6983
6984 } else if (R->FailureKind == ovl_fail_bad_conversion)
6985 return false;
6986
John McCall3712d9e2010-01-15 23:32:50 +00006987 // TODO: others?
6988 }
6989
6990 // Sort everything else by location.
6991 SourceLocation LLoc = GetLocationForCandidate(L);
6992 SourceLocation RLoc = GetLocationForCandidate(R);
6993
6994 // Put candidates without locations (e.g. builtins) at the end.
6995 if (LLoc.isInvalid()) return false;
6996 if (RLoc.isInvalid()) return true;
6997
6998 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006999 }
7000};
7001
John McCallfe796dd2010-01-23 05:17:32 +00007002/// CompleteNonViableCandidate - Normally, overload resolution only
7003/// computes up to the first
7004void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7005 Expr **Args, unsigned NumArgs) {
7006 assert(!Cand->Viable);
7007
7008 // Don't do anything on failures other than bad conversion.
7009 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7010
7011 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007012 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007013 unsigned ConvCount = Cand->Conversions.size();
7014 while (true) {
7015 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7016 ConvIdx++;
7017 if (Cand->Conversions[ConvIdx - 1].isBad())
7018 break;
7019 }
7020
7021 if (ConvIdx == ConvCount)
7022 return;
7023
John McCall65eb8792010-02-25 01:37:24 +00007024 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7025 "remaining conversion is initialized?");
7026
Douglas Gregoradc7a702010-04-16 17:45:54 +00007027 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007028 // operation somehow.
7029 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007030
7031 const FunctionProtoType* Proto;
7032 unsigned ArgIdx = ConvIdx;
7033
7034 if (Cand->IsSurrogate) {
7035 QualType ConvType
7036 = Cand->Surrogate->getConversionType().getNonReferenceType();
7037 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7038 ConvType = ConvPtrType->getPointeeType();
7039 Proto = ConvType->getAs<FunctionProtoType>();
7040 ArgIdx--;
7041 } else if (Cand->Function) {
7042 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7043 if (isa<CXXMethodDecl>(Cand->Function) &&
7044 !isa<CXXConstructorDecl>(Cand->Function))
7045 ArgIdx--;
7046 } else {
7047 // Builtin binary operator with a bad first conversion.
7048 assert(ConvCount <= 3);
7049 for (; ConvIdx != ConvCount; ++ConvIdx)
7050 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007051 = TryCopyInitialization(S, Args[ConvIdx],
7052 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007053 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007054 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00007055 return;
7056 }
7057
7058 // Fill in the rest of the conversions.
7059 unsigned NumArgsInProto = Proto->getNumArgs();
7060 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
7061 if (ArgIdx < NumArgsInProto)
7062 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007063 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007064 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007065 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00007066 else
7067 Cand->Conversions[ConvIdx].setEllipsis();
7068 }
7069}
7070
John McCalld3224162010-01-08 00:58:21 +00007071} // end anonymous namespace
7072
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007073/// PrintOverloadCandidates - When overload resolution fails, prints
7074/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007075/// set.
John McCall5c32be02010-08-24 20:38:10 +00007076void OverloadCandidateSet::NoteCandidates(Sema &S,
7077 OverloadCandidateDisplayKind OCD,
7078 Expr **Args, unsigned NumArgs,
7079 const char *Opc,
7080 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007081 // Sort the candidates by viability and position. Sorting directly would
7082 // be prohibitive, so we make a set of pointers and sort those.
7083 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007084 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7085 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007086 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007087 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007088 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007089 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007090 if (Cand->Function || Cand->IsSurrogate)
7091 Cands.push_back(Cand);
7092 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7093 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007094 }
7095 }
7096
John McCallad2587a2010-01-12 00:48:53 +00007097 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007098 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007099
John McCall0d1da222010-01-12 00:44:57 +00007100 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007101
John McCall12f97bc2010-01-08 04:41:39 +00007102 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00007103 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007104 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007105 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7106 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007107
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007108 // Set an arbitrary limit on the number of candidate functions we'll spam
7109 // the user with. FIXME: This limit should depend on details of the
7110 // candidate list.
7111 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7112 break;
7113 }
7114 ++CandsShown;
7115
John McCalld3224162010-01-08 00:58:21 +00007116 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007117 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007118 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007119 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007120 else {
7121 assert(Cand->Viable &&
7122 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007123 // Generally we only see ambiguities including viable builtin
7124 // operators if overload resolution got screwed up by an
7125 // ambiguous user-defined conversion.
7126 //
7127 // FIXME: It's quite possible for different conversions to see
7128 // different ambiguities, though.
7129 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007130 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007131 ReportedAmbiguousConversions = true;
7132 }
John McCalld3224162010-01-08 00:58:21 +00007133
John McCall0d1da222010-01-12 00:44:57 +00007134 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007135 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007136 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007137 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007138
7139 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007140 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007141}
7142
Douglas Gregorb491ed32011-02-19 21:32:49 +00007143// [PossiblyAFunctionType] --> [Return]
7144// NonFunctionType --> NonFunctionType
7145// R (A) --> R(A)
7146// R (*)(A) --> R (A)
7147// R (&)(A) --> R (A)
7148// R (S::*)(A) --> R (A)
7149QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7150 QualType Ret = PossiblyAFunctionType;
7151 if (const PointerType *ToTypePtr =
7152 PossiblyAFunctionType->getAs<PointerType>())
7153 Ret = ToTypePtr->getPointeeType();
7154 else if (const ReferenceType *ToTypeRef =
7155 PossiblyAFunctionType->getAs<ReferenceType>())
7156 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007157 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007158 PossiblyAFunctionType->getAs<MemberPointerType>())
7159 Ret = MemTypePtr->getPointeeType();
7160 Ret =
7161 Context.getCanonicalType(Ret).getUnqualifiedType();
7162 return Ret;
7163}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007164
Douglas Gregorb491ed32011-02-19 21:32:49 +00007165// A helper class to help with address of function resolution
7166// - allows us to avoid passing around all those ugly parameters
7167class AddressOfFunctionResolver
7168{
7169 Sema& S;
7170 Expr* SourceExpr;
7171 const QualType& TargetType;
7172 QualType TargetFunctionType; // Extracted function type from target type
7173
7174 bool Complain;
7175 //DeclAccessPair& ResultFunctionAccessPair;
7176 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007177
Douglas Gregorb491ed32011-02-19 21:32:49 +00007178 bool TargetTypeIsNonStaticMemberFunction;
7179 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007180
Douglas Gregorb491ed32011-02-19 21:32:49 +00007181 OverloadExpr::FindResult OvlExprInfo;
7182 OverloadExpr *OvlExpr;
7183 TemplateArgumentListInfo OvlExplicitTemplateArgs;
John McCalla0296f72010-03-19 07:35:19 +00007184 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007185
Douglas Gregorb491ed32011-02-19 21:32:49 +00007186public:
7187 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7188 const QualType& TargetType, bool Complain)
7189 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7190 Complain(Complain), Context(S.getASTContext()),
7191 TargetTypeIsNonStaticMemberFunction(
7192 !!TargetType->getAs<MemberPointerType>()),
7193 FoundNonTemplateFunction(false),
7194 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7195 OvlExpr(OvlExprInfo.Expression)
7196 {
7197 ExtractUnqualifiedFunctionTypeFromTargetType();
7198
7199 if (!TargetFunctionType->isFunctionType()) {
7200 if (OvlExpr->hasExplicitTemplateArgs()) {
7201 DeclAccessPair dap;
7202 if( FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
7203 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00007204
7205 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7206 if (!Method->isStatic()) {
7207 // If the target type is a non-function type and the function
7208 // found is a non-static member function, pretend as if that was
7209 // the target, it's the only possible type to end up with.
7210 TargetTypeIsNonStaticMemberFunction = true;
7211
7212 // And skip adding the function if its not in the proper form.
7213 // We'll diagnose this due to an empty set of functions.
7214 if (!OvlExprInfo.HasFormOfMemberPointer)
7215 return;
7216 }
7217 }
7218
Douglas Gregorb491ed32011-02-19 21:32:49 +00007219 Matches.push_back(std::make_pair(dap,Fn));
7220 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007221 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007222 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007223 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007224
7225 if (OvlExpr->hasExplicitTemplateArgs())
7226 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007227
Douglas Gregorb491ed32011-02-19 21:32:49 +00007228 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7229 // C++ [over.over]p4:
7230 // If more than one function is selected, [...]
7231 if (Matches.size() > 1) {
7232 if (FoundNonTemplateFunction)
7233 EliminateAllTemplateMatches();
7234 else
7235 EliminateAllExceptMostSpecializedTemplate();
7236 }
7237 }
7238 }
7239
7240private:
7241 bool isTargetTypeAFunction() const {
7242 return TargetFunctionType->isFunctionType();
7243 }
7244
7245 // [ToType] [Return]
7246
7247 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7248 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7249 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7250 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7251 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7252 }
7253
7254 // return true if any matching specializations were found
7255 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7256 const DeclAccessPair& CurAccessFunPair) {
7257 if (CXXMethodDecl *Method
7258 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7259 // Skip non-static function templates when converting to pointer, and
7260 // static when converting to member pointer.
7261 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7262 return false;
7263 }
7264 else if (TargetTypeIsNonStaticMemberFunction)
7265 return false;
7266
7267 // C++ [over.over]p2:
7268 // If the name is a function template, template argument deduction is
7269 // done (14.8.2.2), and if the argument deduction succeeds, the
7270 // resulting template argument list is used to generate a single
7271 // function template specialization, which is added to the set of
7272 // overloaded functions considered.
7273 FunctionDecl *Specialization = 0;
7274 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7275 if (Sema::TemplateDeductionResult Result
7276 = S.DeduceTemplateArguments(FunctionTemplate,
7277 &OvlExplicitTemplateArgs,
7278 TargetFunctionType, Specialization,
7279 Info)) {
7280 // FIXME: make a note of the failed deduction for diagnostics.
7281 (void)Result;
7282 return false;
7283 }
7284
7285 // Template argument deduction ensures that we have an exact match.
7286 // This function template specicalization works.
7287 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7288 assert(TargetFunctionType
7289 == Context.getCanonicalType(Specialization->getType()));
7290 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7291 return true;
7292 }
7293
7294 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7295 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007296 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007297 // Skip non-static functions when converting to pointer, and static
7298 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007299 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7300 return false;
7301 }
7302 else if (TargetTypeIsNonStaticMemberFunction)
7303 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007304
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007305 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007306 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007307 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7308 FunDecl->getType()) ||
7309 IsNoReturnConversion(Context, FunDecl->getType(), TargetFunctionType,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007310 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007311 Matches.push_back(std::make_pair(CurAccessFunPair,
7312 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007313 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007314 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007315 }
Mike Stump11289f42009-09-09 15:08:12 +00007316 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007317
7318 return false;
7319 }
7320
7321 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7322 bool Ret = false;
7323
7324 // If the overload expression doesn't have the form of a pointer to
7325 // member, don't try to convert it to a pointer-to-member type.
7326 if (IsInvalidFormOfPointerToMemberFunction())
7327 return false;
7328
7329 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7330 E = OvlExpr->decls_end();
7331 I != E; ++I) {
7332 // Look through any using declarations to find the underlying function.
7333 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7334
7335 // C++ [over.over]p3:
7336 // Non-member functions and static member functions match
7337 // targets of type "pointer-to-function" or "reference-to-function."
7338 // Nonstatic member functions match targets of
7339 // type "pointer-to-member-function."
7340 // Note that according to DR 247, the containing class does not matter.
7341 if (FunctionTemplateDecl *FunctionTemplate
7342 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7343 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7344 Ret = true;
7345 }
7346 // If we have explicit template arguments supplied, skip non-templates.
7347 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7348 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7349 Ret = true;
7350 }
7351 assert(Ret || Matches.empty());
7352 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007353 }
7354
Douglas Gregorb491ed32011-02-19 21:32:49 +00007355 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00007356 // [...] and any given function template specialization F1 is
7357 // eliminated if the set contains a second function template
7358 // specialization whose function template is more specialized
7359 // than the function template of F1 according to the partial
7360 // ordering rules of 14.5.5.2.
7361
7362 // The algorithm specified above is quadratic. We instead use a
7363 // two-pass algorithm (similar to the one used to identify the
7364 // best viable function in an overload set) that identifies the
7365 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007366
7367 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7368 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7369 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007370
John McCall58cc69d2010-01-27 01:50:18 +00007371 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007372 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7373 TPOC_Other, 0, SourceExpr->getLocStart(),
7374 S.PDiag(),
7375 S.PDiag(diag::err_addr_ovl_ambiguous)
7376 << Matches[0].second->getDeclName(),
7377 S.PDiag(diag::note_ovl_candidate)
7378 << (unsigned) oc_function_template,
7379 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007380
Douglas Gregorb491ed32011-02-19 21:32:49 +00007381 if (Result != MatchesCopy.end()) {
7382 // Make it the first and only element
7383 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7384 Matches[0].second = cast<FunctionDecl>(*Result);
7385 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00007386 }
7387 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007388
Douglas Gregorb491ed32011-02-19 21:32:49 +00007389 void EliminateAllTemplateMatches() {
7390 // [...] any function template specializations in the set are
7391 // eliminated if the set also contains a non-template function, [...]
7392 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7393 if (Matches[I].second->getPrimaryTemplate() == 0)
7394 ++I;
7395 else {
7396 Matches[I] = Matches[--N];
7397 Matches.set_size(N);
7398 }
7399 }
7400 }
7401
7402public:
7403 void ComplainNoMatchesFound() const {
7404 assert(Matches.empty());
7405 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7406 << OvlExpr->getName() << TargetFunctionType
7407 << OvlExpr->getSourceRange();
7408 S.NoteAllOverloadCandidates(OvlExpr);
7409 }
7410
7411 bool IsInvalidFormOfPointerToMemberFunction() const {
7412 return TargetTypeIsNonStaticMemberFunction &&
7413 !OvlExprInfo.HasFormOfMemberPointer;
7414 }
7415
7416 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7417 // TODO: Should we condition this on whether any functions might
7418 // have matched, or is it more appropriate to do that in callers?
7419 // TODO: a fixit wouldn't hurt.
7420 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7421 << TargetType << OvlExpr->getSourceRange();
7422 }
7423
7424 void ComplainOfInvalidConversion() const {
7425 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7426 << OvlExpr->getName() << TargetType;
7427 }
7428
7429 void ComplainMultipleMatchesFound() const {
7430 assert(Matches.size() > 1);
7431 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7432 << OvlExpr->getName()
7433 << OvlExpr->getSourceRange();
7434 S.NoteAllOverloadCandidates(OvlExpr);
7435 }
7436
7437 int getNumMatches() const { return Matches.size(); }
7438
7439 FunctionDecl* getMatchingFunctionDecl() const {
7440 if (Matches.size() != 1) return 0;
7441 return Matches[0].second;
7442 }
7443
7444 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7445 if (Matches.size() != 1) return 0;
7446 return &Matches[0].first;
7447 }
7448};
7449
7450/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7451/// an overloaded function (C++ [over.over]), where @p From is an
7452/// expression with overloaded function type and @p ToType is the type
7453/// we're trying to resolve to. For example:
7454///
7455/// @code
7456/// int f(double);
7457/// int f(int);
7458///
7459/// int (*pfd)(double) = f; // selects f(double)
7460/// @endcode
7461///
7462/// This routine returns the resulting FunctionDecl if it could be
7463/// resolved, and NULL otherwise. When @p Complain is true, this
7464/// routine will emit diagnostics if there is an error.
7465FunctionDecl *
7466Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7467 bool Complain,
7468 DeclAccessPair &FoundResult) {
7469
7470 assert(AddressOfExpr->getType() == Context.OverloadTy);
7471
7472 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7473 int NumMatches = Resolver.getNumMatches();
7474 FunctionDecl* Fn = 0;
7475 if ( NumMatches == 0 && Complain) {
7476 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7477 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7478 else
7479 Resolver.ComplainNoMatchesFound();
7480 }
7481 else if (NumMatches > 1 && Complain)
7482 Resolver.ComplainMultipleMatchesFound();
7483 else if (NumMatches == 1) {
7484 Fn = Resolver.getMatchingFunctionDecl();
7485 assert(Fn);
7486 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7487 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007488 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00007489 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007490 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007491
7492 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007493}
7494
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007495/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007496/// resolve that overloaded function expression down to a single function.
7497///
7498/// This routine can only resolve template-ids that refer to a single function
7499/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007500/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007501/// as described in C++0x [temp.arg.explicit]p3.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007502FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From,
7503 bool Complain,
7504 DeclAccessPair* FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007505 // C++ [over.over]p1:
7506 // [...] [Note: any redundant set of parentheses surrounding the
7507 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007508 // C++ [over.over]p1:
7509 // [...] The overloaded function name can be preceded by the &
7510 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00007511 if (From->getType() != Context.OverloadTy)
7512 return 0;
7513
John McCall8d08b9b2010-08-27 09:08:28 +00007514 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007515
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007516 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00007517 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007518 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007519
7520 TemplateArgumentListInfo ExplicitTemplateArgs;
7521 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007522
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007523 // Look through all of the overloaded functions, searching for one
7524 // whose type matches exactly.
7525 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00007526 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7527 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007528 // C++0x [temp.arg.explicit]p3:
7529 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007530 // where deduction is not done, if a template argument list is
7531 // specified and it, along with any default template arguments,
7532 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007533 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00007534 FunctionTemplateDecl *FunctionTemplate
7535 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007536
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007537 // C++ [over.over]p2:
7538 // If the name is a function template, template argument deduction is
7539 // done (14.8.2.2), and if the argument deduction succeeds, the
7540 // resulting template argument list is used to generate a single
7541 // function template specialization, which is added to the set of
7542 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007543 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00007544 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007545 if (TemplateDeductionResult Result
7546 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7547 Specialization, Info)) {
7548 // FIXME: make a note of the failed deduction for diagnostics.
7549 (void)Result;
7550 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007551 }
7552
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007553 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007554 if (Matched) {
7555 if (FoundResult)
7556 *FoundResult = DeclAccessPair();
7557
7558 if (Complain) {
7559 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
7560 << OvlExpr->getName();
7561 NoteAllOverloadCandidates(OvlExpr);
7562 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007563 return 0;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007564 }
7565
7566 if ((Matched = Specialization) && FoundResult)
7567 *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007568 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007569
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007570 return Matched;
7571}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007572
Douglas Gregor1beec452011-03-12 01:48:56 +00007573
7574
7575
7576// Resolve and fix an overloaded expression that
7577// can be resolved because it identifies a single function
7578// template specialization
7579// Last three arguments should only be supplied if Complain = true
7580ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
7581 Expr *SrcExpr, bool DoFunctionPointerConverion, bool Complain,
7582 const SourceRange& OpRangeForComplaining,
7583 QualType DestTypeForComplaining,
7584 unsigned DiagIDForComplaining ) {
7585
7586 assert(SrcExpr->getType() == Context.OverloadTy);
7587
7588 DeclAccessPair Found;
John Wiegley01296292011-04-08 18:41:53 +00007589 ExprResult SingleFunctionExpression;
Douglas Gregor1beec452011-03-12 01:48:56 +00007590 if (FunctionDecl* Fn = ResolveSingleFunctionTemplateSpecialization(
7591 SrcExpr, false, // false -> Complain
7592 &Found)) {
7593 if (!DiagnoseUseOfDecl(Fn, SrcExpr->getSourceRange().getBegin())) {
7594 // mark the expression as resolved to Fn
John Wiegley01296292011-04-08 18:41:53 +00007595 SingleFunctionExpression = Owned(FixOverloadedFunctionReference(SrcExpr,
7596 Found, Fn));
Douglas Gregor1beec452011-03-12 01:48:56 +00007597 if (DoFunctionPointerConverion)
John Wiegley01296292011-04-08 18:41:53 +00007598 SingleFunctionExpression =
7599 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
Douglas Gregor1beec452011-03-12 01:48:56 +00007600 }
7601 }
John Wiegley01296292011-04-08 18:41:53 +00007602 if (!SingleFunctionExpression.isUsable()) {
Douglas Gregor89f3cd52011-03-16 19:16:25 +00007603 if (Complain) {
7604 OverloadExpr* oe = OverloadExpr::find(SrcExpr).Expression;
7605 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
7606 << oe->getName() << DestTypeForComplaining << OpRangeForComplaining
7607 << oe->getQualifierLoc().getSourceRange();
7608 NoteAllOverloadCandidates(SrcExpr);
7609 }
7610 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00007611 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00007612
Douglas Gregor1beec452011-03-12 01:48:56 +00007613 return SingleFunctionExpression;
7614}
7615
Douglas Gregorcabea402009-09-22 15:41:20 +00007616/// \brief Add a single candidate to the overload set.
7617static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00007618 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00007619 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007620 Expr **Args, unsigned NumArgs,
7621 OverloadCandidateSet &CandidateSet,
7622 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00007623 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00007624 if (isa<UsingShadowDecl>(Callee))
7625 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7626
Douglas Gregorcabea402009-09-22 15:41:20 +00007627 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00007628 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00007629 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007630 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007631 return;
John McCalld14a8642009-11-21 08:51:07 +00007632 }
7633
7634 if (FunctionTemplateDecl *FuncTemplate
7635 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00007636 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7637 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007638 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00007639 return;
7640 }
7641
7642 assert(false && "unhandled case in overloaded call candidate");
7643
7644 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00007645}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007646
Douglas Gregorcabea402009-09-22 15:41:20 +00007647/// \brief Add the overload candidates named by callee and/or found by argument
7648/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00007649void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00007650 Expr **Args, unsigned NumArgs,
7651 OverloadCandidateSet &CandidateSet,
7652 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00007653
7654#ifndef NDEBUG
7655 // Verify that ArgumentDependentLookup is consistent with the rules
7656 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00007657 //
Douglas Gregorcabea402009-09-22 15:41:20 +00007658 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7659 // and let Y be the lookup set produced by argument dependent
7660 // lookup (defined as follows). If X contains
7661 //
7662 // -- a declaration of a class member, or
7663 //
7664 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00007665 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00007666 //
7667 // -- a declaration that is neither a function or a function
7668 // template
7669 //
7670 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00007671
John McCall57500772009-12-16 12:17:52 +00007672 if (ULE->requiresADL()) {
7673 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7674 E = ULE->decls_end(); I != E; ++I) {
7675 assert(!(*I)->getDeclContext()->isRecord());
7676 assert(isa<UsingShadowDecl>(*I) ||
7677 !(*I)->getDeclContext()->isFunctionOrMethod());
7678 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00007679 }
7680 }
7681#endif
7682
John McCall57500772009-12-16 12:17:52 +00007683 // It would be nice to avoid this copy.
7684 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00007685 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00007686 if (ULE->hasExplicitTemplateArgs()) {
7687 ULE->copyTemplateArgumentsInto(TABuffer);
7688 ExplicitTemplateArgs = &TABuffer;
7689 }
7690
7691 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7692 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00007693 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007694 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00007695 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00007696
John McCall57500772009-12-16 12:17:52 +00007697 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00007698 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7699 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007700 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007701 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00007702 PartialOverloading,
7703 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00007704}
John McCalld681c392009-12-16 08:11:27 +00007705
7706/// Attempts to recover from a call where no functions were found.
7707///
7708/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00007709static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007710BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00007711 UnresolvedLookupExpr *ULE,
7712 SourceLocation LParenLoc,
7713 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007714 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00007715
7716 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00007717 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00007718
John McCall57500772009-12-16 12:17:52 +00007719 TemplateArgumentListInfo TABuffer;
7720 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7721 if (ULE->hasExplicitTemplateArgs()) {
7722 ULE->copyTemplateArgumentsInto(TABuffer);
7723 ExplicitTemplateArgs = &TABuffer;
7724 }
7725
John McCalld681c392009-12-16 08:11:27 +00007726 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7727 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00007728 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00007729 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00007730
John McCall57500772009-12-16 12:17:52 +00007731 assert(!R.empty() && "lookup results empty despite recovery");
7732
7733 // Build an implicit member call if appropriate. Just drop the
7734 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00007735 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00007736 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00007737 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7738 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00007739 else if (ExplicitTemplateArgs)
7740 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7741 else
7742 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7743
7744 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007745 return ExprError();
John McCall57500772009-12-16 12:17:52 +00007746
7747 // This shouldn't cause an infinite loop because we're giving it
7748 // an expression with non-empty lookup results, which should never
7749 // end up here.
John McCallb268a282010-08-23 23:25:46 +00007750 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007751 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007752}
Douglas Gregor4038cf42010-06-08 17:35:15 +00007753
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007754/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00007755/// (which eventually refers to the declaration Func) and the call
7756/// arguments Args/NumArgs, attempt to resolve the function call down
7757/// to a specific function. If overload resolution succeeds, returns
7758/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00007759/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007760/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00007761ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007762Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00007763 SourceLocation LParenLoc,
7764 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00007765 SourceLocation RParenLoc,
7766 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00007767#ifndef NDEBUG
7768 if (ULE->requiresADL()) {
7769 // To do ADL, we must have found an unqualified name.
7770 assert(!ULE->getQualifier() && "qualified name with ADL");
7771
7772 // We don't perform ADL for implicit declarations of builtins.
7773 // Verify that this was correctly set up.
7774 FunctionDecl *F;
7775 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7776 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7777 F->getBuiltinID() && F->isImplicit())
7778 assert(0 && "performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007779
John McCall57500772009-12-16 12:17:52 +00007780 // We don't perform ADL in C.
7781 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00007782 } else
7783 assert(!ULE->isStdAssociatedNamespace() &&
7784 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00007785#endif
7786
John McCallbc077cf2010-02-08 23:07:23 +00007787 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007788
John McCall57500772009-12-16 12:17:52 +00007789 // Add the functions denoted by the callee to the set of candidate
7790 // functions, including those from argument-dependent lookup.
7791 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007792
7793 // If we found nothing, try to recover.
7794 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7795 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007796 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007797 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007798 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007799
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007800 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007801 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007802 case OR_Success: {
7803 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00007804 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00007805 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007806 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7807 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007808 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00007809 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
7810 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00007811 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007812
7813 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007814 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007815 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007816 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007817 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007818 break;
7819
7820 case OR_Ambiguous:
7821 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007822 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007823 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007824 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007825
7826 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00007827 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00007828 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7829 << Best->Function->isDeleted()
7830 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00007831 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00007832 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00007833 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
7834 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00007835 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007836 }
7837
Douglas Gregorb412e172010-07-25 18:17:45 +00007838 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007839 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007840}
7841
John McCall4c4c1df2010-01-26 03:27:55 +00007842static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007843 return Functions.size() > 1 ||
7844 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7845}
7846
Douglas Gregor084d8552009-03-13 23:49:33 +00007847/// \brief Create a unary operation that may resolve to an overloaded
7848/// operator.
7849///
7850/// \param OpLoc The location of the operator itself (e.g., '*').
7851///
7852/// \param OpcIn The UnaryOperator::Opcode that describes this
7853/// operator.
7854///
7855/// \param Functions The set of non-member functions that will be
7856/// considered by overload resolution. The caller needs to build this
7857/// set based on the context using, e.g.,
7858/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7859/// set should not contain any member functions; those will be added
7860/// by CreateOverloadedUnaryOp().
7861///
7862/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007863ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007864Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7865 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007866 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007867 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007868
7869 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7870 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7871 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007872 // TODO: provide better source location info.
7873 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007874
John Wiegley01296292011-04-08 18:41:53 +00007875 if (Input->getObjectKind() == OK_ObjCProperty) {
7876 ExprResult Result = ConvertPropertyForRValue(Input);
7877 if (Result.isInvalid())
7878 return ExprError();
7879 Input = Result.take();
7880 }
John McCalle26a8722010-12-04 08:14:53 +00007881
Douglas Gregor084d8552009-03-13 23:49:33 +00007882 Expr *Args[2] = { Input, 0 };
7883 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007884
Douglas Gregor084d8552009-03-13 23:49:33 +00007885 // For post-increment and post-decrement, add the implicit '0' as
7886 // the second argument, so that we know this is a post-increment or
7887 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007888 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007889 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007890 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7891 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007892 NumArgs = 2;
7893 }
7894
7895 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007896 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007897 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007898 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00007899 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007900 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00007901 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007902
John McCall58cc69d2010-01-27 01:50:18 +00007903 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007904 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007905 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00007906 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007907 /*ADL*/ true, IsOverloaded(Fns),
7908 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007909 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00007910 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00007911 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007912 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00007913 OpLoc));
7914 }
7915
7916 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007917 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007918
7919 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007920 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007921
7922 // Add operator candidates that are member functions.
7923 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7924
John McCall4c4c1df2010-01-26 03:27:55 +00007925 // Add candidates from ADL.
7926 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007927 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007928 /*ExplicitTemplateArgs*/ 0,
7929 CandidateSet);
7930
Douglas Gregor084d8552009-03-13 23:49:33 +00007931 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007932 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007933
7934 // Perform overload resolution.
7935 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007936 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007937 case OR_Success: {
7938 // We found a built-in operator or an overloaded operator.
7939 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007940
Douglas Gregor084d8552009-03-13 23:49:33 +00007941 if (FnDecl) {
7942 // We matched an overloaded operator. Build a call to that
7943 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007944
Chandler Carruth30141632011-02-25 19:41:05 +00007945 MarkDeclarationReferenced(OpLoc, FnDecl);
7946
Douglas Gregor084d8552009-03-13 23:49:33 +00007947 // Convert the arguments.
7948 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007949 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007950
John Wiegley01296292011-04-08 18:41:53 +00007951 ExprResult InputRes =
7952 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7953 Best->FoundDecl, Method);
7954 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007955 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00007956 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007957 } else {
7958 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007959 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007960 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007961 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007962 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007963 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007964 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007965 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007966 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007967 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007968 }
7969
John McCall4fa0d5f2010-05-06 18:15:07 +00007970 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7971
John McCall7decc9e2010-11-18 06:31:45 +00007972 // Determine the result type.
7973 QualType ResultTy = FnDecl->getResultType();
7974 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7975 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00007976
Douglas Gregor084d8552009-03-13 23:49:33 +00007977 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00007978 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl);
7979 if (FnExpr.isInvalid())
7980 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00007981
Eli Friedman030eee42009-11-18 03:58:17 +00007982 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007983 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00007984 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00007985 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007986
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007987 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007988 FnDecl))
7989 return ExprError();
7990
John McCallb268a282010-08-23 23:25:46 +00007991 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007992 } else {
7993 // We matched a built-in operator. Convert the arguments, then
7994 // break out so that we will build the appropriate built-in
7995 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00007996 ExprResult InputRes =
7997 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
7998 Best->Conversions[0], AA_Passing);
7999 if (InputRes.isInvalid())
8000 return ExprError();
8001 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008002 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00008003 }
John Wiegley01296292011-04-08 18:41:53 +00008004 }
8005
8006 case OR_No_Viable_Function:
8007 // No viable function; fall through to handling this as a
8008 // built-in operator, which will produce an error message for us.
8009 break;
8010
8011 case OR_Ambiguous:
8012 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8013 << UnaryOperator::getOpcodeStr(Opc)
8014 << Input->getType()
8015 << Input->getSourceRange();
8016 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
8017 Args, NumArgs,
8018 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8019 return ExprError();
8020
8021 case OR_Deleted:
8022 Diag(OpLoc, diag::err_ovl_deleted_oper)
8023 << Best->Function->isDeleted()
8024 << UnaryOperator::getOpcodeStr(Opc)
8025 << getDeletedOrUnavailableSuffix(Best->Function)
8026 << Input->getSourceRange();
8027 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8028 return ExprError();
8029 }
Douglas Gregor084d8552009-03-13 23:49:33 +00008030
8031 // Either we found no viable overloaded operator or we matched a
8032 // built-in operator. In either case, fall through to trying to
8033 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00008034 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008035}
8036
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008037/// \brief Create a binary operation that may resolve to an overloaded
8038/// operator.
8039///
8040/// \param OpLoc The location of the operator itself (e.g., '+').
8041///
8042/// \param OpcIn The BinaryOperator::Opcode that describes this
8043/// operator.
8044///
8045/// \param Functions The set of non-member functions that will be
8046/// considered by overload resolution. The caller needs to build this
8047/// set based on the context using, e.g.,
8048/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8049/// set should not contain any member functions; those will be added
8050/// by CreateOverloadedBinOp().
8051///
8052/// \param LHS Left-hand argument.
8053/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00008054ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008055Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008056 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00008057 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008058 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008059 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00008060 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008061
8062 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8063 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8064 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8065
8066 // If either side is type-dependent, create an appropriate dependent
8067 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00008068 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00008069 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008070 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00008071 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00008072 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00008073 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00008074 Context.DependentTy,
8075 VK_RValue, OK_Ordinary,
8076 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008077
Douglas Gregor5287f092009-11-05 00:51:44 +00008078 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8079 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008080 VK_LValue,
8081 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00008082 Context.DependentTy,
8083 Context.DependentTy,
8084 OpLoc));
8085 }
John McCall4c4c1df2010-01-26 03:27:55 +00008086
8087 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00008088 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008089 // TODO: provide better source location info in DNLoc component.
8090 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00008091 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00008092 = UnresolvedLookupExpr::Create(Context, NamingClass,
8093 NestedNameSpecifierLoc(), OpNameInfo,
8094 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008095 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008096 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00008097 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008098 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008099 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008100 OpLoc));
8101 }
8102
John McCalle26a8722010-12-04 08:14:53 +00008103 // Always do property rvalue conversions on the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008104 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8105 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8106 if (Result.isInvalid())
8107 return ExprError();
8108 Args[1] = Result.take();
8109 }
John McCalle26a8722010-12-04 08:14:53 +00008110
8111 // The LHS is more complicated.
8112 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8113
8114 // There's a tension for assignment operators between primitive
8115 // property assignment and the overloaded operators.
8116 if (BinaryOperator::isAssignmentOp(Opc)) {
8117 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8118
8119 // Is the property "logically" settable?
8120 bool Settable = (PRE->isExplicitProperty() ||
8121 PRE->getImplicitPropertySetter());
8122
8123 // To avoid gratuitously inventing semantics, use the primitive
8124 // unless it isn't. Thoughts in case we ever really care:
8125 // - If the property isn't logically settable, we have to
8126 // load and hope.
8127 // - If the property is settable and this is simple assignment,
8128 // we really should use the primitive.
8129 // - If the property is settable, then we could try overloading
8130 // on a generic lvalue of the appropriate type; if it works
8131 // out to a builtin candidate, we would do that same operation
8132 // on the property, and otherwise just error.
8133 if (Settable)
8134 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8135 }
8136
John Wiegley01296292011-04-08 18:41:53 +00008137 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8138 if (Result.isInvalid())
8139 return ExprError();
8140 Args[0] = Result.take();
John McCalle26a8722010-12-04 08:14:53 +00008141 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008142
Sebastian Redl6a96bf72009-11-18 23:10:33 +00008143 // If this is the assignment operator, we only perform overload resolution
8144 // if the left-hand side is a class or enumeration type. This is actually
8145 // a hack. The standard requires that we do overload resolution between the
8146 // various built-in candidates, but as DR507 points out, this can lead to
8147 // problems. So we do it this way, which pretty much follows what GCC does.
8148 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00008149 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00008150 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008151
John McCalle26a8722010-12-04 08:14:53 +00008152 // If this is the .* operator, which is not overloadable, just
8153 // create a built-in binary operator.
8154 if (Opc == BO_PtrMemD)
8155 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8156
Douglas Gregor084d8552009-03-13 23:49:33 +00008157 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008158 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008159
8160 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008161 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008162
8163 // Add operator candidates that are member functions.
8164 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8165
John McCall4c4c1df2010-01-26 03:27:55 +00008166 // Add candidates from ADL.
8167 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8168 Args, 2,
8169 /*ExplicitTemplateArgs*/ 0,
8170 CandidateSet);
8171
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008172 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008173 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008174
8175 // Perform overload resolution.
8176 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008177 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00008178 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008179 // We found a built-in operator or an overloaded operator.
8180 FunctionDecl *FnDecl = Best->Function;
8181
8182 if (FnDecl) {
8183 // We matched an overloaded operator. Build a call to that
8184 // operator.
8185
Chandler Carruth30141632011-02-25 19:41:05 +00008186 MarkDeclarationReferenced(OpLoc, FnDecl);
8187
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008188 // Convert the arguments.
8189 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00008190 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00008191 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008192
Chandler Carruth8e543b32010-12-12 08:17:55 +00008193 ExprResult Arg1 =
8194 PerformCopyInitialization(
8195 InitializedEntity::InitializeParameter(Context,
8196 FnDecl->getParamDecl(0)),
8197 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008198 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008199 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008200
John Wiegley01296292011-04-08 18:41:53 +00008201 ExprResult Arg0 =
8202 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8203 Best->FoundDecl, Method);
8204 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008205 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008206 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008207 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008208 } else {
8209 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00008210 ExprResult Arg0 = PerformCopyInitialization(
8211 InitializedEntity::InitializeParameter(Context,
8212 FnDecl->getParamDecl(0)),
8213 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008214 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008215 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008216
Chandler Carruth8e543b32010-12-12 08:17:55 +00008217 ExprResult Arg1 =
8218 PerformCopyInitialization(
8219 InitializedEntity::InitializeParameter(Context,
8220 FnDecl->getParamDecl(1)),
8221 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008222 if (Arg1.isInvalid())
8223 return ExprError();
8224 Args[0] = LHS = Arg0.takeAs<Expr>();
8225 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008226 }
8227
John McCall4fa0d5f2010-05-06 18:15:07 +00008228 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8229
John McCall7decc9e2010-11-18 06:31:45 +00008230 // Determine the result type.
8231 QualType ResultTy = FnDecl->getResultType();
8232 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8233 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008234
8235 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008236 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
8237 if (FnExpr.isInvalid())
8238 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008239
John McCallb268a282010-08-23 23:25:46 +00008240 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008241 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008242 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008243
8244 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008245 FnDecl))
8246 return ExprError();
8247
John McCallb268a282010-08-23 23:25:46 +00008248 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008249 } else {
8250 // We matched a built-in operator. Convert the arguments, then
8251 // break out so that we will build the appropriate built-in
8252 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008253 ExprResult ArgsRes0 =
8254 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8255 Best->Conversions[0], AA_Passing);
8256 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008257 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008258 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008259
John Wiegley01296292011-04-08 18:41:53 +00008260 ExprResult ArgsRes1 =
8261 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8262 Best->Conversions[1], AA_Passing);
8263 if (ArgsRes1.isInvalid())
8264 return ExprError();
8265 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008266 break;
8267 }
8268 }
8269
Douglas Gregor66950a32009-09-30 21:46:01 +00008270 case OR_No_Viable_Function: {
8271 // C++ [over.match.oper]p9:
8272 // If the operator is the operator , [...] and there are no
8273 // viable functions, then the operator is assumed to be the
8274 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00008275 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00008276 break;
8277
Chandler Carruth8e543b32010-12-12 08:17:55 +00008278 // For class as left operand for assignment or compound assigment
8279 // operator do not fall through to handling in built-in, but report that
8280 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00008281 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008282 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00008283 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00008284 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8285 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00008286 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00008287 } else {
8288 // No viable function; try to create a built-in operation, which will
8289 // produce an error. Then, show the non-viable candidates.
8290 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00008291 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008292 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00008293 "C++ binary operator overloading is missing candidates!");
8294 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00008295 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8296 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00008297 return move(Result);
8298 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008299
8300 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008301 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008302 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00008303 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00008304 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008305 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8306 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008307 return ExprError();
8308
8309 case OR_Deleted:
8310 Diag(OpLoc, diag::err_ovl_deleted_oper)
8311 << Best->Function->isDeleted()
8312 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008313 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00008314 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008315 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008316 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00008317 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008318
Douglas Gregor66950a32009-09-30 21:46:01 +00008319 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00008320 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008321}
8322
John McCalldadc5752010-08-24 06:29:42 +00008323ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00008324Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8325 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00008326 Expr *Base, Expr *Idx) {
8327 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00008328 DeclarationName OpName =
8329 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8330
8331 // If either side is type-dependent, create an appropriate dependent
8332 // expression.
8333 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8334
John McCall58cc69d2010-01-27 01:50:18 +00008335 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008336 // CHECKME: no 'operator' keyword?
8337 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8338 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00008339 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008340 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008341 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008342 /*ADL*/ true, /*Overloaded*/ false,
8343 UnresolvedSetIterator(),
8344 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00008345 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00008346
Sebastian Redladba46e2009-10-29 20:17:01 +00008347 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8348 Args, 2,
8349 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008350 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00008351 RLoc));
8352 }
8353
John Wiegley01296292011-04-08 18:41:53 +00008354 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8355 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8356 if (Result.isInvalid())
8357 return ExprError();
8358 Args[0] = Result.take();
8359 }
8360 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8361 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8362 if (Result.isInvalid())
8363 return ExprError();
8364 Args[1] = Result.take();
8365 }
John McCalle26a8722010-12-04 08:14:53 +00008366
Sebastian Redladba46e2009-10-29 20:17:01 +00008367 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008368 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008369
8370 // Subscript can only be overloaded as a member function.
8371
8372 // Add operator candidates that are member functions.
8373 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8374
8375 // Add builtin operator candidates.
8376 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8377
8378 // Perform overload resolution.
8379 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008380 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00008381 case OR_Success: {
8382 // We found a built-in operator or an overloaded operator.
8383 FunctionDecl *FnDecl = Best->Function;
8384
8385 if (FnDecl) {
8386 // We matched an overloaded operator. Build a call to that
8387 // operator.
8388
Chandler Carruth30141632011-02-25 19:41:05 +00008389 MarkDeclarationReferenced(LLoc, FnDecl);
8390
John McCalla0296f72010-03-19 07:35:19 +00008391 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008392 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00008393
Sebastian Redladba46e2009-10-29 20:17:01 +00008394 // Convert the arguments.
8395 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00008396 ExprResult Arg0 =
8397 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8398 Best->FoundDecl, Method);
8399 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00008400 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008401 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00008402
Anders Carlssona68e51e2010-01-29 18:37:50 +00008403 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008404 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00008405 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008406 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00008407 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008408 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00008409 Owned(Args[1]));
8410 if (InputInit.isInvalid())
8411 return ExprError();
8412
8413 Args[1] = InputInit.takeAs<Expr>();
8414
Sebastian Redladba46e2009-10-29 20:17:01 +00008415 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00008416 QualType ResultTy = FnDecl->getResultType();
8417 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8418 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00008419
8420 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008421 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
8422 if (FnExpr.isInvalid())
8423 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00008424
John McCallb268a282010-08-23 23:25:46 +00008425 CXXOperatorCallExpr *TheCall =
8426 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00008427 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00008428 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008429
John McCallb268a282010-08-23 23:25:46 +00008430 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00008431 FnDecl))
8432 return ExprError();
8433
John McCallb268a282010-08-23 23:25:46 +00008434 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00008435 } else {
8436 // We matched a built-in operator. Convert the arguments, then
8437 // break out so that we will build the appropriate built-in
8438 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008439 ExprResult ArgsRes0 =
8440 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8441 Best->Conversions[0], AA_Passing);
8442 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00008443 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008444 Args[0] = ArgsRes0.take();
8445
8446 ExprResult ArgsRes1 =
8447 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8448 Best->Conversions[1], AA_Passing);
8449 if (ArgsRes1.isInvalid())
8450 return ExprError();
8451 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00008452
8453 break;
8454 }
8455 }
8456
8457 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00008458 if (CandidateSet.empty())
8459 Diag(LLoc, diag::err_ovl_no_oper)
8460 << Args[0]->getType() << /*subscript*/ 0
8461 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
8462 else
8463 Diag(LLoc, diag::err_ovl_no_viable_subscript)
8464 << Args[0]->getType()
8465 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008466 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8467 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00008468 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00008469 }
8470
8471 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008472 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008473 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00008474 << Args[0]->getType() << Args[1]->getType()
8475 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008476 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8477 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008478 return ExprError();
8479
8480 case OR_Deleted:
8481 Diag(LLoc, diag::err_ovl_deleted_oper)
8482 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008483 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00008484 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008485 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8486 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008487 return ExprError();
8488 }
8489
8490 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00008491 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008492}
8493
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008494/// BuildCallToMemberFunction - Build a call to a member
8495/// function. MemExpr is the expression that refers to the member
8496/// function (and includes the object parameter), Args/NumArgs are the
8497/// arguments to the function call (not including the object
8498/// parameter). The caller needs to validate that the member
8499/// expression refers to a member function or an overloaded member
8500/// function.
John McCalldadc5752010-08-24 06:29:42 +00008501ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008502Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
8503 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008504 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008505 // Dig out the member expression. This holds both the object
8506 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00008507 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008508
John McCall10eae182009-11-30 22:42:35 +00008509 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008510 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00008511 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008512 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00008513 if (isa<MemberExpr>(NakedMemExpr)) {
8514 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00008515 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00008516 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008517 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00008518 } else {
8519 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008520 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008521
John McCall6e9f8f62009-12-03 04:06:58 +00008522 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00008523 Expr::Classification ObjectClassification
8524 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
8525 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00008526
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008527 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00008528 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00008529
John McCall2d74de92009-12-01 22:10:20 +00008530 // FIXME: avoid copy.
8531 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8532 if (UnresExpr->hasExplicitTemplateArgs()) {
8533 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8534 TemplateArgs = &TemplateArgsBuffer;
8535 }
8536
John McCall10eae182009-11-30 22:42:35 +00008537 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
8538 E = UnresExpr->decls_end(); I != E; ++I) {
8539
John McCall6e9f8f62009-12-03 04:06:58 +00008540 NamedDecl *Func = *I;
8541 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
8542 if (isa<UsingShadowDecl>(Func))
8543 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
8544
Douglas Gregor02824322011-01-26 19:30:28 +00008545
Francois Pichet64225792011-01-18 05:04:39 +00008546 // Microsoft supports direct constructor calls.
8547 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
8548 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
8549 CandidateSet);
8550 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00008551 // If explicit template arguments were provided, we can't call a
8552 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00008553 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00008554 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008555
John McCalla0296f72010-03-19 07:35:19 +00008556 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008557 ObjectClassification,
8558 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00008559 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008560 } else {
John McCall10eae182009-11-30 22:42:35 +00008561 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00008562 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008563 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00008564 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008565 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00008566 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00008567 }
Mike Stump11289f42009-09-09 15:08:12 +00008568
John McCall10eae182009-11-30 22:42:35 +00008569 DeclarationName DeclName = UnresExpr->getMemberName();
8570
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008571 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008572 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00008573 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008574 case OR_Success:
8575 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00008576 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00008577 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00008578 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008579 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008580 break;
8581
8582 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00008583 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008584 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008585 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008586 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008587 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008588 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008589
8590 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00008591 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00008592 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008593 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008594 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008595 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008596
8597 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00008598 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00008599 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008600 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008601 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008602 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008603 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008604 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00008605 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008606 }
8607
John McCall16df1e52010-03-30 21:47:33 +00008608 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00008609
John McCall2d74de92009-12-01 22:10:20 +00008610 // If overload resolution picked a static member, build a
8611 // non-member call based on that function.
8612 if (Method->isStatic()) {
8613 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
8614 Args, NumArgs, RParenLoc);
8615 }
8616
John McCall10eae182009-11-30 22:42:35 +00008617 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008618 }
8619
John McCall7decc9e2010-11-18 06:31:45 +00008620 QualType ResultType = Method->getResultType();
8621 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8622 ResultType = ResultType.getNonLValueExprType(Context);
8623
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008624 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008625 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00008626 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008627 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008628
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008629 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008630 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00008631 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00008632 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008633
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008634 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00008635 // We only need to do this if there was actually an overload; otherwise
8636 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00008637 if (!Method->isStatic()) {
8638 ExprResult ObjectArg =
8639 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
8640 FoundDecl, Method);
8641 if (ObjectArg.isInvalid())
8642 return ExprError();
8643 MemExpr->setBase(ObjectArg.take());
8644 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008645
8646 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00008647 const FunctionProtoType *Proto =
8648 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00008649 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008650 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00008651 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008652
John McCallb268a282010-08-23 23:25:46 +00008653 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00008654 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00008655
John McCallb268a282010-08-23 23:25:46 +00008656 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008657}
8658
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008659/// BuildCallToObjectOfClassType - Build a call to an object of class
8660/// type (C++ [over.call.object]), which can end up invoking an
8661/// overloaded function call operator (@c operator()) or performing a
8662/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00008663ExprResult
John Wiegley01296292011-04-08 18:41:53 +00008664Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00008665 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008666 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008667 SourceLocation RParenLoc) {
John Wiegley01296292011-04-08 18:41:53 +00008668 ExprResult Object = Owned(Obj);
8669 if (Object.get()->getObjectKind() == OK_ObjCProperty) {
8670 Object = ConvertPropertyForRValue(Object.take());
8671 if (Object.isInvalid())
8672 return ExprError();
8673 }
John McCalle26a8722010-12-04 08:14:53 +00008674
John Wiegley01296292011-04-08 18:41:53 +00008675 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
8676 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00008677
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008678 // C++ [over.call.object]p1:
8679 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00008680 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008681 // candidate functions includes at least the function call
8682 // operators of T. The function call operators of T are obtained by
8683 // ordinary lookup of the name operator() in the context of
8684 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00008685 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00008686 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008687
John Wiegley01296292011-04-08 18:41:53 +00008688 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00008689 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00008690 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008691 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008692
John McCall27b18f82009-11-17 02:14:36 +00008693 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8694 LookupQualifiedName(R, Record->getDecl());
8695 R.suppressDiagnostics();
8696
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008697 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00008698 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00008699 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
8700 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00008701 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00008702 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008703
Douglas Gregorab7897a2008-11-19 22:57:39 +00008704 // C++ [over.call.object]p2:
8705 // In addition, for each conversion function declared in T of the
8706 // form
8707 //
8708 // operator conversion-type-id () cv-qualifier;
8709 //
8710 // where cv-qualifier is the same cv-qualification as, or a
8711 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00008712 // denotes the type "pointer to function of (P1,...,Pn) returning
8713 // R", or the type "reference to pointer to function of
8714 // (P1,...,Pn) returning R", or the type "reference to function
8715 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00008716 // is also considered as a candidate function. Similarly,
8717 // surrogate call functions are added to the set of candidate
8718 // functions for each conversion function declared in an
8719 // accessible base class provided the function is not hidden
8720 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00008721 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00008722 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00008723 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00008724 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00008725 NamedDecl *D = *I;
8726 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8727 if (isa<UsingShadowDecl>(D))
8728 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008729
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008730 // Skip over templated conversion functions; they aren't
8731 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00008732 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008733 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00008734
John McCall6e9f8f62009-12-03 04:06:58 +00008735 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00008736
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008737 // Strip the reference type (if any) and then the pointer type (if
8738 // any) to get down to what might be a function type.
8739 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8740 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8741 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00008742
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008743 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00008744 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John Wiegley01296292011-04-08 18:41:53 +00008745 Object.get(), Args, NumArgs, CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008746 }
Mike Stump11289f42009-09-09 15:08:12 +00008747
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008748 // Perform overload resolution.
8749 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00008750 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00008751 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008752 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00008753 // Overload resolution succeeded; we'll build the appropriate call
8754 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008755 break;
8756
8757 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00008758 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00008759 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8760 << Object.get()->getType() << /*call*/ 1
8761 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00008762 else
John Wiegley01296292011-04-08 18:41:53 +00008763 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00008764 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00008765 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008766 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008767 break;
8768
8769 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00008770 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008771 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00008772 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008773 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008774 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008775
8776 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00008777 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00008778 diag::err_ovl_deleted_object_call)
8779 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +00008780 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008781 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +00008782 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008783 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008784 break;
Mike Stump11289f42009-09-09 15:08:12 +00008785 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008786
Douglas Gregorb412e172010-07-25 18:17:45 +00008787 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008788 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008789
Douglas Gregorab7897a2008-11-19 22:57:39 +00008790 if (Best->Function == 0) {
8791 // Since there is no function declaration, this is one of the
8792 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00008793 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00008794 = cast<CXXConversionDecl>(
8795 Best->Conversions[0].UserDefined.ConversionFunction);
8796
John Wiegley01296292011-04-08 18:41:53 +00008797 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008798 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008799
Douglas Gregorab7897a2008-11-19 22:57:39 +00008800 // We selected one of the surrogate functions that converts the
8801 // object parameter to a function pointer. Perform the conversion
8802 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008803
Fariborz Jahanian774cf792009-09-28 18:35:46 +00008804 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00008805 // and then call it.
John Wiegley01296292011-04-08 18:41:53 +00008806 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv);
Douglas Gregor668443e2011-01-20 00:18:04 +00008807 if (Call.isInvalid())
8808 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008809
Douglas Gregor668443e2011-01-20 00:18:04 +00008810 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008811 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008812 }
8813
Chandler Carruth30141632011-02-25 19:41:05 +00008814 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00008815 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008816 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008817
Douglas Gregorab7897a2008-11-19 22:57:39 +00008818 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8819 // that calls this method, using Object for the implicit object
8820 // parameter and passing along the remaining arguments.
8821 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008822 const FunctionProtoType *Proto =
8823 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008824
8825 unsigned NumArgsInProto = Proto->getNumArgs();
8826 unsigned NumArgsToCheck = NumArgs;
8827
8828 // Build the full argument list for the method call (the
8829 // implicit object parameter is placed at the beginning of the
8830 // list).
8831 Expr **MethodArgs;
8832 if (NumArgs < NumArgsInProto) {
8833 NumArgsToCheck = NumArgsInProto;
8834 MethodArgs = new Expr*[NumArgsInProto + 1];
8835 } else {
8836 MethodArgs = new Expr*[NumArgs + 1];
8837 }
John Wiegley01296292011-04-08 18:41:53 +00008838 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008839 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8840 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00008841
John Wiegley01296292011-04-08 18:41:53 +00008842 ExprResult NewFn = CreateFunctionRefExpr(*this, Method);
8843 if (NewFn.isInvalid())
8844 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008845
8846 // Once we've built TheCall, all of the expressions are properly
8847 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00008848 QualType ResultTy = Method->getResultType();
8849 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8850 ResultTy = ResultTy.getNonLValueExprType(Context);
8851
John McCallb268a282010-08-23 23:25:46 +00008852 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008853 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +00008854 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00008855 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008856 delete [] MethodArgs;
8857
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008858 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00008859 Method))
8860 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008861
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008862 // We may have default arguments. If so, we need to allocate more
8863 // slots in the call for them.
8864 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00008865 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008866 else if (NumArgs > NumArgsInProto)
8867 NumArgsToCheck = NumArgsInProto;
8868
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008869 bool IsError = false;
8870
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008871 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +00008872 ExprResult ObjRes =
8873 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
8874 Best->FoundDecl, Method);
8875 if (ObjRes.isInvalid())
8876 IsError = true;
8877 else
8878 Object = move(ObjRes);
8879 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008880
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008881 // Check the argument types.
8882 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008883 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008884 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008885 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00008886
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008887 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008888
John McCalldadc5752010-08-24 06:29:42 +00008889 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008890 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008891 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008892 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00008893 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008894
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008895 IsError |= InputInit.isInvalid();
8896 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008897 } else {
John McCalldadc5752010-08-24 06:29:42 +00008898 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008899 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8900 if (DefArg.isInvalid()) {
8901 IsError = true;
8902 break;
8903 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008904
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008905 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008906 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008907
8908 TheCall->setArg(i + 1, Arg);
8909 }
8910
8911 // If this is a variadic call, handle args passed through "...".
8912 if (Proto->isVariadic()) {
8913 // Promote the arguments (C99 6.5.2.2p7).
8914 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +00008915 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
8916 IsError |= Arg.isInvalid();
8917 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008918 }
8919 }
8920
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008921 if (IsError) return true;
8922
John McCallb268a282010-08-23 23:25:46 +00008923 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00008924 return true;
8925
John McCalle172be52010-08-24 06:09:16 +00008926 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008927}
8928
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008929/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00008930/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008931/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00008932ExprResult
John McCallb268a282010-08-23 23:25:46 +00008933Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008934 assert(Base->getType()->isRecordType() &&
8935 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00008936
John Wiegley01296292011-04-08 18:41:53 +00008937 if (Base->getObjectKind() == OK_ObjCProperty) {
8938 ExprResult Result = ConvertPropertyForRValue(Base);
8939 if (Result.isInvalid())
8940 return ExprError();
8941 Base = Result.take();
8942 }
John McCalle26a8722010-12-04 08:14:53 +00008943
John McCallbc077cf2010-02-08 23:07:23 +00008944 SourceLocation Loc = Base->getExprLoc();
8945
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008946 // C++ [over.ref]p1:
8947 //
8948 // [...] An expression x->m is interpreted as (x.operator->())->m
8949 // for a class object x of type T if T::operator->() exists and if
8950 // the operator is selected as the best match function by the
8951 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00008952 DeclarationName OpName =
8953 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00008954 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008955 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00008956
John McCallbc077cf2010-02-08 23:07:23 +00008957 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00008958 PDiag(diag::err_typecheck_incomplete_tag)
8959 << Base->getSourceRange()))
8960 return ExprError();
8961
John McCall27b18f82009-11-17 02:14:36 +00008962 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8963 LookupQualifiedName(R, BaseRecord->getDecl());
8964 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00008965
8966 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00008967 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00008968 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
8969 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00008970 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008971
8972 // Perform overload resolution.
8973 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008974 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008975 case OR_Success:
8976 // Overload resolution succeeded; we'll build the call below.
8977 break;
8978
8979 case OR_No_Viable_Function:
8980 if (CandidateSet.empty())
8981 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008982 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008983 else
8984 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008985 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008986 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008987 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008988
8989 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008990 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8991 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008992 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008993 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008994
8995 case OR_Deleted:
8996 Diag(OpLoc, diag::err_ovl_deleted_oper)
8997 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008998 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008999 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009000 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009001 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009002 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009003 }
9004
Chandler Carruth30141632011-02-25 19:41:05 +00009005 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00009006 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009007 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00009008
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009009 // Convert the object parameter.
9010 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009011 ExprResult BaseResult =
9012 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9013 Best->FoundDecl, Method);
9014 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +00009015 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009016 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +00009017
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009018 // Build the operator call.
John Wiegley01296292011-04-08 18:41:53 +00009019 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method);
9020 if (FnExpr.isInvalid())
9021 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009022
John McCall7decc9e2010-11-18 06:31:45 +00009023 QualType ResultTy = Method->getResultType();
9024 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9025 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00009026 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009027 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009028 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009029
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009030 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009031 Method))
9032 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +00009033
9034 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009035}
9036
Douglas Gregorcd695e52008-11-10 20:40:00 +00009037/// FixOverloadedFunctionReference - E is an expression that refers to
9038/// a C++ overloaded function (possibly with some parentheses and
9039/// perhaps a '&' around it). We have resolved the overloaded function
9040/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00009041/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00009042Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00009043 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00009044 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009045 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9046 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009047 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009048 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009049
Douglas Gregor51c538b2009-11-20 19:42:02 +00009050 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009051 }
9052
Douglas Gregor51c538b2009-11-20 19:42:02 +00009053 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009054 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9055 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009056 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00009057 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00009058 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00009059 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00009060 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009061 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009062
9063 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +00009064 ICE->getCastKind(),
9065 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00009066 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009067 }
9068
Douglas Gregor51c538b2009-11-20 19:42:02 +00009069 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00009070 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00009071 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009072 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9073 if (Method->isStatic()) {
9074 // Do nothing: static member functions aren't any different
9075 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00009076 } else {
John McCalle66edc12009-11-24 19:00:30 +00009077 // Fix the sub expression, which really has to be an
9078 // UnresolvedLookupExpr holding an overloaded member function
9079 // or template.
John McCall16df1e52010-03-30 21:47:33 +00009080 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9081 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00009082 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009083 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00009084
John McCalld14a8642009-11-21 08:51:07 +00009085 assert(isa<DeclRefExpr>(SubExpr)
9086 && "fixed to something other than a decl ref");
9087 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9088 && "fixed to a member ref with no nested name qualifier");
9089
9090 // We have taken the address of a pointer to member
9091 // function. Perform the computation here so that we get the
9092 // appropriate pointer to member type.
9093 QualType ClassType
9094 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9095 QualType MemPtrType
9096 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9097
John McCall7decc9e2010-11-18 06:31:45 +00009098 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9099 VK_RValue, OK_Ordinary,
9100 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009101 }
9102 }
John McCall16df1e52010-03-30 21:47:33 +00009103 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9104 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009105 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009106 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009107
John McCalle3027922010-08-25 11:45:40 +00009108 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009109 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00009110 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009111 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009112 }
John McCalld14a8642009-11-21 08:51:07 +00009113
9114 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00009115 // FIXME: avoid copy.
9116 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00009117 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00009118 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9119 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00009120 }
9121
John McCalld14a8642009-11-21 08:51:07 +00009122 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009123 ULE->getQualifierLoc(),
John McCalld14a8642009-11-21 08:51:07 +00009124 Fn,
9125 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009126 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009127 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00009128 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00009129 }
9130
John McCall10eae182009-11-30 22:42:35 +00009131 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00009132 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00009133 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9134 if (MemExpr->hasExplicitTemplateArgs()) {
9135 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9136 TemplateArgs = &TemplateArgsBuffer;
9137 }
John McCall6b51f282009-11-23 01:53:49 +00009138
John McCall2d74de92009-12-01 22:10:20 +00009139 Expr *Base;
9140
John McCall7decc9e2010-11-18 06:31:45 +00009141 // If we're filling in a static method where we used to have an
9142 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00009143 if (MemExpr->isImplicitAccess()) {
9144 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9145 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009146 MemExpr->getQualifierLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009147 Fn,
9148 MemExpr->getMemberLoc(),
9149 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009150 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00009151 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00009152 } else {
9153 SourceLocation Loc = MemExpr->getMemberLoc();
9154 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +00009155 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +00009156 Base = new (Context) CXXThisExpr(Loc,
9157 MemExpr->getBaseType(),
9158 /*isImplicit=*/true);
9159 }
John McCall2d74de92009-12-01 22:10:20 +00009160 } else
John McCallc3007a22010-10-26 07:05:15 +00009161 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00009162
9163 return MemberExpr::Create(Context, Base,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009164 MemExpr->isArrow(),
Douglas Gregorea972d32011-02-28 21:54:11 +00009165 MemExpr->getQualifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009166 Fn,
John McCall16df1e52010-03-30 21:47:33 +00009167 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009168 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00009169 TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009170 Fn->getType(),
9171 cast<CXXMethodDecl>(Fn)->isStatic()
9172 ? VK_LValue : VK_RValue,
9173 OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009174 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009175
John McCallc3007a22010-10-26 07:05:15 +00009176 llvm_unreachable("Invalid reference to overloaded function");
9177 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009178}
9179
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009180ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +00009181 DeclAccessPair Found,
9182 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00009183 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00009184}
9185
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009186} // end namespace clang