blob: 63d4f5ade3fca55dde31539fbf6b4fb5eb5ae345 [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,
Douglas Gregore9d62932011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
43 ExprResult E = S.Owned(new (S.Context) DeclRefExpr(Fn, Fn->getType(),
44 VK_LValue, Loc, LocInfo));
John Wiegley01296292011-04-08 18:41:53 +000045 E = S.DefaultFunctionArrayConversion(E.take());
46 if (E.isInvalid())
47 return ExprError();
48 return move(E);
John McCall7decc9e2010-11-18 06:31:45 +000049}
50
John McCall5c32be02010-08-24 20:38:10 +000051static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
52 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000053 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000054 bool CStyle,
55 bool AllowObjCWritebackConversion);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000056
57static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
58 QualType &ToType,
59 bool InOverloadResolution,
60 StandardConversionSequence &SCS,
61 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000062static OverloadingResult
63IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
64 UserDefinedConversionSequence& User,
65 OverloadCandidateSet& Conversions,
66 bool AllowExplicit);
67
68
69static ImplicitConversionSequence::CompareKind
70CompareStandardConversionSequences(Sema &S,
71 const StandardConversionSequence& SCS1,
72 const StandardConversionSequence& SCS2);
73
74static ImplicitConversionSequence::CompareKind
75CompareQualificationConversions(Sema &S,
76 const StandardConversionSequence& SCS1,
77 const StandardConversionSequence& SCS2);
78
79static ImplicitConversionSequence::CompareKind
80CompareDerivedToBaseConversions(Sema &S,
81 const StandardConversionSequence& SCS1,
82 const StandardConversionSequence& SCS2);
83
84
85
Douglas Gregor5251f1b2008-10-21 16:13:35 +000086/// GetConversionCategory - Retrieve the implicit conversion
87/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000088ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000089GetConversionCategory(ImplicitConversionKind Kind) {
90 static const ImplicitConversionCategory
91 Category[(int)ICK_Num_Conversion_Kinds] = {
92 ICC_Identity,
93 ICC_Lvalue_Transformation,
94 ICC_Lvalue_Transformation,
95 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000096 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000097 ICC_Qualification_Adjustment,
98 ICC_Promotion,
99 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 ICC_Promotion,
101 ICC_Conversion,
102 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000103 ICC_Conversion,
104 ICC_Conversion,
105 ICC_Conversion,
106 ICC_Conversion,
107 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000109 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000110 ICC_Conversion,
111 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000112 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000113 ICC_Conversion
114 };
115 return Category[(int)Kind];
116}
117
118/// GetConversionRank - Retrieve the implicit conversion rank
119/// corresponding to the given implicit conversion kind.
120ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
121 static const ImplicitConversionRank
122 Rank[(int)ICK_Num_Conversion_Kinds] = {
123 ICR_Exact_Match,
124 ICR_Exact_Match,
125 ICR_Exact_Match,
126 ICR_Exact_Match,
127 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000128 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000129 ICR_Promotion,
130 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000131 ICR_Promotion,
132 ICR_Conversion,
133 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000134 ICR_Conversion,
135 ICR_Conversion,
136 ICR_Conversion,
137 ICR_Conversion,
138 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000139 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000140 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000141 ICR_Conversion,
142 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000143 ICR_Complex_Real_Conversion,
144 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000145 ICR_Conversion,
146 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 };
148 return Rank[(int)Kind];
149}
150
151/// GetImplicitConversionName - Return the name of this kind of
152/// implicit conversion.
153const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000154 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000155 "No conversion",
156 "Lvalue-to-rvalue",
157 "Array-to-pointer",
158 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000159 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000160 "Qualification",
161 "Integral promotion",
162 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000163 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000164 "Integral conversion",
165 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000166 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000167 "Floating-integral conversion",
168 "Pointer conversion",
169 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000170 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000171 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000172 "Derived-to-base conversion",
173 "Vector conversion",
174 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000175 "Complex-real conversion",
176 "Block Pointer conversion",
177 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000178 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000179 };
180 return Name[Kind];
181}
182
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000183/// StandardConversionSequence - Set the standard conversion
184/// sequence to the identity conversion.
185void StandardConversionSequence::setAsIdentityConversion() {
186 First = ICK_Identity;
187 Second = ICK_Identity;
188 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000189 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000190 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000191 ReferenceBinding = false;
192 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000193 IsLvalueReference = true;
194 BindsToFunctionLvalue = false;
195 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000196 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000197 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000198 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000199}
200
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000201/// getRank - Retrieve the rank of this standard conversion sequence
202/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203/// implicit conversions.
204ImplicitConversionRank StandardConversionSequence::getRank() const {
205 ImplicitConversionRank Rank = ICR_Exact_Match;
206 if (GetConversionRank(First) > Rank)
207 Rank = GetConversionRank(First);
208 if (GetConversionRank(Second) > Rank)
209 Rank = GetConversionRank(Second);
210 if (GetConversionRank(Third) > Rank)
211 Rank = GetConversionRank(Third);
212 return Rank;
213}
214
215/// isPointerConversionToBool - Determines whether this conversion is
216/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000217/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000219bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer or function-to-pointer implicit conversions, so
222 // check for their presence as well as checking whether FromType is
223 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000224 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000225 (getFromType()->isPointerType() ||
226 getFromType()->isObjCObjectPointerType() ||
227 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000228 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230 return true;
231
232 return false;
233}
234
Douglas Gregor5c407d92008-10-23 00:40:37 +0000235/// isPointerConversionToVoidPointer - Determines whether this
236/// conversion is a conversion of a pointer to a void pointer. This is
237/// used as part of the ranking of standard conversion sequences (C++
238/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000239bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000240StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000241isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000242 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000243 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000244
245 // Note that FromType has not necessarily been transformed by the
246 // array-to-pointer implicit conversion, so check for its presence
247 // and redo the conversion to get a pointer.
248 if (First == ICK_Array_To_Pointer)
249 FromType = Context.getArrayDecayedType(FromType);
250
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000253 return ToPtrType->getPointeeType()->isVoidType();
254
255 return false;
256}
257
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000258/// DebugPrint - Print this standard conversion sequence to standard
259/// error. Useful for debugging overloading issues.
260void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000261 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000262 bool PrintedSomething = false;
263 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000264 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 PrintedSomething = true;
266 }
267
268 if (Second != ICK_Identity) {
269 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000270 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000271 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000272 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000273
274 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000275 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000276 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000277 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000278 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000279 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000280 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000281 PrintedSomething = true;
282 }
283
284 if (Third != ICK_Identity) {
285 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000286 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000287 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000288 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000289 PrintedSomething = true;
290 }
291
292 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000293 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000294 }
295}
296
297/// DebugPrint - Print this user-defined conversion sequence to standard
298/// error. Useful for debugging overloading issues.
299void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000300 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000301 if (Before.First || Before.Second || Before.Third) {
302 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000303 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000304 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000305 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000306 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000307 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000308 After.DebugPrint();
309 }
310}
311
312/// DebugPrint - Print this implicit conversion sequence to standard
313/// error. Useful for debugging overloading issues.
314void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000315 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000316 switch (ConversionKind) {
317 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000318 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000319 Standard.DebugPrint();
320 break;
321 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000322 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000323 UserDefined.DebugPrint();
324 break;
325 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000326 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000327 break;
John McCall0d1da222010-01-12 00:44:57 +0000328 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000329 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000330 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000331 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000332 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000333 break;
334 }
335
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000336 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000337}
338
John McCall0d1da222010-01-12 00:44:57 +0000339void AmbiguousConversionSequence::construct() {
340 new (&conversions()) ConversionSet();
341}
342
343void AmbiguousConversionSequence::destruct() {
344 conversions().~ConversionSet();
345}
346
347void
348AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
349 FromTypePtr = O.FromTypePtr;
350 ToTypePtr = O.ToTypePtr;
351 new (&conversions()) ConversionSet(O.conversions());
352}
353
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000354namespace {
355 // Structure used by OverloadCandidate::DeductionFailureInfo to store
356 // template parameter and template argument information.
357 struct DFIParamWithArguments {
358 TemplateParameter Param;
359 TemplateArgument FirstArg;
360 TemplateArgument SecondArg;
361 };
362}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000363
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000364/// \brief Convert from Sema's representation of template deduction information
365/// to the form used in overload-candidate information.
366OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000367static MakeDeductionFailureInfo(ASTContext &Context,
368 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000369 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000370 OverloadCandidate::DeductionFailureInfo Result;
371 Result.Result = static_cast<unsigned>(TDK);
372 Result.Data = 0;
373 switch (TDK) {
374 case Sema::TDK_Success:
375 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000376 case Sema::TDK_TooManyArguments:
377 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000378 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000379
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000380 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000381 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000382 Result.Data = Info.Param.getOpaqueValue();
383 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000384
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000385 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000386 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000387 // FIXME: Should allocate from normal heap so that we can free this later.
388 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000389 Saved->Param = Info.Param;
390 Saved->FirstArg = Info.FirstArg;
391 Saved->SecondArg = Info.SecondArg;
392 Result.Data = Saved;
393 break;
394 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000395
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000396 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000397 Result.Data = Info.take();
398 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000399
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000400 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000401 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000402 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000404
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000405 return Result;
406}
John McCall0d1da222010-01-12 00:44:57 +0000407
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000408void OverloadCandidate::DeductionFailureInfo::Destroy() {
409 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
410 case Sema::TDK_Success:
411 case Sema::TDK_InstantiationDepth:
412 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000413 case Sema::TDK_TooManyArguments:
414 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000415 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000416 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000417
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000418 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000419 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000420 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000421 Data = 0;
422 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000423
424 case Sema::TDK_SubstitutionFailure:
425 // FIXME: Destroy the template arugment list?
426 Data = 0;
427 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000428
Douglas Gregor461761d2010-05-08 18:20:53 +0000429 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000430 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000431 case Sema::TDK_FailedOverloadResolution:
432 break;
433 }
434}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000435
436TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000437OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
438 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
439 case Sema::TDK_Success:
440 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000441 case Sema::TDK_TooManyArguments:
442 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000443 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000444 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000445
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000446 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000447 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000448 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000449
450 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000451 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000452 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000453
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000454 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000455 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000456 case Sema::TDK_FailedOverloadResolution:
457 break;
458 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000459
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000460 return TemplateParameter();
461}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000462
Douglas Gregord09efd42010-05-08 20:07:26 +0000463TemplateArgumentList *
464OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
465 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
466 case Sema::TDK_Success:
467 case Sema::TDK_InstantiationDepth:
468 case Sema::TDK_TooManyArguments:
469 case Sema::TDK_TooFewArguments:
470 case Sema::TDK_Incomplete:
471 case Sema::TDK_InvalidExplicitArguments:
472 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000473 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000474 return 0;
475
476 case Sema::TDK_SubstitutionFailure:
477 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000478
Douglas Gregord09efd42010-05-08 20:07:26 +0000479 // Unhandled
480 case Sema::TDK_NonDeducedMismatch:
481 case Sema::TDK_FailedOverloadResolution:
482 break;
483 }
484
485 return 0;
486}
487
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000488const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
489 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
490 case Sema::TDK_Success:
491 case Sema::TDK_InstantiationDepth:
492 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000493 case Sema::TDK_TooManyArguments:
494 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000495 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000496 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000497 return 0;
498
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000499 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000500 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000501 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000502
Douglas Gregor461761d2010-05-08 18:20:53 +0000503 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000504 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000505 case Sema::TDK_FailedOverloadResolution:
506 break;
507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000508
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000509 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000510}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000511
512const TemplateArgument *
513OverloadCandidate::DeductionFailureInfo::getSecondArg() {
514 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
515 case Sema::TDK_Success:
516 case Sema::TDK_InstantiationDepth:
517 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000518 case Sema::TDK_TooManyArguments:
519 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000520 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000521 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000522 return 0;
523
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000524 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000525 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000526 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
527
Douglas Gregor461761d2010-05-08 18:20:53 +0000528 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000529 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000530 case Sema::TDK_FailedOverloadResolution:
531 break;
532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000534 return 0;
535}
536
537void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000538 inherited::clear();
539 Functions.clear();
540}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000541
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000542// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000543// overload of the declarations in Old. This routine returns false if
544// New and Old cannot be overloaded, e.g., if New has the same
545// signature as some function in Old (C++ 1.3.10) or if the Old
546// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000547// it does return false, MatchedDecl will point to the decl that New
548// cannot be overloaded with. This decl may be a UsingShadowDecl on
549// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000550//
551// Example: Given the following input:
552//
553// void f(int, float); // #1
554// void f(int, int); // #2
555// int f(int, int); // #3
556//
557// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000558// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000559//
John McCall3d988d92009-12-02 08:47:38 +0000560// When we process #2, Old contains only the FunctionDecl for #1. By
561// comparing the parameter types, we see that #1 and #2 are overloaded
562// (since they have different signatures), so this routine returns
563// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000564//
John McCall3d988d92009-12-02 08:47:38 +0000565// When we process #3, Old is an overload set containing #1 and #2. We
566// compare the signatures of #3 to #1 (they're overloaded, so we do
567// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
568// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000569// signature), IsOverload returns false and MatchedDecl will be set to
570// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000571//
572// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
573// into a class by a using declaration. The rules for whether to hide
574// shadow declarations ignore some properties which otherwise figure
575// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000576Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000577Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
578 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000579 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000580 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000581 NamedDecl *OldD = *I;
582
583 bool OldIsUsingDecl = false;
584 if (isa<UsingShadowDecl>(OldD)) {
585 OldIsUsingDecl = true;
586
587 // We can always introduce two using declarations into the same
588 // context, even if they have identical signatures.
589 if (NewIsUsingDecl) continue;
590
591 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
592 }
593
594 // If either declaration was introduced by a using declaration,
595 // we'll need to use slightly different rules for matching.
596 // Essentially, these rules are the normal rules, except that
597 // function templates hide function templates with different
598 // return types or template parameter lists.
599 bool UseMemberUsingDeclRules =
600 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
601
John McCall3d988d92009-12-02 08:47:38 +0000602 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000603 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
604 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
605 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
606 continue;
607 }
608
John McCalldaa3d6b2009-12-09 03:35:25 +0000609 Match = *I;
610 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000611 }
John McCall3d988d92009-12-02 08:47:38 +0000612 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000613 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
614 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
615 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
616 continue;
617 }
618
John McCalldaa3d6b2009-12-09 03:35:25 +0000619 Match = *I;
620 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000621 }
John McCalla8987a2942010-11-10 03:01:53 +0000622 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000623 // We can overload with these, which can show up when doing
624 // redeclaration checks for UsingDecls.
625 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000626 } else if (isa<TagDecl>(OldD)) {
627 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000628 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
629 // Optimistically assume that an unresolved using decl will
630 // overload; if it doesn't, we'll have to diagnose during
631 // template instantiation.
632 } else {
John McCall1f82f242009-11-18 22:49:29 +0000633 // (C++ 13p1):
634 // Only function declarations can be overloaded; object and type
635 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000636 Match = *I;
637 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000638 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000639 }
John McCall1f82f242009-11-18 22:49:29 +0000640
John McCalldaa3d6b2009-12-09 03:35:25 +0000641 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000642}
643
John McCalle9cccd82010-06-16 08:42:20 +0000644bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
645 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000646 // If both of the functions are extern "C", then they are not
647 // overloads.
648 if (Old->isExternC() && New->isExternC())
649 return false;
650
John McCall1f82f242009-11-18 22:49:29 +0000651 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
652 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
653
654 // C++ [temp.fct]p2:
655 // A function template can be overloaded with other function templates
656 // and with normal (non-template) functions.
657 if ((OldTemplate == 0) != (NewTemplate == 0))
658 return true;
659
660 // Is the function New an overload of the function Old?
661 QualType OldQType = Context.getCanonicalType(Old->getType());
662 QualType NewQType = Context.getCanonicalType(New->getType());
663
664 // Compare the signatures (C++ 1.3.10) of the two functions to
665 // determine whether they are overloads. If we find any mismatch
666 // in the signature, they are overloads.
667
668 // If either of these functions is a K&R-style function (no
669 // prototype), then we consider them to have matching signatures.
670 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
671 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
672 return false;
673
John McCall424cec92011-01-19 06:33:43 +0000674 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
675 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000676
677 // The signature of a function includes the types of its
678 // parameters (C++ 1.3.10), which includes the presence or absence
679 // of the ellipsis; see C++ DR 357).
680 if (OldQType != NewQType &&
681 (OldType->getNumArgs() != NewType->getNumArgs() ||
682 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000683 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000684 return true;
685
686 // C++ [temp.over.link]p4:
687 // The signature of a function template consists of its function
688 // signature, its return type and its template parameter list. The names
689 // of the template parameters are significant only for establishing the
690 // relationship between the template parameters and the rest of the
691 // signature.
692 //
693 // We check the return type and template parameter lists for function
694 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000695 //
696 // However, we don't consider either of these when deciding whether
697 // a member introduced by a shadow declaration is hidden.
698 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000699 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
700 OldTemplate->getTemplateParameters(),
701 false, TPL_TemplateMatch) ||
702 OldType->getResultType() != NewType->getResultType()))
703 return true;
704
705 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000706 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000707 //
708 // As part of this, also check whether one of the member functions
709 // is static, in which case they are not overloads (C++
710 // 13.1p2). While not part of the definition of the signature,
711 // this check is important to determine whether these functions
712 // can be overloaded.
713 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
714 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
715 if (OldMethod && NewMethod &&
716 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000717 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000718 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
719 if (!UseUsingDeclRules &&
720 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
721 (OldMethod->getRefQualifier() == RQ_None ||
722 NewMethod->getRefQualifier() == RQ_None)) {
723 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000724 // - Member function declarations with the same name and the same
725 // parameter-type-list as well as member function template
726 // declarations with the same name, the same parameter-type-list, and
727 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000728 // them, but not all, have a ref-qualifier (8.3.5).
729 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
730 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
731 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
732 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000733
John McCall1f82f242009-11-18 22:49:29 +0000734 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000736
John McCall1f82f242009-11-18 22:49:29 +0000737 // The signatures match; this is not an overload.
738 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000739}
740
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000741/// \brief Checks availability of the function depending on the current
742/// function context. Inside an unavailable function, unavailability is ignored.
743///
744/// \returns true if \arg FD is unavailable and current context is inside
745/// an available function, false otherwise.
746bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
747 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
748}
749
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000750/// TryImplicitConversion - Attempt to perform an implicit conversion
751/// from the given expression (Expr) to the given type (ToType). This
752/// function returns an implicit conversion sequence that can be used
753/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000754///
755/// void f(float f);
756/// void g(int i) { f(i); }
757///
758/// this routine would produce an implicit conversion sequence to
759/// describe the initialization of f from i, which will be a standard
760/// conversion sequence containing an lvalue-to-rvalue conversion (C++
761/// 4.1) followed by a floating-integral conversion (C++ 4.9).
762//
763/// Note that this routine only determines how the conversion can be
764/// performed; it does not actually perform the conversion. As such,
765/// it will not produce any diagnostics if no conversion is available,
766/// but will instead return an implicit conversion sequence of kind
767/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000768///
769/// If @p SuppressUserConversions, then user-defined conversions are
770/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000771/// If @p AllowExplicit, then explicit user-defined conversions are
772/// permitted.
John McCall31168b02011-06-15 23:02:42 +0000773///
774/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
775/// writeback conversion, which allows __autoreleasing id* parameters to
776/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +0000777static ImplicitConversionSequence
778TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
779 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000780 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000781 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000782 bool CStyle,
783 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000784 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000785 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000786 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +0000787 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000788 return ICS;
789 }
790
John McCall5c32be02010-08-24 20:38:10 +0000791 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000792 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000793 return ICS;
794 }
795
Douglas Gregor836a7e82010-08-11 02:15:33 +0000796 // C++ [over.ics.user]p4:
797 // A conversion of an expression of class type to the same class
798 // type is given Exact Match rank, and a conversion of an
799 // expression of class type to a base class of that type is
800 // given Conversion rank, in spite of the fact that a copy/move
801 // constructor (i.e., a user-defined conversion function) is
802 // called for those cases.
803 QualType FromType = From->getType();
804 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000805 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
806 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000807 ICS.setStandard();
808 ICS.Standard.setAsIdentityConversion();
809 ICS.Standard.setFromType(FromType);
810 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000811
Douglas Gregor5ab11652010-04-17 22:01:05 +0000812 // We don't actually check at this point whether there is a valid
813 // copy/move constructor, since overloading just assumes that it
814 // exists. When we actually perform initialization, we'll find the
815 // appropriate constructor to copy the returned object, if needed.
816 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817
Douglas Gregor5ab11652010-04-17 22:01:05 +0000818 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000819 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000820 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000821
Douglas Gregor836a7e82010-08-11 02:15:33 +0000822 return ICS;
823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824
Douglas Gregor836a7e82010-08-11 02:15:33 +0000825 if (SuppressUserConversions) {
826 // We're not in the case above, so there is no conversion that
827 // we can perform.
828 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000829 return ICS;
830 }
831
832 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000833 OverloadCandidateSet Conversions(From->getExprLoc());
834 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000835 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000836 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000837
838 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000839 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000840 // C++ [over.ics.user]p4:
841 // A conversion of an expression of class type to the same class
842 // type is given Exact Match rank, and a conversion of an
843 // expression of class type to a base class of that type is
844 // given Conversion rank, in spite of the fact that a copy
845 // constructor (i.e., a user-defined conversion function) is
846 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000847 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000848 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000849 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000850 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
851 QualType ToCanon
852 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000853 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000854 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000855 // Turn this into a "standard" conversion sequence, so that it
856 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000857 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000858 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000859 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000860 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000861 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000862 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000863 ICS.Standard.Second = ICK_Derived_To_Base;
864 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000865 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000866
867 // C++ [over.best.ics]p4:
868 // However, when considering the argument of a user-defined
869 // conversion function that is a candidate by 13.3.1.3 when
870 // invoked for the copying of the temporary in the second step
871 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
872 // 13.3.1.6 in all cases, only standard conversion sequences and
873 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000874 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000875 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000876 }
John McCalle8c8cd22010-01-13 22:30:33 +0000877 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000878 ICS.setAmbiguous();
879 ICS.Ambiguous.setFromType(From->getType());
880 ICS.Ambiguous.setToType(ToType);
881 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
882 Cand != Conversions.end(); ++Cand)
883 if (Cand->Viable)
884 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000885 } else {
John McCall65eb8792010-02-25 01:37:24 +0000886 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000887 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000888
889 return ICS;
890}
891
John McCall31168b02011-06-15 23:02:42 +0000892ImplicitConversionSequence
893Sema::TryImplicitConversion(Expr *From, QualType ToType,
894 bool SuppressUserConversions,
895 bool AllowExplicit,
896 bool InOverloadResolution,
897 bool CStyle,
898 bool AllowObjCWritebackConversion) {
899 return clang::TryImplicitConversion(*this, From, ToType,
900 SuppressUserConversions, AllowExplicit,
901 InOverloadResolution, CStyle,
902 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +0000903}
904
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000905/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +0000906/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000907/// converted expression. Flavor is the kind of conversion we're
908/// performing, used in the error message. If @p AllowExplicit,
909/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +0000910ExprResult
911Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000912 AssignmentAction Action, bool AllowExplicit,
913 bool Diagnose) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000914 ImplicitConversionSequence ICS;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000915 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS,
916 Diagnose);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000917}
918
John Wiegley01296292011-04-08 18:41:53 +0000919ExprResult
920Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000921 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000922 ImplicitConversionSequence& ICS,
923 bool Diagnose) {
John McCall31168b02011-06-15 23:02:42 +0000924 // Objective-C ARC: Determine whether we will allow the writeback conversion.
925 bool AllowObjCWritebackConversion
926 = getLangOptions().ObjCAutoRefCount &&
927 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +0000928
John McCall5c32be02010-08-24 20:38:10 +0000929 ICS = clang::TryImplicitConversion(*this, From, ToType,
930 /*SuppressUserConversions=*/false,
931 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000932 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +0000933 /*CStyle=*/false,
934 AllowObjCWritebackConversion);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000935 if (!Diagnose && ICS.isFailure())
936 return ExprError();
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000937 return PerformImplicitConversion(From, ToType, ICS, Action);
938}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000939
940/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000941/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +0000942bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
943 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000944 if (Context.hasSameUnqualifiedType(FromType, ToType))
945 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000946
John McCall991eb4b2010-12-21 00:44:39 +0000947 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
948 // where F adds one of the following at most once:
949 // - a pointer
950 // - a member pointer
951 // - a block pointer
952 CanQualType CanTo = Context.getCanonicalType(ToType);
953 CanQualType CanFrom = Context.getCanonicalType(FromType);
954 Type::TypeClass TyClass = CanTo->getTypeClass();
955 if (TyClass != CanFrom->getTypeClass()) return false;
956 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
957 if (TyClass == Type::Pointer) {
958 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
959 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
960 } else if (TyClass == Type::BlockPointer) {
961 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
962 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
963 } else if (TyClass == Type::MemberPointer) {
964 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
965 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
966 } else {
967 return false;
968 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000969
John McCall991eb4b2010-12-21 00:44:39 +0000970 TyClass = CanTo->getTypeClass();
971 if (TyClass != CanFrom->getTypeClass()) return false;
972 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
973 return false;
974 }
975
976 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
977 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
978 if (!EInfo.getNoReturn()) return false;
979
980 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
981 assert(QualType(FromFn, 0).isCanonical());
982 if (QualType(FromFn, 0) != CanTo) return false;
983
984 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000985 return true;
986}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000987
Douglas Gregor46188682010-05-18 22:42:18 +0000988/// \brief Determine whether the conversion from FromType to ToType is a valid
989/// vector conversion.
990///
991/// \param ICK Will be set to the vector conversion kind, if this is a vector
992/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000993static bool IsVectorConversion(ASTContext &Context, QualType FromType,
994 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +0000995 // We need at least one of these types to be a vector type to have a vector
996 // conversion.
997 if (!ToType->isVectorType() && !FromType->isVectorType())
998 return false;
999
1000 // Identical types require no conversions.
1001 if (Context.hasSameUnqualifiedType(FromType, ToType))
1002 return false;
1003
1004 // There are no conversions between extended vector types, only identity.
1005 if (ToType->isExtVectorType()) {
1006 // There are no conversions between extended vector types other than the
1007 // identity conversion.
1008 if (FromType->isExtVectorType())
1009 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001010
Douglas Gregor46188682010-05-18 22:42:18 +00001011 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001012 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001013 ICK = ICK_Vector_Splat;
1014 return true;
1015 }
1016 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001017
1018 // We can perform the conversion between vector types in the following cases:
1019 // 1)vector types are equivalent AltiVec and GCC vector types
1020 // 2)lax vector conversions are permitted and the vector types are of the
1021 // same size
1022 if (ToType->isVectorType() && FromType->isVectorType()) {
1023 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001024 (Context.getLangOptions().LaxVectorConversions &&
1025 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001026 ICK = ICK_Vector_Conversion;
1027 return true;
1028 }
Douglas Gregor46188682010-05-18 22:42:18 +00001029 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001030
Douglas Gregor46188682010-05-18 22:42:18 +00001031 return false;
1032}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001033
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001034/// IsStandardConversion - Determines whether there is a standard
1035/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1036/// expression From to the type ToType. Standard conversion sequences
1037/// only consider non-class types; for conversions that involve class
1038/// types, use TryImplicitConversion. If a conversion exists, SCS will
1039/// contain the standard conversion sequence required to perform this
1040/// conversion and this routine will return true. Otherwise, this
1041/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001042static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1043 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001044 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001045 bool CStyle,
1046 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001047 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001048
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001049 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001050 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001051 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001052 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001053 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001054 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001055
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001056 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001057 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001058 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001059 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001060 return false;
1061
Mike Stump11289f42009-09-09 15:08:12 +00001062 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001063 }
1064
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001065 // The first conversion can be an lvalue-to-rvalue conversion,
1066 // array-to-pointer conversion, or function-to-pointer conversion
1067 // (C++ 4p1).
1068
John McCall5c32be02010-08-24 20:38:10 +00001069 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001070 DeclAccessPair AccessPair;
1071 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001072 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001073 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001074 // We were able to resolve the address of the overloaded function,
1075 // so we can convert to the type of that function.
1076 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001077
1078 // we can sometimes resolve &foo<int> regardless of ToType, so check
1079 // if the type matches (identity) or we are converting to bool
1080 if (!S.Context.hasSameUnqualifiedType(
1081 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1082 QualType resultTy;
1083 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001084 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001085 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1086 // otherwise, only a boolean conversion is standard
1087 if (!ToType->isBooleanType())
1088 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001089 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001090
Chandler Carruthffce2452011-03-29 08:08:18 +00001091 // Check if the "from" expression is taking the address of an overloaded
1092 // function and recompute the FromType accordingly. Take advantage of the
1093 // fact that non-static member functions *must* have such an address-of
1094 // expression.
1095 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1096 if (Method && !Method->isStatic()) {
1097 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1098 "Non-unary operator on non-static member address");
1099 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1100 == UO_AddrOf &&
1101 "Non-address-of operator on non-static member address");
1102 const Type *ClassType
1103 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1104 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001105 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1106 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1107 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001108 "Non-address-of operator for overloaded function expression");
1109 FromType = S.Context.getPointerType(FromType);
1110 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001111
Douglas Gregor980fb162010-04-29 18:24:40 +00001112 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001113 assert(S.Context.hasSameType(
1114 FromType,
1115 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001116 } else {
1117 return false;
1118 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001119 }
John McCall154a2fd2011-08-30 00:57:29 +00001120 // Lvalue-to-rvalue conversion (C++11 4.1):
1121 // A glvalue (3.10) of a non-function, non-array type T can
1122 // be converted to a prvalue.
1123 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001124 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001125 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001126 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001127 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001128
1129 // If T is a non-class type, the type of the rvalue is the
1130 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001131 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1132 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001133 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001134 } else if (FromType->isArrayType()) {
1135 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001136 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001137
1138 // An lvalue or rvalue of type "array of N T" or "array of unknown
1139 // bound of T" can be converted to an rvalue of type "pointer to
1140 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001141 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001142
John McCall5c32be02010-08-24 20:38:10 +00001143 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001144 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001145 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001146
1147 // For the purpose of ranking in overload resolution
1148 // (13.3.3.1.1), this conversion is considered an
1149 // array-to-pointer conversion followed by a qualification
1150 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001151 SCS.Second = ICK_Identity;
1152 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001153 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001154 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001155 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001156 }
John McCall086a4642010-11-24 05:12:34 +00001157 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001158 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001159 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001160
1161 // An lvalue of function type T can be converted to an rvalue of
1162 // type "pointer to T." The result is a pointer to the
1163 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001164 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001165 } else {
1166 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001167 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001168 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001169 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001170
1171 // The second conversion can be an integral promotion, floating
1172 // point promotion, integral conversion, floating point conversion,
1173 // floating-integral conversion, pointer conversion,
1174 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001175 // For overloading in C, this can also be a "compatible-type"
1176 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001177 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001178 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001179 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001180 // The unqualified versions of the types are the same: there's no
1181 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001182 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001183 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001184 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001185 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001186 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001187 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001188 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001189 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001190 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001191 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001192 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001193 SCS.Second = ICK_Complex_Promotion;
1194 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001195 } else if (ToType->isBooleanType() &&
1196 (FromType->isArithmeticType() ||
1197 FromType->isAnyPointerType() ||
1198 FromType->isBlockPointerType() ||
1199 FromType->isMemberPointerType() ||
1200 FromType->isNullPtrType())) {
1201 // Boolean conversions (C++ 4.12).
1202 SCS.Second = ICK_Boolean_Conversion;
1203 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001204 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001205 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001206 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001207 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001208 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001209 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001210 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001211 SCS.Second = ICK_Complex_Conversion;
1212 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001213 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1214 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001215 // Complex-real conversions (C99 6.3.1.7)
1216 SCS.Second = ICK_Complex_Real;
1217 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001218 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001219 // Floating point conversions (C++ 4.8).
1220 SCS.Second = ICK_Floating_Conversion;
1221 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001222 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001223 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001224 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001225 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001226 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001227 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001228 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001229 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001230 SCS.Second = ICK_Block_Pointer_Conversion;
1231 } else if (AllowObjCWritebackConversion &&
1232 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1233 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001234 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1235 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001236 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001237 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001238 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001239 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001240 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001241 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001242 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001243 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001244 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001245 SCS.Second = SecondICK;
1246 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001247 } else if (!S.getLangOptions().CPlusPlus &&
1248 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001249 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001250 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001251 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001252 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001253 // Treat a conversion that strips "noreturn" as an identity conversion.
1254 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001255 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1256 InOverloadResolution,
1257 SCS, CStyle)) {
1258 SCS.Second = ICK_TransparentUnionConversion;
1259 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001260 } else {
1261 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001262 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001263 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001264 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001265
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001266 QualType CanonFrom;
1267 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001268 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001269 bool ObjCLifetimeConversion;
1270 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1271 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001272 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001273 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001274 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001275 CanonFrom = S.Context.getCanonicalType(FromType);
1276 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001277 } else {
1278 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001279 SCS.Third = ICK_Identity;
1280
Mike Stump11289f42009-09-09 15:08:12 +00001281 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001282 // [...] Any difference in top-level cv-qualification is
1283 // subsumed by the initialization itself and does not constitute
1284 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001285 CanonFrom = S.Context.getCanonicalType(FromType);
1286 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001287 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001288 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001289 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001290 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1291 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001292 FromType = ToType;
1293 CanonFrom = CanonTo;
1294 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001295 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001296 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001297
1298 // If we have not converted the argument type to the parameter type,
1299 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001300 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001301 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001302
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001303 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001304}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001305
1306static bool
1307IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1308 QualType &ToType,
1309 bool InOverloadResolution,
1310 StandardConversionSequence &SCS,
1311 bool CStyle) {
1312
1313 const RecordType *UT = ToType->getAsUnionType();
1314 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1315 return false;
1316 // The field to initialize within the transparent union.
1317 RecordDecl *UD = UT->getDecl();
1318 // It's compatible if the expression matches any of the fields.
1319 for (RecordDecl::field_iterator it = UD->field_begin(),
1320 itend = UD->field_end();
1321 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001322 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1323 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001324 ToType = it->getType();
1325 return true;
1326 }
1327 }
1328 return false;
1329}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001330
1331/// IsIntegralPromotion - Determines whether the conversion from the
1332/// expression From (whose potentially-adjusted type is FromType) to
1333/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1334/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001335bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001336 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001337 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001338 if (!To) {
1339 return false;
1340 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001341
1342 // An rvalue of type char, signed char, unsigned char, short int, or
1343 // unsigned short int can be converted to an rvalue of type int if
1344 // int can represent all the values of the source type; otherwise,
1345 // the source rvalue can be converted to an rvalue of type unsigned
1346 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001347 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1348 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001349 if (// We can promote any signed, promotable integer type to an int
1350 (FromType->isSignedIntegerType() ||
1351 // We can promote any unsigned integer type whose size is
1352 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001353 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001354 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001355 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001356 }
1357
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001358 return To->getKind() == BuiltinType::UInt;
1359 }
1360
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001361 // C++0x [conv.prom]p3:
1362 // A prvalue of an unscoped enumeration type whose underlying type is not
1363 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1364 // following types that can represent all the values of the enumeration
1365 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1366 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001367 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001368 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001369 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001370 // with lowest integer conversion rank (4.13) greater than the rank of long
1371 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001372 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001373 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1374 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1375 // provided for a scoped enumeration.
1376 if (FromEnumType->getDecl()->isScoped())
1377 return false;
1378
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001379 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001380 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001381 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001382 return Context.hasSameUnqualifiedType(ToType,
1383 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001384 }
John McCall56774992009-12-09 09:09:27 +00001385
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001386 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1388 // to an rvalue a prvalue of the first of the following types that can
1389 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001390 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001391 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001392 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001393 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001394 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001395 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001396 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001397 // Determine whether the type we're converting from is signed or
1398 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001399 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001400 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001401
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001402 // The types we'll try to promote to, in the appropriate
1403 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001404 QualType PromoteTypes[6] = {
1405 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001406 Context.LongTy, Context.UnsignedLongTy ,
1407 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001408 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001409 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001410 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1411 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001412 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001413 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1414 // We found the type that we can promote to. If this is the
1415 // type we wanted, we have a promotion. Otherwise, no
1416 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001417 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001418 }
1419 }
1420 }
1421
1422 // An rvalue for an integral bit-field (9.6) can be converted to an
1423 // rvalue of type int if int can represent all the values of the
1424 // bit-field; otherwise, it can be converted to unsigned int if
1425 // unsigned int can represent all the values of the bit-field. If
1426 // the bit-field is larger yet, no integral promotion applies to
1427 // it. If the bit-field has an enumerated type, it is treated as any
1428 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001429 // FIXME: We should delay checking of bit-fields until we actually perform the
1430 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001431 using llvm::APSInt;
1432 if (From)
1433 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001434 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001435 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001436 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1437 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1438 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001439
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001440 // Are we promoting to an int from a bitfield that fits in an int?
1441 if (BitWidth < ToSize ||
1442 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1443 return To->getKind() == BuiltinType::Int;
1444 }
Mike Stump11289f42009-09-09 15:08:12 +00001445
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001446 // Are we promoting to an unsigned int from an unsigned bitfield
1447 // that fits into an unsigned int?
1448 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1449 return To->getKind() == BuiltinType::UInt;
1450 }
Mike Stump11289f42009-09-09 15:08:12 +00001451
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001452 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001453 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001454 }
Mike Stump11289f42009-09-09 15:08:12 +00001455
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001456 // An rvalue of type bool can be converted to an rvalue of type int,
1457 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001458 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001459 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001460 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001461
1462 return false;
1463}
1464
1465/// IsFloatingPointPromotion - Determines whether the conversion from
1466/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1467/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001468bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001469 /// An rvalue of type float can be converted to an rvalue of type
1470 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001471 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1472 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001473 if (FromBuiltin->getKind() == BuiltinType::Float &&
1474 ToBuiltin->getKind() == BuiltinType::Double)
1475 return true;
1476
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001477 // C99 6.3.1.5p1:
1478 // When a float is promoted to double or long double, or a
1479 // double is promoted to long double [...].
1480 if (!getLangOptions().CPlusPlus &&
1481 (FromBuiltin->getKind() == BuiltinType::Float ||
1482 FromBuiltin->getKind() == BuiltinType::Double) &&
1483 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1484 return true;
1485 }
1486
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001487 return false;
1488}
1489
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001490/// \brief Determine if a conversion is a complex promotion.
1491///
1492/// A complex promotion is defined as a complex -> complex conversion
1493/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001494/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001495bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001496 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001497 if (!FromComplex)
1498 return false;
1499
John McCall9dd450b2009-09-21 23:43:11 +00001500 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001501 if (!ToComplex)
1502 return false;
1503
1504 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001505 ToComplex->getElementType()) ||
1506 IsIntegralPromotion(0, FromComplex->getElementType(),
1507 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001508}
1509
Douglas Gregor237f96c2008-11-26 23:31:11 +00001510/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1511/// the pointer type FromPtr to a pointer to type ToPointee, with the
1512/// same type qualifiers as FromPtr has on its pointee type. ToType,
1513/// if non-empty, will be a pointer to ToType that may or may not have
1514/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001515///
Mike Stump11289f42009-09-09 15:08:12 +00001516static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001517BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001518 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001519 ASTContext &Context,
1520 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001521 assert((FromPtr->getTypeClass() == Type::Pointer ||
1522 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1523 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001524
John McCall31168b02011-06-15 23:02:42 +00001525 /// Conversions to 'id' subsume cv-qualifier conversions.
1526 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001527 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001528
1529 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001530 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001531 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001532 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001533
John McCall31168b02011-06-15 23:02:42 +00001534 if (StripObjCLifetime)
1535 Quals.removeObjCLifetime();
1536
Mike Stump11289f42009-09-09 15:08:12 +00001537 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001538 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001539 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001540 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001541 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001542
1543 // Build a pointer to ToPointee. It has the right qualifiers
1544 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001545 if (isa<ObjCObjectPointerType>(ToType))
1546 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001547 return Context.getPointerType(ToPointee);
1548 }
1549
1550 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001551 QualType QualifiedCanonToPointee
1552 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001553
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001554 if (isa<ObjCObjectPointerType>(ToType))
1555 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1556 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001557}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001558
Mike Stump11289f42009-09-09 15:08:12 +00001559static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001560 bool InOverloadResolution,
1561 ASTContext &Context) {
1562 // Handle value-dependent integral null pointer constants correctly.
1563 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1564 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001565 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001566 return !InOverloadResolution;
1567
Douglas Gregor56751b52009-09-25 04:25:58 +00001568 return Expr->isNullPointerConstant(Context,
1569 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1570 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001571}
Mike Stump11289f42009-09-09 15:08:12 +00001572
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001573/// IsPointerConversion - Determines whether the conversion of the
1574/// expression From, which has the (possibly adjusted) type FromType,
1575/// can be converted to the type ToType via a pointer conversion (C++
1576/// 4.10). If so, returns true and places the converted type (that
1577/// might differ from ToType in its cv-qualifiers at some level) into
1578/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001579///
Douglas Gregora29dc052008-11-27 01:19:21 +00001580/// This routine also supports conversions to and from block pointers
1581/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1582/// pointers to interfaces. FIXME: Once we've determined the
1583/// appropriate overloading rules for Objective-C, we may want to
1584/// split the Objective-C checks into a different routine; however,
1585/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001586/// conversions, so for now they live here. IncompatibleObjC will be
1587/// set if the conversion is an allowed Objective-C conversion that
1588/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001589bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001590 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001591 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001592 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001593 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001594 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1595 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001596 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001597
Mike Stump11289f42009-09-09 15:08:12 +00001598 // Conversion from a null pointer constant to any Objective-C pointer type.
1599 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001600 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001601 ConvertedType = ToType;
1602 return true;
1603 }
1604
Douglas Gregor231d1c62008-11-27 00:15:41 +00001605 // Blocks: Block pointers can be converted to void*.
1606 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001607 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001608 ConvertedType = ToType;
1609 return true;
1610 }
1611 // Blocks: A null pointer constant can be converted to a block
1612 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001613 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001614 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001615 ConvertedType = ToType;
1616 return true;
1617 }
1618
Sebastian Redl576fd422009-05-10 18:38:11 +00001619 // If the left-hand-side is nullptr_t, the right side can be a null
1620 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001621 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001622 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001623 ConvertedType = ToType;
1624 return true;
1625 }
1626
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001627 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001628 if (!ToTypePtr)
1629 return false;
1630
1631 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001632 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001633 ConvertedType = ToType;
1634 return true;
1635 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001636
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001637 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001638 // , including objective-c pointers.
1639 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001640 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1641 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001642 ConvertedType = BuildSimilarlyQualifiedPointerType(
1643 FromType->getAs<ObjCObjectPointerType>(),
1644 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001645 ToType, Context);
1646 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001647 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001648 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001649 if (!FromTypePtr)
1650 return false;
1651
1652 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001653
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001654 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001655 // pointer conversion, so don't do all of the work below.
1656 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1657 return false;
1658
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001659 // An rvalue of type "pointer to cv T," where T is an object type,
1660 // can be converted to an rvalue of type "pointer to cv void" (C++
1661 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001662 if (FromPointeeType->isIncompleteOrObjectType() &&
1663 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001664 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001665 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001666 ToType, Context,
1667 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001668 return true;
1669 }
1670
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001671 // MSVC allows implicit function to void* type conversion.
Francois Pichet0706d202011-09-17 17:15:52 +00001672 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001673 ToPointeeType->isVoidType()) {
1674 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1675 ToPointeeType,
1676 ToType, Context);
1677 return true;
1678 }
1679
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001680 // When we're overloading in C, we allow a special kind of pointer
1681 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001682 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001683 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001684 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001685 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001686 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001687 return true;
1688 }
1689
Douglas Gregor5c407d92008-10-23 00:40:37 +00001690 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001691 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001692 // An rvalue of type "pointer to cv D," where D is a class type,
1693 // can be converted to an rvalue of type "pointer to cv B," where
1694 // B is a base class (clause 10) of D. If B is an inaccessible
1695 // (clause 11) or ambiguous (10.2) base class of D, a program that
1696 // necessitates this conversion is ill-formed. The result of the
1697 // conversion is a pointer to the base class sub-object of the
1698 // derived class object. The null pointer value is converted to
1699 // the null pointer value of the destination type.
1700 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001701 // Note that we do not check for ambiguity or inaccessibility
1702 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001703 if (getLangOptions().CPlusPlus &&
1704 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001705 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001706 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001707 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001708 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001709 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001710 ToType, Context);
1711 return true;
1712 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001713
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001714 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1715 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1716 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1717 ToPointeeType,
1718 ToType, Context);
1719 return true;
1720 }
1721
Douglas Gregora119f102008-12-19 19:13:09 +00001722 return false;
1723}
Douglas Gregoraec25842011-04-26 23:16:46 +00001724
1725/// \brief Adopt the given qualifiers for the given type.
1726static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1727 Qualifiers TQs = T.getQualifiers();
1728
1729 // Check whether qualifiers already match.
1730 if (TQs == Qs)
1731 return T;
1732
1733 if (Qs.compatiblyIncludes(TQs))
1734 return Context.getQualifiedType(T, Qs);
1735
1736 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1737}
Douglas Gregora119f102008-12-19 19:13:09 +00001738
1739/// isObjCPointerConversion - Determines whether this is an
1740/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1741/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001742bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001743 QualType& ConvertedType,
1744 bool &IncompatibleObjC) {
1745 if (!getLangOptions().ObjC1)
1746 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001747
Douglas Gregoraec25842011-04-26 23:16:46 +00001748 // The set of qualifiers on the type we're converting from.
1749 Qualifiers FromQualifiers = FromType.getQualifiers();
1750
Steve Naroff7cae42b2009-07-10 23:34:53 +00001751 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001752 const ObjCObjectPointerType* ToObjCPtr =
1753 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001754 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001755 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001756
Steve Naroff7cae42b2009-07-10 23:34:53 +00001757 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001758 // If the pointee types are the same (ignoring qualifications),
1759 // then this is not a pointer conversion.
1760 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1761 FromObjCPtr->getPointeeType()))
1762 return false;
1763
Douglas Gregoraec25842011-04-26 23:16:46 +00001764 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00001765 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001766 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001767 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001768 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001769 return true;
1770 }
1771 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001772 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001773 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001774 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001775 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001776 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001777 return true;
1778 }
1779 // Objective C++: We're able to convert from a pointer to an
1780 // interface to a pointer to a different interface.
1781 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001782 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1783 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1784 if (getLangOptions().CPlusPlus && LHS && RHS &&
1785 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1786 FromObjCPtr->getPointeeType()))
1787 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001788 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001789 ToObjCPtr->getPointeeType(),
1790 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001791 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001792 return true;
1793 }
1794
1795 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1796 // Okay: this is some kind of implicit downcast of Objective-C
1797 // interfaces, which is permitted. However, we're going to
1798 // complain about it.
1799 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001800 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001801 ToObjCPtr->getPointeeType(),
1802 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001803 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001804 return true;
1805 }
Mike Stump11289f42009-09-09 15:08:12 +00001806 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001807 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001808 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001809 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001810 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001811 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001812 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001813 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001814 // to a block pointer type.
1815 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001816 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001817 return true;
1818 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001819 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001821 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001822 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001823 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001824 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00001825 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001826 return true;
1827 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001828 else
Douglas Gregora119f102008-12-19 19:13:09 +00001829 return false;
1830
Douglas Gregor033f56d2008-12-23 00:53:59 +00001831 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001832 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001833 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001834 else if (const BlockPointerType *FromBlockPtr =
1835 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001836 FromPointeeType = FromBlockPtr->getPointeeType();
1837 else
Douglas Gregora119f102008-12-19 19:13:09 +00001838 return false;
1839
Douglas Gregora119f102008-12-19 19:13:09 +00001840 // If we have pointers to pointers, recursively check whether this
1841 // is an Objective-C conversion.
1842 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1843 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1844 IncompatibleObjC)) {
1845 // We always complain about this conversion.
1846 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001847 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001848 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001849 return true;
1850 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001851 // Allow conversion of pointee being objective-c pointer to another one;
1852 // as in I* to id.
1853 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1854 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1855 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1856 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00001857
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001858 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001859 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001860 return true;
1861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862
Douglas Gregor033f56d2008-12-23 00:53:59 +00001863 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001864 // differences in the argument and result types are in Objective-C
1865 // pointer conversions. If so, we permit the conversion (but
1866 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001867 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001868 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001869 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001870 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001871 if (FromFunctionType && ToFunctionType) {
1872 // If the function types are exactly the same, this isn't an
1873 // Objective-C pointer conversion.
1874 if (Context.getCanonicalType(FromPointeeType)
1875 == Context.getCanonicalType(ToPointeeType))
1876 return false;
1877
1878 // Perform the quick checks that will tell us whether these
1879 // function types are obviously different.
1880 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1881 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1882 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1883 return false;
1884
1885 bool HasObjCConversion = false;
1886 if (Context.getCanonicalType(FromFunctionType->getResultType())
1887 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1888 // Okay, the types match exactly. Nothing to do.
1889 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1890 ToFunctionType->getResultType(),
1891 ConvertedType, IncompatibleObjC)) {
1892 // Okay, we have an Objective-C pointer conversion.
1893 HasObjCConversion = true;
1894 } else {
1895 // Function types are too different. Abort.
1896 return false;
1897 }
Mike Stump11289f42009-09-09 15:08:12 +00001898
Douglas Gregora119f102008-12-19 19:13:09 +00001899 // Check argument types.
1900 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1901 ArgIdx != NumArgs; ++ArgIdx) {
1902 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1903 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1904 if (Context.getCanonicalType(FromArgType)
1905 == Context.getCanonicalType(ToArgType)) {
1906 // Okay, the types match exactly. Nothing to do.
1907 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1908 ConvertedType, IncompatibleObjC)) {
1909 // Okay, we have an Objective-C pointer conversion.
1910 HasObjCConversion = true;
1911 } else {
1912 // Argument types are too different. Abort.
1913 return false;
1914 }
1915 }
1916
1917 if (HasObjCConversion) {
1918 // We had an Objective-C conversion. Allow this pointer
1919 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00001920 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001921 IncompatibleObjC = true;
1922 return true;
1923 }
1924 }
1925
Sebastian Redl72b597d2009-01-25 19:43:20 +00001926 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001927}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001928
John McCall31168b02011-06-15 23:02:42 +00001929/// \brief Determine whether this is an Objective-C writeback conversion,
1930/// used for parameter passing when performing automatic reference counting.
1931///
1932/// \param FromType The type we're converting form.
1933///
1934/// \param ToType The type we're converting to.
1935///
1936/// \param ConvertedType The type that will be produced after applying
1937/// this conversion.
1938bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
1939 QualType &ConvertedType) {
1940 if (!getLangOptions().ObjCAutoRefCount ||
1941 Context.hasSameUnqualifiedType(FromType, ToType))
1942 return false;
1943
1944 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
1945 QualType ToPointee;
1946 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
1947 ToPointee = ToPointer->getPointeeType();
1948 else
1949 return false;
1950
1951 Qualifiers ToQuals = ToPointee.getQualifiers();
1952 if (!ToPointee->isObjCLifetimeType() ||
1953 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
1954 !ToQuals.withoutObjCGLifetime().empty())
1955 return false;
1956
1957 // Argument must be a pointer to __strong to __weak.
1958 QualType FromPointee;
1959 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
1960 FromPointee = FromPointer->getPointeeType();
1961 else
1962 return false;
1963
1964 Qualifiers FromQuals = FromPointee.getQualifiers();
1965 if (!FromPointee->isObjCLifetimeType() ||
1966 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
1967 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
1968 return false;
1969
1970 // Make sure that we have compatible qualifiers.
1971 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
1972 if (!ToQuals.compatiblyIncludes(FromQuals))
1973 return false;
1974
1975 // Remove qualifiers from the pointee type we're converting from; they
1976 // aren't used in the compatibility check belong, and we'll be adding back
1977 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
1978 FromPointee = FromPointee.getUnqualifiedType();
1979
1980 // The unqualified form of the pointee types must be compatible.
1981 ToPointee = ToPointee.getUnqualifiedType();
1982 bool IncompatibleObjC;
1983 if (Context.typesAreCompatible(FromPointee, ToPointee))
1984 FromPointee = ToPointee;
1985 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
1986 IncompatibleObjC))
1987 return false;
1988
1989 /// \brief Construct the type we're converting to, which is a pointer to
1990 /// __autoreleasing pointee.
1991 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
1992 ConvertedType = Context.getPointerType(FromPointee);
1993 return true;
1994}
1995
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001996bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1997 QualType& ConvertedType) {
1998 QualType ToPointeeType;
1999 if (const BlockPointerType *ToBlockPtr =
2000 ToType->getAs<BlockPointerType>())
2001 ToPointeeType = ToBlockPtr->getPointeeType();
2002 else
2003 return false;
2004
2005 QualType FromPointeeType;
2006 if (const BlockPointerType *FromBlockPtr =
2007 FromType->getAs<BlockPointerType>())
2008 FromPointeeType = FromBlockPtr->getPointeeType();
2009 else
2010 return false;
2011 // We have pointer to blocks, check whether the only
2012 // differences in the argument and result types are in Objective-C
2013 // pointer conversions. If so, we permit the conversion.
2014
2015 const FunctionProtoType *FromFunctionType
2016 = FromPointeeType->getAs<FunctionProtoType>();
2017 const FunctionProtoType *ToFunctionType
2018 = ToPointeeType->getAs<FunctionProtoType>();
2019
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002020 if (!FromFunctionType || !ToFunctionType)
2021 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002022
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002023 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002024 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002025
2026 // Perform the quick checks that will tell us whether these
2027 // function types are obviously different.
2028 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2029 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2030 return false;
2031
2032 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2033 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2034 if (FromEInfo != ToEInfo)
2035 return false;
2036
2037 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002038 if (Context.hasSameType(FromFunctionType->getResultType(),
2039 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002040 // Okay, the types match exactly. Nothing to do.
2041 } else {
2042 QualType RHS = FromFunctionType->getResultType();
2043 QualType LHS = ToFunctionType->getResultType();
2044 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2045 !RHS.hasQualifiers() && LHS.hasQualifiers())
2046 LHS = LHS.getUnqualifiedType();
2047
2048 if (Context.hasSameType(RHS,LHS)) {
2049 // OK exact match.
2050 } else if (isObjCPointerConversion(RHS, LHS,
2051 ConvertedType, IncompatibleObjC)) {
2052 if (IncompatibleObjC)
2053 return false;
2054 // Okay, we have an Objective-C pointer conversion.
2055 }
2056 else
2057 return false;
2058 }
2059
2060 // Check argument types.
2061 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2062 ArgIdx != NumArgs; ++ArgIdx) {
2063 IncompatibleObjC = false;
2064 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2065 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2066 if (Context.hasSameType(FromArgType, ToArgType)) {
2067 // Okay, the types match exactly. Nothing to do.
2068 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2069 ConvertedType, IncompatibleObjC)) {
2070 if (IncompatibleObjC)
2071 return false;
2072 // Okay, we have an Objective-C pointer conversion.
2073 } else
2074 // Argument types are too different. Abort.
2075 return false;
2076 }
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002077 if (LangOpts.ObjCAutoRefCount) {
2078 if (FromFunctionType->hasAnyConsumedArgs() !=
2079 ToFunctionType->hasAnyConsumedArgs())
2080 return false;
2081 FunctionProtoType::ExtProtoInfo FromEPI =
2082 FromFunctionType->getExtProtoInfo();
2083 FunctionProtoType::ExtProtoInfo ToEPI =
2084 ToFunctionType->getExtProtoInfo();
2085 if (FromEPI.ConsumedArguments && ToEPI.ConsumedArguments)
2086 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2087 ArgIdx != NumArgs; ++ArgIdx) {
2088 if (FromEPI.ConsumedArguments[ArgIdx] !=
2089 ToEPI.ConsumedArguments[ArgIdx])
2090 return false;
2091 }
2092 }
2093
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002094 ConvertedType = ToType;
2095 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002096}
2097
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002098/// FunctionArgTypesAreEqual - This routine checks two function proto types
2099/// for equlity of their argument types. Caller has already checked that
2100/// they have same number of arguments. This routine assumes that Objective-C
2101/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002102bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00002103 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002104 if (!getLangOptions().ObjC1)
2105 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2106 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002107
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002108 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2109 N = NewType->arg_type_begin(),
2110 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2111 QualType ToType = (*O);
2112 QualType FromType = (*N);
2113 if (ToType != FromType) {
2114 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2115 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002116 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2117 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2118 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2119 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002120 continue;
2121 }
John McCall8b07ec22010-05-15 11:32:37 +00002122 else if (const ObjCObjectPointerType *PTTo =
2123 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002124 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002125 FromType->getAs<ObjCObjectPointerType>())
2126 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2127 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002128 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002129 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002130 }
2131 }
2132 return true;
2133}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002134
Douglas Gregor39c16d42008-10-24 04:54:22 +00002135/// CheckPointerConversion - Check the pointer conversion from the
2136/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002137/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002138/// conversions for which IsPointerConversion has already returned
2139/// true. It returns true and produces a diagnostic if there was an
2140/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002141bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002142 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002143 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002144 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002145 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002146 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002147
John McCall8cb679e2010-11-15 09:13:47 +00002148 Kind = CK_BitCast;
2149
Chandler Carruthffab8732011-04-09 07:32:05 +00002150 if (!IsCStyleOrFunctionalCast &&
2151 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2152 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2153 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002154 PDiag(diag::warn_impcast_bool_to_null_pointer)
2155 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002156
John McCall9320b872011-09-09 05:25:32 +00002157 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2158 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002159 QualType FromPointeeType = FromPtrType->getPointeeType(),
2160 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002161
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002162 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2163 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002164 // We must have a derived-to-base conversion. Check an
2165 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002166 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2167 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002168 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002169 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002170 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002171
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002172 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002173 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002174 }
2175 }
John McCall9320b872011-09-09 05:25:32 +00002176 } else if (const ObjCObjectPointerType *ToPtrType =
2177 ToType->getAs<ObjCObjectPointerType>()) {
2178 if (const ObjCObjectPointerType *FromPtrType =
2179 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002180 // Objective-C++ conversions are always okay.
2181 // FIXME: We should have a different class of conversions for the
2182 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002183 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002184 return false;
John McCall9320b872011-09-09 05:25:32 +00002185 } else if (FromType->isBlockPointerType()) {
2186 Kind = CK_BlockPointerToObjCPointerCast;
2187 } else {
2188 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002189 }
John McCall9320b872011-09-09 05:25:32 +00002190 } else if (ToType->isBlockPointerType()) {
2191 if (!FromType->isBlockPointerType())
2192 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002193 }
John McCall8cb679e2010-11-15 09:13:47 +00002194
2195 // We shouldn't fall into this case unless it's valid for other
2196 // reasons.
2197 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2198 Kind = CK_NullToPointer;
2199
Douglas Gregor39c16d42008-10-24 04:54:22 +00002200 return false;
2201}
2202
Sebastian Redl72b597d2009-01-25 19:43:20 +00002203/// IsMemberPointerConversion - Determines whether the conversion of the
2204/// expression From, which has the (possibly adjusted) type FromType, can be
2205/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2206/// If so, returns true and places the converted type (that might differ from
2207/// ToType in its cv-qualifiers at some level) into ConvertedType.
2208bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002209 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002210 bool InOverloadResolution,
2211 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002212 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002213 if (!ToTypePtr)
2214 return false;
2215
2216 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002217 if (From->isNullPointerConstant(Context,
2218 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2219 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002220 ConvertedType = ToType;
2221 return true;
2222 }
2223
2224 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002225 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002226 if (!FromTypePtr)
2227 return false;
2228
2229 // A pointer to member of B can be converted to a pointer to member of D,
2230 // where D is derived from B (C++ 4.11p2).
2231 QualType FromClass(FromTypePtr->getClass(), 0);
2232 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002233
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002234 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2235 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2236 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002237 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2238 ToClass.getTypePtr());
2239 return true;
2240 }
2241
2242 return false;
2243}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002244
Sebastian Redl72b597d2009-01-25 19:43:20 +00002245/// CheckMemberPointerConversion - Check the member pointer conversion from the
2246/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002247/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002248/// for which IsMemberPointerConversion has already returned true. It returns
2249/// true and produces a diagnostic if there was an error, or returns false
2250/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002251bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002252 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002253 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002254 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002255 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002256 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002257 if (!FromPtrType) {
2258 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002259 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002260 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002261 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002262 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002263 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002264 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002265
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002266 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002267 assert(ToPtrType && "No member pointer cast has a target type "
2268 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002269
Sebastian Redled8f2002009-01-28 18:33:18 +00002270 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2271 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002272
Sebastian Redled8f2002009-01-28 18:33:18 +00002273 // FIXME: What about dependent types?
2274 assert(FromClass->isRecordType() && "Pointer into non-class.");
2275 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002276
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002277 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002278 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002279 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2280 assert(DerivationOkay &&
2281 "Should not have been called if derivation isn't OK.");
2282 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002283
Sebastian Redled8f2002009-01-28 18:33:18 +00002284 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2285 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002286 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2287 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2288 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2289 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002290 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002291
Douglas Gregor89ee6822009-02-28 01:32:25 +00002292 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002293 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2294 << FromClass << ToClass << QualType(VBase, 0)
2295 << From->getSourceRange();
2296 return true;
2297 }
2298
John McCall5b0829a2010-02-10 09:31:12 +00002299 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002300 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2301 Paths.front(),
2302 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002303
Anders Carlssond7923c62009-08-22 23:33:40 +00002304 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002305 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002306 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002307 return false;
2308}
2309
Douglas Gregor9a657932008-10-21 23:43:52 +00002310/// IsQualificationConversion - Determines whether the conversion from
2311/// an rvalue of type FromType to ToType is a qualification conversion
2312/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002313///
2314/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2315/// when the qualification conversion involves a change in the Objective-C
2316/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002317bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002318Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002319 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002320 FromType = Context.getCanonicalType(FromType);
2321 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002322 ObjCLifetimeConversion = false;
2323
Douglas Gregor9a657932008-10-21 23:43:52 +00002324 // If FromType and ToType are the same type, this is not a
2325 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002326 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002327 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002328
Douglas Gregor9a657932008-10-21 23:43:52 +00002329 // (C++ 4.4p4):
2330 // A conversion can add cv-qualifiers at levels other than the first
2331 // in multi-level pointers, subject to the following rules: [...]
2332 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002333 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002334 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002335 // Within each iteration of the loop, we check the qualifiers to
2336 // determine if this still looks like a qualification
2337 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002338 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002339 // until there are no more pointers or pointers-to-members left to
2340 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002341 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002342
Douglas Gregor90609aa2011-04-25 18:40:17 +00002343 Qualifiers FromQuals = FromType.getQualifiers();
2344 Qualifiers ToQuals = ToType.getQualifiers();
2345
John McCall31168b02011-06-15 23:02:42 +00002346 // Objective-C ARC:
2347 // Check Objective-C lifetime conversions.
2348 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2349 UnwrappedAnyPointer) {
2350 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2351 ObjCLifetimeConversion = true;
2352 FromQuals.removeObjCLifetime();
2353 ToQuals.removeObjCLifetime();
2354 } else {
2355 // Qualification conversions cannot cast between different
2356 // Objective-C lifetime qualifiers.
2357 return false;
2358 }
2359 }
2360
Douglas Gregorf30053d2011-05-08 06:09:53 +00002361 // Allow addition/removal of GC attributes but not changing GC attributes.
2362 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2363 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2364 FromQuals.removeObjCGCAttr();
2365 ToQuals.removeObjCGCAttr();
2366 }
2367
Douglas Gregor9a657932008-10-21 23:43:52 +00002368 // -- for every j > 0, if const is in cv 1,j then const is in cv
2369 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002370 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002371 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002372
Douglas Gregor9a657932008-10-21 23:43:52 +00002373 // -- if the cv 1,j and cv 2,j are different, then const is in
2374 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002375 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002376 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002377 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002378
Douglas Gregor9a657932008-10-21 23:43:52 +00002379 // Keep track of whether all prior cv-qualifiers in the "to" type
2380 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002381 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002382 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002383 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002384
2385 // We are left with FromType and ToType being the pointee types
2386 // after unwrapping the original FromType and ToType the same number
2387 // of types. If we unwrapped any pointers, and if FromType and
2388 // ToType have the same unqualified type (since we checked
2389 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002390 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002391}
2392
Douglas Gregor576e98c2009-01-30 23:27:23 +00002393/// Determines whether there is a user-defined conversion sequence
2394/// (C++ [over.ics.user]) that converts expression From to the type
2395/// ToType. If such a conversion exists, User will contain the
2396/// user-defined conversion sequence that performs such a conversion
2397/// and this routine will return true. Otherwise, this routine returns
2398/// false and User is unspecified.
2399///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002400/// \param AllowExplicit true if the conversion should consider C++0x
2401/// "explicit" conversion functions as well as non-explicit conversion
2402/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002403static OverloadingResult
2404IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2405 UserDefinedConversionSequence& User,
2406 OverloadCandidateSet& CandidateSet,
2407 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002408 // Whether we will only visit constructors.
2409 bool ConstructorsOnly = false;
2410
2411 // If the type we are conversion to is a class type, enumerate its
2412 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002413 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002414 // C++ [over.match.ctor]p1:
2415 // When objects of class type are direct-initialized (8.5), or
2416 // copy-initialized from an expression of the same or a
2417 // derived class type (8.5), overload resolution selects the
2418 // constructor. [...] For copy-initialization, the candidate
2419 // functions are all the converting constructors (12.3.1) of
2420 // that class. The argument list is the expression-list within
2421 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002422 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002423 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002424 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002425 ConstructorsOnly = true;
2426
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002427 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2428 // RequireCompleteType may have returned true due to some invalid decl
2429 // during template instantiation, but ToType may be complete enough now
2430 // to try to recover.
2431 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002432 // We're not going to find any constructors.
2433 } else if (CXXRecordDecl *ToRecordDecl
2434 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002435 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002436 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002437 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002438 NamedDecl *D = *Con;
2439 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2440
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002441 // Find the constructor (which may be a template).
2442 CXXConstructorDecl *Constructor = 0;
2443 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002444 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002445 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002446 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002447 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2448 else
John McCalla0296f72010-03-19 07:35:19 +00002449 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002450
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002451 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002452 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002453 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002454 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2455 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002456 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002457 /*SuppressUserConversions=*/
2458 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002459 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002460 // Allow one user-defined conversion when user specifies a
2461 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002462 S.AddOverloadCandidate(Constructor, FoundDecl,
2463 &From, 1, CandidateSet,
2464 /*SuppressUserConversions=*/
2465 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002466 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002467 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002468 }
2469 }
2470
Douglas Gregor5ab11652010-04-17 22:01:05 +00002471 // Enumerate conversion functions, if we're allowed to.
2472 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002473 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2474 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002475 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002476 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002477 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002478 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002479 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2480 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002481 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002482 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002483 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002484 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002485 DeclAccessPair FoundDecl = I.getPair();
2486 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002487 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2488 if (isa<UsingShadowDecl>(D))
2489 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2490
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002491 CXXConversionDecl *Conv;
2492 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002493 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2494 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002495 else
John McCallda4458e2010-03-31 01:36:47 +00002496 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002497
2498 if (AllowExplicit || !Conv->isExplicit()) {
2499 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002500 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2501 ActingContext, From, ToType,
2502 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002503 else
John McCall5c32be02010-08-24 20:38:10 +00002504 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2505 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002506 }
2507 }
2508 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002509 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002510
2511 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002512 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002513 case OR_Success:
2514 // Record the standard conversion we used and the conversion function.
2515 if (CXXConstructorDecl *Constructor
2516 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002517 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2518
John McCall5c32be02010-08-24 20:38:10 +00002519 // C++ [over.ics.user]p1:
2520 // If the user-defined conversion is specified by a
2521 // constructor (12.3.1), the initial standard conversion
2522 // sequence converts the source type to the type required by
2523 // the argument of the constructor.
2524 //
2525 QualType ThisType = Constructor->getThisType(S.Context);
2526 if (Best->Conversions[0].isEllipsis())
2527 User.EllipsisConversion = true;
2528 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002529 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002530 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002531 }
John McCall5c32be02010-08-24 20:38:10 +00002532 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00002533 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002534 User.After.setAsIdentityConversion();
2535 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2536 User.After.setAllToTypes(ToType);
2537 return OR_Success;
2538 } else if (CXXConversionDecl *Conversion
2539 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002540 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2541
John McCall5c32be02010-08-24 20:38:10 +00002542 // C++ [over.ics.user]p1:
2543 //
2544 // [...] If the user-defined conversion is specified by a
2545 // conversion function (12.3.2), the initial standard
2546 // conversion sequence converts the source type to the
2547 // implicit object parameter of the conversion function.
2548 User.Before = Best->Conversions[0].Standard;
2549 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00002550 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002551 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002552
John McCall5c32be02010-08-24 20:38:10 +00002553 // C++ [over.ics.user]p2:
2554 // The second standard conversion sequence converts the
2555 // result of the user-defined conversion to the target type
2556 // for the sequence. Since an implicit conversion sequence
2557 // is an initialization, the special rules for
2558 // initialization by user-defined conversion apply when
2559 // selecting the best user-defined conversion for a
2560 // user-defined conversion sequence (see 13.3.3 and
2561 // 13.3.3.1).
2562 User.After = Best->FinalConversion;
2563 return OR_Success;
2564 } else {
2565 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002566 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002567 }
2568
John McCall5c32be02010-08-24 20:38:10 +00002569 case OR_No_Viable_Function:
2570 return OR_No_Viable_Function;
2571 case OR_Deleted:
2572 // No conversion here! We're done.
2573 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002574
John McCall5c32be02010-08-24 20:38:10 +00002575 case OR_Ambiguous:
2576 return OR_Ambiguous;
2577 }
2578
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002579 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002580}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002581
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002582bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002583Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002584 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002585 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002586 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002587 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002588 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002589 if (OvResult == OR_Ambiguous)
2590 Diag(From->getSourceRange().getBegin(),
2591 diag::err_typecheck_ambiguous_condition)
2592 << From->getType() << ToType << From->getSourceRange();
2593 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2594 Diag(From->getSourceRange().getBegin(),
2595 diag::err_typecheck_nonviable_condition)
2596 << From->getType() << ToType << From->getSourceRange();
2597 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002598 return false;
John McCall5c32be02010-08-24 20:38:10 +00002599 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002600 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002601}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002602
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002603/// CompareImplicitConversionSequences - Compare two implicit
2604/// conversion sequences to determine whether one is better than the
2605/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002606static ImplicitConversionSequence::CompareKind
2607CompareImplicitConversionSequences(Sema &S,
2608 const ImplicitConversionSequence& ICS1,
2609 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002610{
2611 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2612 // conversion sequences (as defined in 13.3.3.1)
2613 // -- a standard conversion sequence (13.3.3.1.1) is a better
2614 // conversion sequence than a user-defined conversion sequence or
2615 // an ellipsis conversion sequence, and
2616 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2617 // conversion sequence than an ellipsis conversion sequence
2618 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002619 //
John McCall0d1da222010-01-12 00:44:57 +00002620 // C++0x [over.best.ics]p10:
2621 // For the purpose of ranking implicit conversion sequences as
2622 // described in 13.3.3.2, the ambiguous conversion sequence is
2623 // treated as a user-defined sequence that is indistinguishable
2624 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002625 if (ICS1.getKindRank() < ICS2.getKindRank())
2626 return ImplicitConversionSequence::Better;
2627 else if (ICS2.getKindRank() < ICS1.getKindRank())
2628 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002629
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002630 // The following checks require both conversion sequences to be of
2631 // the same kind.
2632 if (ICS1.getKind() != ICS2.getKind())
2633 return ImplicitConversionSequence::Indistinguishable;
2634
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002635 // Two implicit conversion sequences of the same form are
2636 // indistinguishable conversion sequences unless one of the
2637 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002638 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002639 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002640 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002641 // User-defined conversion sequence U1 is a better conversion
2642 // sequence than another user-defined conversion sequence U2 if
2643 // they contain the same user-defined conversion function or
2644 // constructor and if the second standard conversion sequence of
2645 // U1 is better than the second standard conversion sequence of
2646 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002647 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002648 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002649 return CompareStandardConversionSequences(S,
2650 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002651 ICS2.UserDefined.After);
2652 }
2653
2654 return ImplicitConversionSequence::Indistinguishable;
2655}
2656
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002657static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2658 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2659 Qualifiers Quals;
2660 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002661 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002662 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002663
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002664 return Context.hasSameUnqualifiedType(T1, T2);
2665}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002666
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002667// Per 13.3.3.2p3, compare the given standard conversion sequences to
2668// determine if one is a proper subset of the other.
2669static ImplicitConversionSequence::CompareKind
2670compareStandardConversionSubsets(ASTContext &Context,
2671 const StandardConversionSequence& SCS1,
2672 const StandardConversionSequence& SCS2) {
2673 ImplicitConversionSequence::CompareKind Result
2674 = ImplicitConversionSequence::Indistinguishable;
2675
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002676 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002677 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00002678 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2679 return ImplicitConversionSequence::Better;
2680 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2681 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002682
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002683 if (SCS1.Second != SCS2.Second) {
2684 if (SCS1.Second == ICK_Identity)
2685 Result = ImplicitConversionSequence::Better;
2686 else if (SCS2.Second == ICK_Identity)
2687 Result = ImplicitConversionSequence::Worse;
2688 else
2689 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002690 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002691 return ImplicitConversionSequence::Indistinguishable;
2692
2693 if (SCS1.Third == SCS2.Third) {
2694 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2695 : ImplicitConversionSequence::Indistinguishable;
2696 }
2697
2698 if (SCS1.Third == ICK_Identity)
2699 return Result == ImplicitConversionSequence::Worse
2700 ? ImplicitConversionSequence::Indistinguishable
2701 : ImplicitConversionSequence::Better;
2702
2703 if (SCS2.Third == ICK_Identity)
2704 return Result == ImplicitConversionSequence::Better
2705 ? ImplicitConversionSequence::Indistinguishable
2706 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002707
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002708 return ImplicitConversionSequence::Indistinguishable;
2709}
2710
Douglas Gregore696ebb2011-01-26 14:52:12 +00002711/// \brief Determine whether one of the given reference bindings is better
2712/// than the other based on what kind of bindings they are.
2713static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2714 const StandardConversionSequence &SCS2) {
2715 // C++0x [over.ics.rank]p3b4:
2716 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2717 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002718 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002719 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002720 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002721 // reference*.
2722 //
2723 // FIXME: Rvalue references. We're going rogue with the above edits,
2724 // because the semantics in the current C++0x working paper (N3225 at the
2725 // time of this writing) break the standard definition of std::forward
2726 // and std::reference_wrapper when dealing with references to functions.
2727 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002728 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2729 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2730 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002731
Douglas Gregore696ebb2011-01-26 14:52:12 +00002732 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2733 SCS2.IsLvalueReference) ||
2734 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2735 !SCS2.IsLvalueReference);
2736}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002737
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002738/// CompareStandardConversionSequences - Compare two standard
2739/// conversion sequences to determine whether one is better than the
2740/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002741static ImplicitConversionSequence::CompareKind
2742CompareStandardConversionSequences(Sema &S,
2743 const StandardConversionSequence& SCS1,
2744 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002745{
2746 // Standard conversion sequence S1 is a better conversion sequence
2747 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2748
2749 // -- S1 is a proper subsequence of S2 (comparing the conversion
2750 // sequences in the canonical form defined by 13.3.3.1.1,
2751 // excluding any Lvalue Transformation; the identity conversion
2752 // sequence is considered to be a subsequence of any
2753 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002754 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002755 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002756 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002757
2758 // -- the rank of S1 is better than the rank of S2 (by the rules
2759 // defined below), or, if not that,
2760 ImplicitConversionRank Rank1 = SCS1.getRank();
2761 ImplicitConversionRank Rank2 = SCS2.getRank();
2762 if (Rank1 < Rank2)
2763 return ImplicitConversionSequence::Better;
2764 else if (Rank2 < Rank1)
2765 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002766
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002767 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2768 // are indistinguishable unless one of the following rules
2769 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002770
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002771 // A conversion that is not a conversion of a pointer, or
2772 // pointer to member, to bool is better than another conversion
2773 // that is such a conversion.
2774 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2775 return SCS2.isPointerConversionToBool()
2776 ? ImplicitConversionSequence::Better
2777 : ImplicitConversionSequence::Worse;
2778
Douglas Gregor5c407d92008-10-23 00:40:37 +00002779 // C++ [over.ics.rank]p4b2:
2780 //
2781 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002782 // conversion of B* to A* is better than conversion of B* to
2783 // void*, and conversion of A* to void* is better than conversion
2784 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002785 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002786 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002787 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002788 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002789 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2790 // Exactly one of the conversion sequences is a conversion to
2791 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002792 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2793 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002794 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2795 // Neither conversion sequence converts to a void pointer; compare
2796 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002797 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002798 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002799 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002800 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2801 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002802 // Both conversion sequences are conversions to void
2803 // pointers. Compare the source types to determine if there's an
2804 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002805 QualType FromType1 = SCS1.getFromType();
2806 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002807
2808 // Adjust the types we're converting from via the array-to-pointer
2809 // conversion, if we need to.
2810 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002811 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002812 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002813 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002814
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002815 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2816 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002817
John McCall5c32be02010-08-24 20:38:10 +00002818 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002819 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002820 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002821 return ImplicitConversionSequence::Worse;
2822
2823 // Objective-C++: If one interface is more specific than the
2824 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002825 const ObjCObjectPointerType* FromObjCPtr1
2826 = FromType1->getAs<ObjCObjectPointerType>();
2827 const ObjCObjectPointerType* FromObjCPtr2
2828 = FromType2->getAs<ObjCObjectPointerType>();
2829 if (FromObjCPtr1 && FromObjCPtr2) {
2830 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2831 FromObjCPtr2);
2832 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2833 FromObjCPtr1);
2834 if (AssignLeft != AssignRight) {
2835 return AssignLeft? ImplicitConversionSequence::Better
2836 : ImplicitConversionSequence::Worse;
2837 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002838 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002839 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002840
2841 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2842 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002843 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002844 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002845 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002846
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002847 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002848 // Check for a better reference binding based on the kind of bindings.
2849 if (isBetterReferenceBindingKind(SCS1, SCS2))
2850 return ImplicitConversionSequence::Better;
2851 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2852 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002853
Sebastian Redlb28b4072009-03-22 23:49:27 +00002854 // C++ [over.ics.rank]p3b4:
2855 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2856 // which the references refer are the same type except for
2857 // top-level cv-qualifiers, and the type to which the reference
2858 // initialized by S2 refers is more cv-qualified than the type
2859 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002860 QualType T1 = SCS1.getToType(2);
2861 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002862 T1 = S.Context.getCanonicalType(T1);
2863 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002864 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002865 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2866 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002867 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00002868 // Objective-C++ ARC: If the references refer to objects with different
2869 // lifetimes, prefer bindings that don't change lifetime.
2870 if (SCS1.ObjCLifetimeConversionBinding !=
2871 SCS2.ObjCLifetimeConversionBinding) {
2872 return SCS1.ObjCLifetimeConversionBinding
2873 ? ImplicitConversionSequence::Worse
2874 : ImplicitConversionSequence::Better;
2875 }
2876
Chandler Carruth8e543b32010-12-12 08:17:55 +00002877 // If the type is an array type, promote the element qualifiers to the
2878 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002879 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002880 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002881 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002882 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002883 if (T2.isMoreQualifiedThan(T1))
2884 return ImplicitConversionSequence::Better;
2885 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00002886 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002887 }
2888 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002889
Francois Pichet08d2fa02011-09-18 21:37:37 +00002890 // In Microsoft mode, prefer an integral conversion to a
2891 // floating-to-integral conversion if the integral conversion
2892 // is between types of the same size.
2893 // For example:
2894 // void f(float);
2895 // void f(int);
2896 // int main {
2897 // long a;
2898 // f(a);
2899 // }
2900 // Here, MSVC will call f(int) instead of generating a compile error
2901 // as clang will do in standard mode.
2902 if (S.getLangOptions().MicrosoftMode &&
2903 SCS1.Second == ICK_Integral_Conversion &&
2904 SCS2.Second == ICK_Floating_Integral &&
2905 S.Context.getTypeSize(SCS1.getFromType()) ==
2906 S.Context.getTypeSize(SCS1.getToType(2)))
2907 return ImplicitConversionSequence::Better;
2908
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002909 return ImplicitConversionSequence::Indistinguishable;
2910}
2911
2912/// CompareQualificationConversions - Compares two standard conversion
2913/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002914/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2915ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002916CompareQualificationConversions(Sema &S,
2917 const StandardConversionSequence& SCS1,
2918 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002919 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002920 // -- S1 and S2 differ only in their qualification conversion and
2921 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2922 // cv-qualification signature of type T1 is a proper subset of
2923 // the cv-qualification signature of type T2, and S1 is not the
2924 // deprecated string literal array-to-pointer conversion (4.2).
2925 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2926 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2927 return ImplicitConversionSequence::Indistinguishable;
2928
2929 // FIXME: the example in the standard doesn't use a qualification
2930 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002931 QualType T1 = SCS1.getToType(2);
2932 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002933 T1 = S.Context.getCanonicalType(T1);
2934 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002935 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002936 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2937 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002938
2939 // If the types are the same, we won't learn anything by unwrapped
2940 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002941 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002942 return ImplicitConversionSequence::Indistinguishable;
2943
Chandler Carruth607f38e2009-12-29 07:16:59 +00002944 // If the type is an array type, promote the element qualifiers to the type
2945 // for comparison.
2946 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002947 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002948 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002949 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002950
Mike Stump11289f42009-09-09 15:08:12 +00002951 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002952 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00002953
2954 // Objective-C++ ARC:
2955 // Prefer qualification conversions not involving a change in lifetime
2956 // to qualification conversions that do not change lifetime.
2957 if (SCS1.QualificationIncludesObjCLifetime !=
2958 SCS2.QualificationIncludesObjCLifetime) {
2959 Result = SCS1.QualificationIncludesObjCLifetime
2960 ? ImplicitConversionSequence::Worse
2961 : ImplicitConversionSequence::Better;
2962 }
2963
John McCall5c32be02010-08-24 20:38:10 +00002964 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002965 // Within each iteration of the loop, we check the qualifiers to
2966 // determine if this still looks like a qualification
2967 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002968 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002969 // until there are no more pointers or pointers-to-members left
2970 // to unwrap. This essentially mimics what
2971 // IsQualificationConversion does, but here we're checking for a
2972 // strict subset of qualifiers.
2973 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2974 // The qualifiers are the same, so this doesn't tell us anything
2975 // about how the sequences rank.
2976 ;
2977 else if (T2.isMoreQualifiedThan(T1)) {
2978 // T1 has fewer qualifiers, so it could be the better sequence.
2979 if (Result == ImplicitConversionSequence::Worse)
2980 // Neither has qualifiers that are a subset of the other's
2981 // qualifiers.
2982 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002983
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002984 Result = ImplicitConversionSequence::Better;
2985 } else if (T1.isMoreQualifiedThan(T2)) {
2986 // T2 has fewer qualifiers, so it could be the better sequence.
2987 if (Result == ImplicitConversionSequence::Better)
2988 // Neither has qualifiers that are a subset of the other's
2989 // qualifiers.
2990 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002991
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002992 Result = ImplicitConversionSequence::Worse;
2993 } else {
2994 // Qualifiers are disjoint.
2995 return ImplicitConversionSequence::Indistinguishable;
2996 }
2997
2998 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002999 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003000 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003001 }
3002
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003003 // Check that the winning standard conversion sequence isn't using
3004 // the deprecated string literal array to pointer conversion.
3005 switch (Result) {
3006 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003007 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003008 Result = ImplicitConversionSequence::Indistinguishable;
3009 break;
3010
3011 case ImplicitConversionSequence::Indistinguishable:
3012 break;
3013
3014 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003015 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003016 Result = ImplicitConversionSequence::Indistinguishable;
3017 break;
3018 }
3019
3020 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003021}
3022
Douglas Gregor5c407d92008-10-23 00:40:37 +00003023/// CompareDerivedToBaseConversions - Compares two standard conversion
3024/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003025/// various kinds of derived-to-base conversions (C++
3026/// [over.ics.rank]p4b3). As part of these checks, we also look at
3027/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003028ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003029CompareDerivedToBaseConversions(Sema &S,
3030 const StandardConversionSequence& SCS1,
3031 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003032 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003033 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003034 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003035 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003036
3037 // Adjust the types we're converting from via the array-to-pointer
3038 // conversion, if we need to.
3039 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003040 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003041 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003042 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003043
3044 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003045 FromType1 = S.Context.getCanonicalType(FromType1);
3046 ToType1 = S.Context.getCanonicalType(ToType1);
3047 FromType2 = S.Context.getCanonicalType(FromType2);
3048 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003049
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003050 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003051 //
3052 // If class B is derived directly or indirectly from class A and
3053 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003054 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003055 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003056 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003057 SCS2.Second == ICK_Pointer_Conversion &&
3058 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3059 FromType1->isPointerType() && FromType2->isPointerType() &&
3060 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003061 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003062 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003063 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003064 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003065 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003066 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003067 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003068 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003069
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003070 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003071 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003072 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003073 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003074 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003075 return ImplicitConversionSequence::Worse;
3076 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003077
3078 // -- conversion of B* to A* is better than conversion of C* to A*,
3079 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003080 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003081 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003082 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003083 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003084 }
3085 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3086 SCS2.Second == ICK_Pointer_Conversion) {
3087 const ObjCObjectPointerType *FromPtr1
3088 = FromType1->getAs<ObjCObjectPointerType>();
3089 const ObjCObjectPointerType *FromPtr2
3090 = FromType2->getAs<ObjCObjectPointerType>();
3091 const ObjCObjectPointerType *ToPtr1
3092 = ToType1->getAs<ObjCObjectPointerType>();
3093 const ObjCObjectPointerType *ToPtr2
3094 = ToType2->getAs<ObjCObjectPointerType>();
3095
3096 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3097 // Apply the same conversion ranking rules for Objective-C pointer types
3098 // that we do for C++ pointers to class types. However, we employ the
3099 // Objective-C pseudo-subtyping relationship used for assignment of
3100 // Objective-C pointer types.
3101 bool FromAssignLeft
3102 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3103 bool FromAssignRight
3104 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3105 bool ToAssignLeft
3106 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3107 bool ToAssignRight
3108 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3109
3110 // A conversion to an a non-id object pointer type or qualified 'id'
3111 // type is better than a conversion to 'id'.
3112 if (ToPtr1->isObjCIdType() &&
3113 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3114 return ImplicitConversionSequence::Worse;
3115 if (ToPtr2->isObjCIdType() &&
3116 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3117 return ImplicitConversionSequence::Better;
3118
3119 // A conversion to a non-id object pointer type is better than a
3120 // conversion to a qualified 'id' type
3121 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3122 return ImplicitConversionSequence::Worse;
3123 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3124 return ImplicitConversionSequence::Better;
3125
3126 // A conversion to an a non-Class object pointer type or qualified 'Class'
3127 // type is better than a conversion to 'Class'.
3128 if (ToPtr1->isObjCClassType() &&
3129 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3130 return ImplicitConversionSequence::Worse;
3131 if (ToPtr2->isObjCClassType() &&
3132 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3133 return ImplicitConversionSequence::Better;
3134
3135 // A conversion to a non-Class object pointer type is better than a
3136 // conversion to a qualified 'Class' type.
3137 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3138 return ImplicitConversionSequence::Worse;
3139 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3140 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003141
Douglas Gregor058d3de2011-01-31 18:51:41 +00003142 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3143 if (S.Context.hasSameType(FromType1, FromType2) &&
3144 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3145 (ToAssignLeft != ToAssignRight))
3146 return ToAssignLeft? ImplicitConversionSequence::Worse
3147 : ImplicitConversionSequence::Better;
3148
3149 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3150 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3151 (FromAssignLeft != FromAssignRight))
3152 return FromAssignLeft? ImplicitConversionSequence::Better
3153 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003154 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003155 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003156
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003157 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003158 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3159 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3160 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003161 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003162 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003163 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003164 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003165 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003166 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003167 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003168 ToType2->getAs<MemberPointerType>();
3169 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3170 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3171 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3172 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3173 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3174 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3175 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3176 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003177 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003178 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003179 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003180 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003181 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003182 return ImplicitConversionSequence::Better;
3183 }
3184 // conversion of B::* to C::* is better than conversion of A::* to C::*
3185 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003186 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003187 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003188 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003189 return ImplicitConversionSequence::Worse;
3190 }
3191 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003192
Douglas Gregor5ab11652010-04-17 22:01:05 +00003193 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003194 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003195 // -- binding of an expression of type C to a reference of type
3196 // B& is better than binding an expression of type C to a
3197 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003198 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3199 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3200 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003201 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003202 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003203 return ImplicitConversionSequence::Worse;
3204 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003205
Douglas Gregor2fe98832008-11-03 19:09:14 +00003206 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003207 // -- binding of an expression of type B to a reference of type
3208 // A& is better than binding an expression of type C to a
3209 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003210 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3211 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3212 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003213 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003214 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003215 return ImplicitConversionSequence::Worse;
3216 }
3217 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003218
Douglas Gregor5c407d92008-10-23 00:40:37 +00003219 return ImplicitConversionSequence::Indistinguishable;
3220}
3221
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003222/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3223/// determine whether they are reference-related,
3224/// reference-compatible, reference-compatible with added
3225/// qualification, or incompatible, for use in C++ initialization by
3226/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3227/// type, and the first type (T1) is the pointee type of the reference
3228/// type being initialized.
3229Sema::ReferenceCompareResult
3230Sema::CompareReferenceRelationship(SourceLocation Loc,
3231 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003232 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003233 bool &ObjCConversion,
3234 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003235 assert(!OrigT1->isReferenceType() &&
3236 "T1 must be the pointee type of the reference type");
3237 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3238
3239 QualType T1 = Context.getCanonicalType(OrigT1);
3240 QualType T2 = Context.getCanonicalType(OrigT2);
3241 Qualifiers T1Quals, T2Quals;
3242 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3243 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3244
3245 // C++ [dcl.init.ref]p4:
3246 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3247 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3248 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003249 DerivedToBase = false;
3250 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003251 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003252 if (UnqualT1 == UnqualT2) {
3253 // Nothing to do.
3254 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003255 IsDerivedFrom(UnqualT2, UnqualT1))
3256 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003257 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3258 UnqualT2->isObjCObjectOrInterfaceType() &&
3259 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3260 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003261 else
3262 return Ref_Incompatible;
3263
3264 // At this point, we know that T1 and T2 are reference-related (at
3265 // least).
3266
3267 // If the type is an array type, promote the element qualifiers to the type
3268 // for comparison.
3269 if (isa<ArrayType>(T1) && T1Quals)
3270 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3271 if (isa<ArrayType>(T2) && T2Quals)
3272 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3273
3274 // C++ [dcl.init.ref]p4:
3275 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3276 // reference-related to T2 and cv1 is the same cv-qualification
3277 // as, or greater cv-qualification than, cv2. For purposes of
3278 // overload resolution, cases for which cv1 is greater
3279 // cv-qualification than cv2 are identified as
3280 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003281 //
3282 // Note that we also require equivalence of Objective-C GC and address-space
3283 // qualifiers when performing these computations, so that e.g., an int in
3284 // address space 1 is not reference-compatible with an int in address
3285 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003286 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3287 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3288 T1Quals.removeObjCLifetime();
3289 T2Quals.removeObjCLifetime();
3290 ObjCLifetimeConversion = true;
3291 }
3292
Douglas Gregord517d552011-04-28 17:56:11 +00003293 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003294 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003295 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003296 return Ref_Compatible_With_Added_Qualification;
3297 else
3298 return Ref_Related;
3299}
3300
Douglas Gregor836a7e82010-08-11 02:15:33 +00003301/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003302/// with DeclType. Return true if something definite is found.
3303static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003304FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3305 QualType DeclType, SourceLocation DeclLoc,
3306 Expr *Init, QualType T2, bool AllowRvalues,
3307 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003308 assert(T2->isRecordType() && "Can only find conversions of record types.");
3309 CXXRecordDecl *T2RecordDecl
3310 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3311
3312 OverloadCandidateSet CandidateSet(DeclLoc);
3313 const UnresolvedSetImpl *Conversions
3314 = T2RecordDecl->getVisibleConversionFunctions();
3315 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3316 E = Conversions->end(); I != E; ++I) {
3317 NamedDecl *D = *I;
3318 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3319 if (isa<UsingShadowDecl>(D))
3320 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3321
3322 FunctionTemplateDecl *ConvTemplate
3323 = dyn_cast<FunctionTemplateDecl>(D);
3324 CXXConversionDecl *Conv;
3325 if (ConvTemplate)
3326 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3327 else
3328 Conv = cast<CXXConversionDecl>(D);
3329
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003330 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003331 // explicit conversions, skip it.
3332 if (!AllowExplicit && Conv->isExplicit())
3333 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003334
Douglas Gregor836a7e82010-08-11 02:15:33 +00003335 if (AllowRvalues) {
3336 bool DerivedToBase = false;
3337 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003338 bool ObjCLifetimeConversion = false;
Douglas Gregor836a7e82010-08-11 02:15:33 +00003339 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003340 S.CompareReferenceRelationship(
3341 DeclLoc,
3342 Conv->getConversionType().getNonReferenceType()
3343 .getUnqualifiedType(),
3344 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003345 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003346 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003347 continue;
3348 } else {
3349 // If the conversion function doesn't return a reference type,
3350 // it can't be considered for this conversion. An rvalue reference
3351 // is only acceptable if its referencee is a function type.
3352
3353 const ReferenceType *RefType =
3354 Conv->getConversionType()->getAs<ReferenceType>();
3355 if (!RefType ||
3356 (!RefType->isLValueReferenceType() &&
3357 !RefType->getPointeeType()->isFunctionType()))
3358 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003359 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003360
Douglas Gregor836a7e82010-08-11 02:15:33 +00003361 if (ConvTemplate)
3362 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003363 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003364 else
3365 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003366 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003367 }
3368
3369 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003370 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003371 case OR_Success:
3372 // C++ [over.ics.ref]p1:
3373 //
3374 // [...] If the parameter binds directly to the result of
3375 // applying a conversion function to the argument
3376 // expression, the implicit conversion sequence is a
3377 // user-defined conversion sequence (13.3.3.1.2), with the
3378 // second standard conversion sequence either an identity
3379 // conversion or, if the conversion function returns an
3380 // entity of a type that is a derived class of the parameter
3381 // type, a derived-to-base Conversion.
3382 if (!Best->FinalConversion.DirectBinding)
3383 return false;
3384
Chandler Carruth30141632011-02-25 19:41:05 +00003385 if (Best->Function)
3386 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003387 ICS.setUserDefined();
3388 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3389 ICS.UserDefined.After = Best->FinalConversion;
3390 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003391 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003392 ICS.UserDefined.EllipsisConversion = false;
3393 assert(ICS.UserDefined.After.ReferenceBinding &&
3394 ICS.UserDefined.After.DirectBinding &&
3395 "Expected a direct reference binding!");
3396 return true;
3397
3398 case OR_Ambiguous:
3399 ICS.setAmbiguous();
3400 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3401 Cand != CandidateSet.end(); ++Cand)
3402 if (Cand->Viable)
3403 ICS.Ambiguous.addConversion(Cand->Function);
3404 return true;
3405
3406 case OR_No_Viable_Function:
3407 case OR_Deleted:
3408 // There was no suitable conversion, or we found a deleted
3409 // conversion; continue with other checks.
3410 return false;
3411 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003412
Eric Christopheraba9fb22010-06-30 18:36:32 +00003413 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003414}
3415
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003416/// \brief Compute an implicit conversion sequence for reference
3417/// initialization.
3418static ImplicitConversionSequence
3419TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3420 SourceLocation DeclLoc,
3421 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003422 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003423 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3424
3425 // Most paths end in a failed conversion.
3426 ImplicitConversionSequence ICS;
3427 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3428
3429 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3430 QualType T2 = Init->getType();
3431
3432 // If the initializer is the address of an overloaded function, try
3433 // to resolve the overloaded function. If all goes well, T2 is the
3434 // type of the resulting function.
3435 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3436 DeclAccessPair Found;
3437 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3438 false, Found))
3439 T2 = Fn->getType();
3440 }
3441
3442 // Compute some basic properties of the types and the initializer.
3443 bool isRValRef = DeclType->isRValueReferenceType();
3444 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003445 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003446 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003447 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003448 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003449 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003450 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003451
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003452
Sebastian Redld92badf2010-06-30 18:13:39 +00003453 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003454 // A reference to type "cv1 T1" is initialized by an expression
3455 // of type "cv2 T2" as follows:
3456
Sebastian Redld92badf2010-06-30 18:13:39 +00003457 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003458 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003459 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3460 // reference-compatible with "cv2 T2," or
3461 //
3462 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3463 if (InitCategory.isLValue() &&
3464 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003465 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003466 // When a parameter of reference type binds directly (8.5.3)
3467 // to an argument expression, the implicit conversion sequence
3468 // is the identity conversion, unless the argument expression
3469 // has a type that is a derived class of the parameter type,
3470 // in which case the implicit conversion sequence is a
3471 // derived-to-base Conversion (13.3.3.1).
3472 ICS.setStandard();
3473 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003474 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3475 : ObjCConversion? ICK_Compatible_Conversion
3476 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003477 ICS.Standard.Third = ICK_Identity;
3478 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3479 ICS.Standard.setToType(0, T2);
3480 ICS.Standard.setToType(1, T1);
3481 ICS.Standard.setToType(2, T1);
3482 ICS.Standard.ReferenceBinding = true;
3483 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003484 ICS.Standard.IsLvalueReference = !isRValRef;
3485 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3486 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003487 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003488 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003489 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003490
Sebastian Redld92badf2010-06-30 18:13:39 +00003491 // Nothing more to do: the inaccessibility/ambiguity check for
3492 // derived-to-base conversions is suppressed when we're
3493 // computing the implicit conversion sequence (C++
3494 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003495 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003496 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003497
Sebastian Redld92badf2010-06-30 18:13:39 +00003498 // -- has a class type (i.e., T2 is a class type), where T1 is
3499 // not reference-related to T2, and can be implicitly
3500 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3501 // is reference-compatible with "cv3 T3" 92) (this
3502 // conversion is selected by enumerating the applicable
3503 // conversion functions (13.3.1.6) and choosing the best
3504 // one through overload resolution (13.3)),
3505 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003506 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003507 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003508 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3509 Init, T2, /*AllowRvalues=*/false,
3510 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003511 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003512 }
3513 }
3514
Sebastian Redld92badf2010-06-30 18:13:39 +00003515 // -- Otherwise, the reference shall be an lvalue reference to a
3516 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003517 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003518 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003519 // We actually handle one oddity of C++ [over.ics.ref] at this
3520 // point, which is that, due to p2 (which short-circuits reference
3521 // binding by only attempting a simple conversion for non-direct
3522 // bindings) and p3's strange wording, we allow a const volatile
3523 // reference to bind to an rvalue. Hence the check for the presence
3524 // of "const" rather than checking for "const" being the only
3525 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003526 // This is also the point where rvalue references and lvalue inits no longer
3527 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003528 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003529 return ICS;
3530
Douglas Gregorf143cd52011-01-24 16:14:37 +00003531 // -- If the initializer expression
3532 //
3533 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003534 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003535 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3536 (InitCategory.isXValue() ||
3537 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3538 (InitCategory.isLValue() && T2->isFunctionType()))) {
3539 ICS.setStandard();
3540 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003541 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003542 : ObjCConversion? ICK_Compatible_Conversion
3543 : ICK_Identity;
3544 ICS.Standard.Third = ICK_Identity;
3545 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3546 ICS.Standard.setToType(0, T2);
3547 ICS.Standard.setToType(1, T1);
3548 ICS.Standard.setToType(2, T1);
3549 ICS.Standard.ReferenceBinding = true;
3550 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3551 // binding unless we're binding to a class prvalue.
3552 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3553 // allow the use of rvalue references in C++98/03 for the benefit of
3554 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003555 ICS.Standard.DirectBinding =
3556 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003557 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003558 ICS.Standard.IsLvalueReference = !isRValRef;
3559 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003560 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003561 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003562 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003563 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003564 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003565 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003566
Douglas Gregorf143cd52011-01-24 16:14:37 +00003567 // -- has a class type (i.e., T2 is a class type), where T1 is not
3568 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003569 // an xvalue, class prvalue, or function lvalue of type
3570 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003571 // "cv3 T3",
3572 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003573 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003574 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003575 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003576 // class subobject).
3577 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003578 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003579 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3580 Init, T2, /*AllowRvalues=*/true,
3581 AllowExplicit)) {
3582 // In the second case, if the reference is an rvalue reference
3583 // and the second standard conversion sequence of the
3584 // user-defined conversion sequence includes an lvalue-to-rvalue
3585 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003586 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003587 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3588 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3589
Douglas Gregor95273c32011-01-21 16:36:05 +00003590 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003591 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003592
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003593 // -- Otherwise, a temporary of type "cv1 T1" is created and
3594 // initialized from the initializer expression using the
3595 // rules for a non-reference copy initialization (8.5). The
3596 // reference is then bound to the temporary. If T1 is
3597 // reference-related to T2, cv1 must be the same
3598 // cv-qualification as, or greater cv-qualification than,
3599 // cv2; otherwise, the program is ill-formed.
3600 if (RefRelationship == Sema::Ref_Related) {
3601 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3602 // we would be reference-compatible or reference-compatible with
3603 // added qualification. But that wasn't the case, so the reference
3604 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00003605 //
3606 // Note that we only want to check address spaces and cvr-qualifiers here.
3607 // ObjC GC and lifetime qualifiers aren't important.
3608 Qualifiers T1Quals = T1.getQualifiers();
3609 Qualifiers T2Quals = T2.getQualifiers();
3610 T1Quals.removeObjCGCAttr();
3611 T1Quals.removeObjCLifetime();
3612 T2Quals.removeObjCGCAttr();
3613 T2Quals.removeObjCLifetime();
3614 if (!T1Quals.compatiblyIncludes(T2Quals))
3615 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003616 }
3617
3618 // If at least one of the types is a class type, the types are not
3619 // related, and we aren't allowed any user conversions, the
3620 // reference binding fails. This case is important for breaking
3621 // recursion, since TryImplicitConversion below will attempt to
3622 // create a temporary through the use of a copy constructor.
3623 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3624 (T1->isRecordType() || T2->isRecordType()))
3625 return ICS;
3626
Douglas Gregorcba72b12011-01-21 05:18:22 +00003627 // If T1 is reference-related to T2 and the reference is an rvalue
3628 // reference, the initializer expression shall not be an lvalue.
3629 if (RefRelationship >= Sema::Ref_Related &&
3630 isRValRef && Init->Classify(S.Context).isLValue())
3631 return ICS;
3632
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003633 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003634 // When a parameter of reference type is not bound directly to
3635 // an argument expression, the conversion sequence is the one
3636 // required to convert the argument expression to the
3637 // underlying type of the reference according to
3638 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3639 // to copy-initializing a temporary of the underlying type with
3640 // the argument expression. Any difference in top-level
3641 // cv-qualification is subsumed by the initialization itself
3642 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003643 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3644 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003645 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003646 /*CStyle=*/false,
3647 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003648
3649 // Of course, that's still a reference binding.
3650 if (ICS.isStandard()) {
3651 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003652 ICS.Standard.IsLvalueReference = !isRValRef;
3653 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3654 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003655 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003656 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003657 } else if (ICS.isUserDefined()) {
3658 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00003659 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3660 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3661 ICS.UserDefined.After.BindsToRvalue = true;
3662 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3663 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003664 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003665
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003666 return ICS;
3667}
3668
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003669/// TryCopyInitialization - Try to copy-initialize a value of type
3670/// ToType from the expression From. Return the implicit conversion
3671/// sequence required to pass this argument, which may be a bad
3672/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003673/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003674/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003675static ImplicitConversionSequence
3676TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003677 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00003678 bool InOverloadResolution,
3679 bool AllowObjCWritebackConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003680 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003681 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003682 /*FIXME:*/From->getLocStart(),
3683 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003684 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003685
John McCall5c32be02010-08-24 20:38:10 +00003686 return TryImplicitConversion(S, From, ToType,
3687 SuppressUserConversions,
3688 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003689 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00003690 /*CStyle=*/false,
3691 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003692}
3693
Anna Zaks1b068122011-07-28 19:46:48 +00003694static bool TryCopyInitialization(const CanQualType FromQTy,
3695 const CanQualType ToQTy,
3696 Sema &S,
3697 SourceLocation Loc,
3698 ExprValueKind FromVK) {
3699 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
3700 ImplicitConversionSequence ICS =
3701 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
3702
3703 return !ICS.isBad();
3704}
3705
Douglas Gregor436424c2008-11-18 23:14:02 +00003706/// TryObjectArgumentInitialization - Try to initialize the object
3707/// parameter of the given member function (@c Method) from the
3708/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003709static ImplicitConversionSequence
3710TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003711 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003712 CXXMethodDecl *Method,
3713 CXXRecordDecl *ActingContext) {
3714 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003715 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3716 // const volatile object.
3717 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3718 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003719 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003720
3721 // Set up the conversion sequence as a "bad" conversion, to allow us
3722 // to exit early.
3723 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003724
3725 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003726 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003727 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003728 FromType = PT->getPointeeType();
3729
Douglas Gregor02824322011-01-26 19:30:28 +00003730 // When we had a pointer, it's implicitly dereferenced, so we
3731 // better have an lvalue.
3732 assert(FromClassification.isLValue());
3733 }
3734
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003735 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003736
Douglas Gregor02824322011-01-26 19:30:28 +00003737 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003738 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003739 // parameter is
3740 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003741 // - "lvalue reference to cv X" for functions declared without a
3742 // ref-qualifier or with the & ref-qualifier
3743 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003744 // ref-qualifier
3745 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003746 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003747 // cv-qualification on the member function declaration.
3748 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003750 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003751 // (C++ [over.match.funcs]p5). We perform a simplified version of
3752 // reference binding here, that allows class rvalues to bind to
3753 // non-constant references.
3754
Douglas Gregor02824322011-01-26 19:30:28 +00003755 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003756 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003757 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003758 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003759 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003760 ICS.setBad(BadConversionSequence::bad_qualifiers,
3761 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003762 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003763 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003764
3765 // Check that we have either the same type or a derived type. It
3766 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003767 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003768 ImplicitConversionKind SecondKind;
3769 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3770 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003771 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003772 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003773 else {
John McCall65eb8792010-02-25 01:37:24 +00003774 ICS.setBad(BadConversionSequence::unrelated_class,
3775 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003776 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003777 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003778
Douglas Gregor02824322011-01-26 19:30:28 +00003779 // Check the ref-qualifier.
3780 switch (Method->getRefQualifier()) {
3781 case RQ_None:
3782 // Do nothing; we don't care about lvalueness or rvalueness.
3783 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003784
Douglas Gregor02824322011-01-26 19:30:28 +00003785 case RQ_LValue:
3786 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3787 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003788 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003789 ImplicitParamType);
3790 return ICS;
3791 }
3792 break;
3793
3794 case RQ_RValue:
3795 if (!FromClassification.isRValue()) {
3796 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003797 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003798 ImplicitParamType);
3799 return ICS;
3800 }
3801 break;
3802 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003803
Douglas Gregor436424c2008-11-18 23:14:02 +00003804 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003805 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003806 ICS.Standard.setAsIdentityConversion();
3807 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003808 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003809 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003810 ICS.Standard.ReferenceBinding = true;
3811 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003812 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003813 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003814 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3815 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3816 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003817 return ICS;
3818}
3819
3820/// PerformObjectArgumentInitialization - Perform initialization of
3821/// the implicit object parameter for the given Method with the given
3822/// expression.
John Wiegley01296292011-04-08 18:41:53 +00003823ExprResult
3824Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003825 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003826 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003827 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003828 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003829 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003830 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003831
Douglas Gregor02824322011-01-26 19:30:28 +00003832 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003833 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003834 FromRecordType = PT->getPointeeType();
3835 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003836 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003837 } else {
3838 FromRecordType = From->getType();
3839 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003840 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003841 }
3842
John McCall6e9f8f62009-12-03 04:06:58 +00003843 // Note that we always use the true parent context when performing
3844 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003845 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003846 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3847 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003848 if (ICS.isBad()) {
3849 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3850 Qualifiers FromQs = FromRecordType.getQualifiers();
3851 Qualifiers ToQs = DestType.getQualifiers();
3852 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3853 if (CVR) {
3854 Diag(From->getSourceRange().getBegin(),
3855 diag::err_member_function_call_bad_cvr)
3856 << Method->getDeclName() << FromRecordType << (CVR - 1)
3857 << From->getSourceRange();
3858 Diag(Method->getLocation(), diag::note_previous_decl)
3859 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00003860 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003861 }
3862 }
3863
Douglas Gregor436424c2008-11-18 23:14:02 +00003864 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003865 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003866 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003867 }
Mike Stump11289f42009-09-09 15:08:12 +00003868
John Wiegley01296292011-04-08 18:41:53 +00003869 if (ICS.Standard.Second == ICK_Derived_To_Base) {
3870 ExprResult FromRes =
3871 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3872 if (FromRes.isInvalid())
3873 return ExprError();
3874 From = FromRes.take();
3875 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003876
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003877 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00003878 From = ImpCastExprToType(From, DestType, CK_NoOp,
3879 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3880 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00003881}
3882
Douglas Gregor5fb53972009-01-14 15:45:31 +00003883/// TryContextuallyConvertToBool - Attempt to contextually convert the
3884/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003885static ImplicitConversionSequence
3886TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003887 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003888 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003889 // FIXME: Are these flags correct?
3890 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003891 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003892 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003893 /*CStyle=*/false,
3894 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003895}
3896
3897/// PerformContextuallyConvertToBool - Perform a contextual conversion
3898/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00003899ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00003900 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003901 if (!ICS.isBad())
3902 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003903
Fariborz Jahanian76197412009-11-18 18:26:29 +00003904 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00003905 return Diag(From->getSourceRange().getBegin(),
3906 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003907 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003908 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00003909}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003910
John McCallfec112d2011-09-09 06:11:02 +00003911/// dropPointerConversions - If the given standard conversion sequence
3912/// involves any pointer conversions, remove them. This may change
3913/// the result type of the conversion sequence.
3914static void dropPointerConversion(StandardConversionSequence &SCS) {
3915 if (SCS.Second == ICK_Pointer_Conversion) {
3916 SCS.Second = ICK_Identity;
3917 SCS.Third = ICK_Identity;
3918 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
3919 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003920}
John McCall5c32be02010-08-24 20:38:10 +00003921
John McCallfec112d2011-09-09 06:11:02 +00003922/// TryContextuallyConvertToObjCPointer - Attempt to contextually
3923/// convert the expression From to an Objective-C pointer type.
3924static ImplicitConversionSequence
3925TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
3926 // Do an implicit conversion to 'id'.
3927 QualType Ty = S.Context.getObjCIdType();
3928 ImplicitConversionSequence ICS
3929 = TryImplicitConversion(S, From, Ty,
3930 // FIXME: Are these flags correct?
3931 /*SuppressUserConversions=*/false,
3932 /*AllowExplicit=*/true,
3933 /*InOverloadResolution=*/false,
3934 /*CStyle=*/false,
3935 /*AllowObjCWritebackConversion=*/false);
3936
3937 // Strip off any final conversions to 'id'.
3938 switch (ICS.getKind()) {
3939 case ImplicitConversionSequence::BadConversion:
3940 case ImplicitConversionSequence::AmbiguousConversion:
3941 case ImplicitConversionSequence::EllipsisConversion:
3942 break;
3943
3944 case ImplicitConversionSequence::UserDefinedConversion:
3945 dropPointerConversion(ICS.UserDefined.After);
3946 break;
3947
3948 case ImplicitConversionSequence::StandardConversion:
3949 dropPointerConversion(ICS.Standard);
3950 break;
3951 }
3952
3953 return ICS;
3954}
3955
3956/// PerformContextuallyConvertToObjCPointer - Perform a contextual
3957/// conversion of the expression From to an Objective-C pointer type.
3958ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003959 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00003960 ImplicitConversionSequence ICS =
3961 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003962 if (!ICS.isBad())
3963 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00003964 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003965}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003966
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003967/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003968/// enumeration type.
3969///
3970/// This routine will attempt to convert an expression of class type to an
3971/// integral or enumeration type, if that class type only has a single
3972/// conversion to an integral or enumeration type.
3973///
Douglas Gregor4799d032010-06-30 00:20:43 +00003974/// \param Loc The source location of the construct that requires the
3975/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003976///
Douglas Gregor4799d032010-06-30 00:20:43 +00003977/// \param FromE The expression we're converting from.
3978///
3979/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3980/// have integral or enumeration type.
3981///
3982/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3983/// incomplete class type.
3984///
3985/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3986/// explicit conversion function (because no implicit conversion functions
3987/// were available). This is a recovery mode.
3988///
3989/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3990/// showing which conversion was picked.
3991///
3992/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3993/// conversion function that could convert to integral or enumeration type.
3994///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003995/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00003996/// usable conversion function.
3997///
3998/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3999/// function, which may be an extension in this case.
4000///
4001/// \returns The expression, converted to an integral or enumeration type if
4002/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004003ExprResult
John McCallb268a282010-08-23 23:25:46 +00004004Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004005 const PartialDiagnostic &NotIntDiag,
4006 const PartialDiagnostic &IncompleteDiag,
4007 const PartialDiagnostic &ExplicitConvDiag,
4008 const PartialDiagnostic &ExplicitConvNote,
4009 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004010 const PartialDiagnostic &AmbigNote,
4011 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004012 // We can't perform any more checking for type-dependent expressions.
4013 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004014 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004015
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004016 // If the expression already has integral or enumeration type, we're golden.
4017 QualType T = From->getType();
4018 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00004019 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004020
4021 // FIXME: Check for missing '()' if T is a function type?
4022
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004023 // 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 +00004024 // expression of integral or enumeration type.
4025 const RecordType *RecordTy = T->getAs<RecordType>();
4026 if (!RecordTy || !getLangOptions().CPlusPlus) {
4027 Diag(Loc, NotIntDiag)
4028 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004029 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004030 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004031
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004032 // We must have a complete class type.
4033 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004034 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004035
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004036 // Look for a conversion to an integral or enumeration type.
4037 UnresolvedSet<4> ViableConversions;
4038 UnresolvedSet<4> ExplicitConversions;
4039 const UnresolvedSetImpl *Conversions
4040 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004041
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004042 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004043 E = Conversions->end();
4044 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004045 ++I) {
4046 if (CXXConversionDecl *Conversion
4047 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4048 if (Conversion->getConversionType().getNonReferenceType()
4049 ->isIntegralOrEnumerationType()) {
4050 if (Conversion->isExplicit())
4051 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4052 else
4053 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4054 }
4055 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004056
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004057 switch (ViableConversions.size()) {
4058 case 0:
4059 if (ExplicitConversions.size() == 1) {
4060 DeclAccessPair Found = ExplicitConversions[0];
4061 CXXConversionDecl *Conversion
4062 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004063
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004064 // The user probably meant to invoke the given explicit
4065 // conversion; use it.
4066 QualType ConvTy
4067 = Conversion->getConversionType().getNonReferenceType();
4068 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00004069 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004070
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004071 Diag(Loc, ExplicitConvDiag)
4072 << T << ConvTy
4073 << FixItHint::CreateInsertion(From->getLocStart(),
4074 "static_cast<" + TypeStr + ">(")
4075 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4076 ")");
4077 Diag(Conversion->getLocation(), ExplicitConvNote)
4078 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004079
4080 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004081 // explicit conversion function.
4082 if (isSFINAEContext())
4083 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004084
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004085 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00004086 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
4087 if (Result.isInvalid())
4088 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004089
Douglas Gregor668443e2011-01-20 00:18:04 +00004090 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004091 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004092
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004093 // We'll complain below about a non-integral condition type.
4094 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004095
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004096 case 1: {
4097 // Apply this conversion.
4098 DeclAccessPair Found = ViableConversions[0];
4099 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004100
Douglas Gregor4799d032010-06-30 00:20:43 +00004101 CXXConversionDecl *Conversion
4102 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4103 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004104 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004105 if (ConvDiag.getDiagID()) {
4106 if (isSFINAEContext())
4107 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004108
Douglas Gregor4799d032010-06-30 00:20:43 +00004109 Diag(Loc, ConvDiag)
4110 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004112
Douglas Gregor668443e2011-01-20 00:18:04 +00004113 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004114 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00004115 if (Result.isInvalid())
4116 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004117
Douglas Gregor668443e2011-01-20 00:18:04 +00004118 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004119 break;
4120 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004121
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004122 default:
4123 Diag(Loc, AmbigDiag)
4124 << T << From->getSourceRange();
4125 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4126 CXXConversionDecl *Conv
4127 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4128 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4129 Diag(Conv->getLocation(), AmbigNote)
4130 << ConvTy->isEnumeralType() << ConvTy;
4131 }
John McCallb268a282010-08-23 23:25:46 +00004132 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004133 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004134
Douglas Gregor5823da32010-06-29 23:25:20 +00004135 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004136 Diag(Loc, NotIntDiag)
4137 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004138
John McCallb268a282010-08-23 23:25:46 +00004139 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004140}
4141
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004142/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004143/// candidate functions, using the given function call arguments. If
4144/// @p SuppressUserConversions, then don't allow user-defined
4145/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004146///
4147/// \para PartialOverloading true if we are performing "partial" overloading
4148/// based on an incomplete set of function arguments. This feature is used by
4149/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004150void
4151Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004152 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004153 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004154 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004155 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004156 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004157 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004158 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004159 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004160 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004161 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004162
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004163 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004164 if (!isa<CXXConstructorDecl>(Method)) {
4165 // If we get here, it's because we're calling a member function
4166 // that is named without a member access expression (e.g.,
4167 // "this->f") that was either written explicitly or created
4168 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004169 // function, e.g., X::f(). We use an empty type for the implied
4170 // object argument (C++ [over.call.func]p3), and the acting context
4171 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004172 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004173 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004174 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004175 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004176 return;
4177 }
4178 // We treat a constructor like a non-member function, since its object
4179 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004180 }
4181
Douglas Gregorff7028a2009-11-13 23:59:09 +00004182 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004183 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004184
Douglas Gregor27381f32009-11-23 12:27:39 +00004185 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004186 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004187
Douglas Gregorffe14e32009-11-14 01:20:54 +00004188 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4189 // C++ [class.copy]p3:
4190 // A member function template is never instantiated to perform the copy
4191 // of a class object to an object of its class type.
4192 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004193 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004194 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004195 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4196 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004197 return;
4198 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004199
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004200 // Add this candidate
4201 CandidateSet.push_back(OverloadCandidate());
4202 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004203 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004204 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004205 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004206 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004207 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004208 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004209
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004210 unsigned NumArgsInProto = Proto->getNumArgs();
4211
4212 // (C++ 13.3.2p2): A candidate function having fewer than m
4213 // parameters is viable only if it has an ellipsis in its parameter
4214 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004215 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004216 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004217 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004218 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004219 return;
4220 }
4221
4222 // (C++ 13.3.2p2): A candidate function having more than m parameters
4223 // is viable only if the (m+1)st parameter has a default argument
4224 // (8.3.6). For the purposes of overload resolution, the
4225 // parameter list is truncated on the right, so that there are
4226 // exactly m parameters.
4227 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004228 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004229 // Not enough arguments.
4230 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004231 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004232 return;
4233 }
4234
4235 // Determine the implicit conversion sequences for each of the
4236 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004237 Candidate.Conversions.resize(NumArgs);
4238 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4239 if (ArgIdx < NumArgsInProto) {
4240 // (C++ 13.3.2p3): for F to be a viable function, there shall
4241 // exist for each argument an implicit conversion sequence
4242 // (13.3.3.1) that converts that argument to the corresponding
4243 // parameter of F.
4244 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004245 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004246 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004248 /*InOverloadResolution=*/true,
4249 /*AllowObjCWritebackConversion=*/
4250 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004251 if (Candidate.Conversions[ArgIdx].isBad()) {
4252 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004253 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004254 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004255 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004256 } else {
4257 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4258 // argument for which there is no corresponding parameter is
4259 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004260 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004261 }
4262 }
4263}
4264
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004265/// \brief Add all of the function declarations in the given function set to
4266/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004267void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004268 Expr **Args, unsigned NumArgs,
4269 OverloadCandidateSet& CandidateSet,
4270 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004271 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004272 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4273 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004274 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004275 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004276 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004277 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004279 CandidateSet, SuppressUserConversions);
4280 else
John McCalla0296f72010-03-19 07:35:19 +00004281 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004282 SuppressUserConversions);
4283 } else {
John McCalla0296f72010-03-19 07:35:19 +00004284 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004285 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4286 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004287 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004288 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004289 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004290 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004291 Args[0]->Classify(Context),
4292 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004293 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004294 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004295 else
John McCalla0296f72010-03-19 07:35:19 +00004296 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004297 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004298 Args, NumArgs, CandidateSet,
4299 SuppressUserConversions);
4300 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004301 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004302}
4303
John McCallf0f1cf02009-11-17 07:50:12 +00004304/// AddMethodCandidate - Adds a named decl (which is some kind of
4305/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004306void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004307 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004308 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004309 Expr **Args, unsigned NumArgs,
4310 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004311 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004312 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004313 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004314
4315 if (isa<UsingShadowDecl>(Decl))
4316 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004317
John McCallf0f1cf02009-11-17 07:50:12 +00004318 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4319 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4320 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004321 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4322 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004323 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004324 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004325 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004326 } else {
John McCalla0296f72010-03-19 07:35:19 +00004327 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004328 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004329 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004330 }
4331}
4332
Douglas Gregor436424c2008-11-18 23:14:02 +00004333/// AddMethodCandidate - Adds the given C++ member function to the set
4334/// of candidate functions, using the given function call arguments
4335/// and the object argument (@c Object). For example, in a call
4336/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4337/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4338/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004339/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004340void
John McCalla0296f72010-03-19 07:35:19 +00004341Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004342 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004343 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004344 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004345 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004346 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004347 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004348 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004349 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004350 assert(!isa<CXXConstructorDecl>(Method) &&
4351 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004352
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004353 if (!CandidateSet.isNewCandidate(Method))
4354 return;
4355
Douglas Gregor27381f32009-11-23 12:27:39 +00004356 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004357 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004358
Douglas Gregor436424c2008-11-18 23:14:02 +00004359 // Add this candidate
4360 CandidateSet.push_back(OverloadCandidate());
4361 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004362 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004363 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004364 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004365 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004366 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004367
4368 unsigned NumArgsInProto = Proto->getNumArgs();
4369
4370 // (C++ 13.3.2p2): A candidate function having fewer than m
4371 // parameters is viable only if it has an ellipsis in its parameter
4372 // list (8.3.5).
4373 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4374 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004375 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004376 return;
4377 }
4378
4379 // (C++ 13.3.2p2): A candidate function having more than m parameters
4380 // is viable only if the (m+1)st parameter has a default argument
4381 // (8.3.6). For the purposes of overload resolution, the
4382 // parameter list is truncated on the right, so that there are
4383 // exactly m parameters.
4384 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4385 if (NumArgs < MinRequiredArgs) {
4386 // Not enough arguments.
4387 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004388 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004389 return;
4390 }
4391
4392 Candidate.Viable = true;
4393 Candidate.Conversions.resize(NumArgs + 1);
4394
John McCall6e9f8f62009-12-03 04:06:58 +00004395 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004396 // The implicit object argument is ignored.
4397 Candidate.IgnoreObjectArgument = true;
4398 else {
4399 // Determine the implicit conversion sequence for the object
4400 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004401 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004402 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4403 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004404 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004405 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004406 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004407 return;
4408 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004409 }
4410
4411 // Determine the implicit conversion sequences for each of the
4412 // arguments.
4413 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4414 if (ArgIdx < NumArgsInProto) {
4415 // (C++ 13.3.2p3): for F to be a viable function, there shall
4416 // exist for each argument an implicit conversion sequence
4417 // (13.3.3.1) that converts that argument to the corresponding
4418 // parameter of F.
4419 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004420 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004421 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004422 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004423 /*InOverloadResolution=*/true,
4424 /*AllowObjCWritebackConversion=*/
4425 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004426 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004427 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004428 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004429 break;
4430 }
4431 } else {
4432 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4433 // argument for which there is no corresponding parameter is
4434 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004435 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004436 }
4437 }
4438}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004439
Douglas Gregor97628d62009-08-21 00:16:32 +00004440/// \brief Add a C++ member function template as a candidate to the candidate
4441/// set, using template argument deduction to produce an appropriate member
4442/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004443void
Douglas Gregor97628d62009-08-21 00:16:32 +00004444Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004445 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004446 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004447 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004448 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004449 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004450 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004451 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004452 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004453 if (!CandidateSet.isNewCandidate(MethodTmpl))
4454 return;
4455
Douglas Gregor97628d62009-08-21 00:16:32 +00004456 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004457 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004458 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004459 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004460 // candidate functions in the usual way.113) A given name can refer to one
4461 // or more function templates and also to a set of overloaded non-template
4462 // functions. In such a case, the candidate functions generated from each
4463 // function template are combined with the set of non-template candidate
4464 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004465 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004466 FunctionDecl *Specialization = 0;
4467 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004468 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004469 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004470 CandidateSet.push_back(OverloadCandidate());
4471 OverloadCandidate &Candidate = CandidateSet.back();
4472 Candidate.FoundDecl = FoundDecl;
4473 Candidate.Function = MethodTmpl->getTemplatedDecl();
4474 Candidate.Viable = false;
4475 Candidate.FailureKind = ovl_fail_bad_deduction;
4476 Candidate.IsSurrogate = false;
4477 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004478 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004479 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004480 Info);
4481 return;
4482 }
Mike Stump11289f42009-09-09 15:08:12 +00004483
Douglas Gregor97628d62009-08-21 00:16:32 +00004484 // Add the function template specialization produced by template argument
4485 // deduction as a candidate.
4486 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004487 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004488 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004489 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004490 ActingContext, ObjectType, ObjectClassification,
4491 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004492}
4493
Douglas Gregor05155d82009-08-21 23:19:43 +00004494/// \brief Add a C++ function template specialization as a candidate
4495/// in the candidate set, using template argument deduction to produce
4496/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004497void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004498Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004499 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004500 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004501 Expr **Args, unsigned NumArgs,
4502 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004503 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004504 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4505 return;
4506
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004507 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004508 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004509 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004510 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004511 // candidate functions in the usual way.113) A given name can refer to one
4512 // or more function templates and also to a set of overloaded non-template
4513 // functions. In such a case, the candidate functions generated from each
4514 // function template are combined with the set of non-template candidate
4515 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004516 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004517 FunctionDecl *Specialization = 0;
4518 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004519 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004520 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004521 CandidateSet.push_back(OverloadCandidate());
4522 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004523 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004524 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4525 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004526 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004527 Candidate.IsSurrogate = false;
4528 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004529 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004530 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004531 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004532 return;
4533 }
Mike Stump11289f42009-09-09 15:08:12 +00004534
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004535 // Add the function template specialization produced by template argument
4536 // deduction as a candidate.
4537 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004538 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004539 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004540}
Mike Stump11289f42009-09-09 15:08:12 +00004541
Douglas Gregora1f013e2008-11-07 22:36:19 +00004542/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004543/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004544/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004545/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004546/// (which may or may not be the same type as the type that the
4547/// conversion function produces).
4548void
4549Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004550 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004551 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004552 Expr *From, QualType ToType,
4553 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004554 assert(!Conversion->getDescribedFunctionTemplate() &&
4555 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004556 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004557 if (!CandidateSet.isNewCandidate(Conversion))
4558 return;
4559
Douglas Gregor27381f32009-11-23 12:27:39 +00004560 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004561 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004562
Douglas Gregora1f013e2008-11-07 22:36:19 +00004563 // Add this candidate
4564 CandidateSet.push_back(OverloadCandidate());
4565 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004566 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004567 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004568 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004569 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004570 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004571 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004572 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004573 Candidate.Viable = true;
4574 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004575 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004576
Douglas Gregor6affc782010-08-19 15:37:02 +00004577 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004578 // For conversion functions, the function is considered to be a member of
4579 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004580 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004581 //
4582 // Determine the implicit conversion sequence for the implicit
4583 // object parameter.
4584 QualType ImplicitParamType = From->getType();
4585 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4586 ImplicitParamType = FromPtrType->getPointeeType();
4587 CXXRecordDecl *ConversionContext
4588 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004589
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004590 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004591 = TryObjectArgumentInitialization(*this, From->getType(),
4592 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004593 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004594
John McCall0d1da222010-01-12 00:44:57 +00004595 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004596 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004597 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004598 return;
4599 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004600
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004601 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004602 // derived to base as such conversions are given Conversion Rank. They only
4603 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4604 QualType FromCanon
4605 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4606 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4607 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4608 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004609 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004610 return;
4611 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004612
Douglas Gregora1f013e2008-11-07 22:36:19 +00004613 // To determine what the conversion from the result of calling the
4614 // conversion function to the type we're eventually trying to
4615 // convert to (ToType), we need to synthesize a call to the
4616 // conversion function and attempt copy initialization from it. This
4617 // makes sure that we get the right semantics with respect to
4618 // lvalues/rvalues and the type. Fortunately, we can allocate this
4619 // call on the stack and we don't need its arguments to be
4620 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004621 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004622 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004623 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4624 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004625 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004626 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004627
Richard Smith48d24642011-07-13 22:53:21 +00004628 QualType ConversionType = Conversion->getConversionType();
4629 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004630 Candidate.Viable = false;
4631 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4632 return;
4633 }
4634
Richard Smith48d24642011-07-13 22:53:21 +00004635 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00004636
Mike Stump11289f42009-09-09 15:08:12 +00004637 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004638 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4639 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00004640 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004641 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004642 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004643 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004644 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004645 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00004646 /*InOverloadResolution=*/false,
4647 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004648
John McCall0d1da222010-01-12 00:44:57 +00004649 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004650 case ImplicitConversionSequence::StandardConversion:
4651 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004652
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004653 // C++ [over.ics.user]p3:
4654 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004655 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004656 // shall have exact match rank.
4657 if (Conversion->getPrimaryTemplate() &&
4658 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4659 Candidate.Viable = false;
4660 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4661 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004662
Douglas Gregorcba72b12011-01-21 05:18:22 +00004663 // C++0x [dcl.init.ref]p5:
4664 // In the second case, if the reference is an rvalue reference and
4665 // the second standard conversion sequence of the user-defined
4666 // conversion sequence includes an lvalue-to-rvalue conversion, the
4667 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004668 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004669 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4670 Candidate.Viable = false;
4671 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4672 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004673 break;
4674
4675 case ImplicitConversionSequence::BadConversion:
4676 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004677 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004678 break;
4679
4680 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004681 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00004682 "Can only end up with a standard conversion sequence or failure");
4683 }
4684}
4685
Douglas Gregor05155d82009-08-21 23:19:43 +00004686/// \brief Adds a conversion function template specialization
4687/// candidate to the overload set, using template argument deduction
4688/// to deduce the template arguments of the conversion function
4689/// template from the type that we are converting to (C++
4690/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004691void
Douglas Gregor05155d82009-08-21 23:19:43 +00004692Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004693 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004694 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004695 Expr *From, QualType ToType,
4696 OverloadCandidateSet &CandidateSet) {
4697 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4698 "Only conversion function templates permitted here");
4699
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004700 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4701 return;
4702
John McCallbc077cf2010-02-08 23:07:23 +00004703 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004704 CXXConversionDecl *Specialization = 0;
4705 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004706 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004707 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004708 CandidateSet.push_back(OverloadCandidate());
4709 OverloadCandidate &Candidate = CandidateSet.back();
4710 Candidate.FoundDecl = FoundDecl;
4711 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4712 Candidate.Viable = false;
4713 Candidate.FailureKind = ovl_fail_bad_deduction;
4714 Candidate.IsSurrogate = false;
4715 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004716 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004717 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004718 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004719 return;
4720 }
Mike Stump11289f42009-09-09 15:08:12 +00004721
Douglas Gregor05155d82009-08-21 23:19:43 +00004722 // Add the conversion function template specialization produced by
4723 // template argument deduction as a candidate.
4724 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004725 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004726 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004727}
4728
Douglas Gregorab7897a2008-11-19 22:57:39 +00004729/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4730/// converts the given @c Object to a function pointer via the
4731/// conversion function @c Conversion, and then attempts to call it
4732/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4733/// the type of function that we'll eventually be calling.
4734void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004735 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004736 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004737 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004738 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004739 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004740 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004741 if (!CandidateSet.isNewCandidate(Conversion))
4742 return;
4743
Douglas Gregor27381f32009-11-23 12:27:39 +00004744 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004745 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004746
Douglas Gregorab7897a2008-11-19 22:57:39 +00004747 CandidateSet.push_back(OverloadCandidate());
4748 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004749 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004750 Candidate.Function = 0;
4751 Candidate.Surrogate = Conversion;
4752 Candidate.Viable = true;
4753 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004754 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004755 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004756 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004757
4758 // Determine the implicit conversion sequence for the implicit
4759 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004760 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004761 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004762 Object->Classify(Context),
4763 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004764 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004765 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004766 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004767 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004768 return;
4769 }
4770
4771 // The first conversion is actually a user-defined conversion whose
4772 // first conversion is ObjectInit's standard conversion (which is
4773 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004774 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004775 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004776 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004777 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00004778 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00004779 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004780 = Candidate.Conversions[0].UserDefined.Before;
4781 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4782
Mike Stump11289f42009-09-09 15:08:12 +00004783 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004784 unsigned NumArgsInProto = Proto->getNumArgs();
4785
4786 // (C++ 13.3.2p2): A candidate function having fewer than m
4787 // parameters is viable only if it has an ellipsis in its parameter
4788 // list (8.3.5).
4789 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4790 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004791 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004792 return;
4793 }
4794
4795 // Function types don't have any default arguments, so just check if
4796 // we have enough arguments.
4797 if (NumArgs < NumArgsInProto) {
4798 // Not enough arguments.
4799 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004800 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004801 return;
4802 }
4803
4804 // Determine the implicit conversion sequences for each of the
4805 // arguments.
4806 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4807 if (ArgIdx < NumArgsInProto) {
4808 // (C++ 13.3.2p3): for F to be a viable function, there shall
4809 // exist for each argument an implicit conversion sequence
4810 // (13.3.3.1) that converts that argument to the corresponding
4811 // parameter of F.
4812 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004813 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004814 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004815 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00004816 /*InOverloadResolution=*/false,
4817 /*AllowObjCWritebackConversion=*/
4818 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004819 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004820 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004821 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004822 break;
4823 }
4824 } else {
4825 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4826 // argument for which there is no corresponding parameter is
4827 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004828 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004829 }
4830 }
4831}
4832
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004833/// \brief Add overload candidates for overloaded operators that are
4834/// member functions.
4835///
4836/// Add the overloaded operator candidates that are member functions
4837/// for the operator Op that was used in an operator expression such
4838/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4839/// CandidateSet will store the added overload candidates. (C++
4840/// [over.match.oper]).
4841void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4842 SourceLocation OpLoc,
4843 Expr **Args, unsigned NumArgs,
4844 OverloadCandidateSet& CandidateSet,
4845 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004846 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4847
4848 // C++ [over.match.oper]p3:
4849 // For a unary operator @ with an operand of a type whose
4850 // cv-unqualified version is T1, and for a binary operator @ with
4851 // a left operand of a type whose cv-unqualified version is T1 and
4852 // a right operand of a type whose cv-unqualified version is T2,
4853 // three sets of candidate functions, designated member
4854 // candidates, non-member candidates and built-in candidates, are
4855 // constructed as follows:
4856 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004857
4858 // -- If T1 is a class type, the set of member candidates is the
4859 // result of the qualified lookup of T1::operator@
4860 // (13.3.1.1.1); otherwise, the set of member candidates is
4861 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004862 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004863 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004864 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004865 return;
Mike Stump11289f42009-09-09 15:08:12 +00004866
John McCall27b18f82009-11-17 02:14:36 +00004867 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4868 LookupQualifiedName(Operators, T1Rec->getDecl());
4869 Operators.suppressDiagnostics();
4870
Mike Stump11289f42009-09-09 15:08:12 +00004871 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004872 OperEnd = Operators.end();
4873 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004874 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004875 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004876 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00004877 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004878 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004879 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004880}
4881
Douglas Gregora11693b2008-11-12 17:17:38 +00004882/// AddBuiltinCandidate - Add a candidate for a built-in
4883/// operator. ResultTy and ParamTys are the result and parameter types
4884/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004885/// arguments being passed to the candidate. IsAssignmentOperator
4886/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004887/// operator. NumContextualBoolArguments is the number of arguments
4888/// (at the beginning of the argument list) that will be contextually
4889/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004890void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004891 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004892 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004893 bool IsAssignmentOperator,
4894 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004895 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004896 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004897
Douglas Gregora11693b2008-11-12 17:17:38 +00004898 // Add this candidate
4899 CandidateSet.push_back(OverloadCandidate());
4900 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004901 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004902 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004903 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004904 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004905 Candidate.BuiltinTypes.ResultTy = ResultTy;
4906 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4907 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4908
4909 // Determine the implicit conversion sequences for each of the
4910 // arguments.
4911 Candidate.Viable = true;
4912 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004913 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004914 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004915 // C++ [over.match.oper]p4:
4916 // For the built-in assignment operators, conversions of the
4917 // left operand are restricted as follows:
4918 // -- no temporaries are introduced to hold the left operand, and
4919 // -- no user-defined conversions are applied to the left
4920 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004921 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004922 //
4923 // We block these conversions by turning off user-defined
4924 // conversions, since that is the only way that initialization of
4925 // a reference to a non-class type can occur from something that
4926 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004927 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004928 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004929 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004930 Candidate.Conversions[ArgIdx]
4931 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004932 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004933 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004934 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004935 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00004936 /*InOverloadResolution=*/false,
4937 /*AllowObjCWritebackConversion=*/
4938 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004939 }
John McCall0d1da222010-01-12 00:44:57 +00004940 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004941 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004942 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004943 break;
4944 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004945 }
4946}
4947
4948/// BuiltinCandidateTypeSet - A set of types that will be used for the
4949/// candidate operator functions for built-in operators (C++
4950/// [over.built]). The types are separated into pointer types and
4951/// enumeration types.
4952class BuiltinCandidateTypeSet {
4953 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004954 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004955
4956 /// PointerTypes - The set of pointer types that will be used in the
4957 /// built-in candidates.
4958 TypeSet PointerTypes;
4959
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004960 /// MemberPointerTypes - The set of member pointer types that will be
4961 /// used in the built-in candidates.
4962 TypeSet MemberPointerTypes;
4963
Douglas Gregora11693b2008-11-12 17:17:38 +00004964 /// EnumerationTypes - The set of enumeration types that will be
4965 /// used in the built-in candidates.
4966 TypeSet EnumerationTypes;
4967
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004968 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004969 /// candidates.
4970 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004971
4972 /// \brief A flag indicating non-record types are viable candidates
4973 bool HasNonRecordTypes;
4974
4975 /// \brief A flag indicating whether either arithmetic or enumeration types
4976 /// were present in the candidate set.
4977 bool HasArithmeticOrEnumeralTypes;
4978
Douglas Gregor80af3132011-05-21 23:15:46 +00004979 /// \brief A flag indicating whether the nullptr type was present in the
4980 /// candidate set.
4981 bool HasNullPtrType;
4982
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004983 /// Sema - The semantic analysis instance where we are building the
4984 /// candidate type set.
4985 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004986
Douglas Gregora11693b2008-11-12 17:17:38 +00004987 /// Context - The AST context in which we will build the type sets.
4988 ASTContext &Context;
4989
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004990 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4991 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004992 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004993
4994public:
4995 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004996 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004997
Mike Stump11289f42009-09-09 15:08:12 +00004998 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004999 : HasNonRecordTypes(false),
5000 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005001 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005002 SemaRef(SemaRef),
5003 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005004
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005005 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005006 SourceLocation Loc,
5007 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005008 bool AllowExplicitConversions,
5009 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005010
5011 /// pointer_begin - First pointer type found;
5012 iterator pointer_begin() { return PointerTypes.begin(); }
5013
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005014 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005015 iterator pointer_end() { return PointerTypes.end(); }
5016
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005017 /// member_pointer_begin - First member pointer type found;
5018 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5019
5020 /// member_pointer_end - Past the last member pointer type found;
5021 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5022
Douglas Gregora11693b2008-11-12 17:17:38 +00005023 /// enumeration_begin - First enumeration type found;
5024 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5025
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005026 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005027 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005028
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005029 iterator vector_begin() { return VectorTypes.begin(); }
5030 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005031
5032 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5033 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005034 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005035};
5036
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005037/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005038/// the set of pointer types along with any more-qualified variants of
5039/// that type. For example, if @p Ty is "int const *", this routine
5040/// will add "int const *", "int const volatile *", "int const
5041/// restrict *", and "int const volatile restrict *" to the set of
5042/// pointer types. Returns true if the add of @p Ty itself succeeded,
5043/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005044///
5045/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005046bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005047BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5048 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00005049
Douglas Gregora11693b2008-11-12 17:17:38 +00005050 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005051 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00005052 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005053
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005054 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00005055 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005056 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005057 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005058 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005059 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005060 buildObjCPtr = true;
5061 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005062 else
David Blaikie83d382b2011-09-23 05:06:16 +00005063 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005064 }
5065 else
5066 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005067
Sebastian Redl4990a632009-11-18 20:39:26 +00005068 // Don't add qualified variants of arrays. For one, they're not allowed
5069 // (the qualifier would sink to the element type), and for another, the
5070 // only overload situation where it matters is subscript or pointer +- int,
5071 // and those shouldn't have qualifier variants anyway.
5072 if (PointeeTy->isArrayType())
5073 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005074 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005075 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005076 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005077 bool hasVolatile = VisibleQuals.hasVolatile();
5078 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005079
John McCall8ccfcb52009-09-24 19:53:00 +00005080 // Iterate through all strict supersets of BaseCVR.
5081 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5082 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005083 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5084 // in the types.
5085 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5086 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005087 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005088 if (!buildObjCPtr)
5089 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5090 else
5091 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005092 }
5093
5094 return true;
5095}
5096
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005097/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5098/// to the set of pointer types along with any more-qualified variants of
5099/// that type. For example, if @p Ty is "int const *", this routine
5100/// will add "int const *", "int const volatile *", "int const
5101/// restrict *", and "int const volatile restrict *" to the set of
5102/// pointer types. Returns true if the add of @p Ty itself succeeded,
5103/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005104///
5105/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005106bool
5107BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5108 QualType Ty) {
5109 // Insert this type.
5110 if (!MemberPointerTypes.insert(Ty))
5111 return false;
5112
John McCall8ccfcb52009-09-24 19:53:00 +00005113 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5114 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005115
John McCall8ccfcb52009-09-24 19:53:00 +00005116 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005117 // Don't add qualified variants of arrays. For one, they're not allowed
5118 // (the qualifier would sink to the element type), and for another, the
5119 // only overload situation where it matters is subscript or pointer +- int,
5120 // and those shouldn't have qualifier variants anyway.
5121 if (PointeeTy->isArrayType())
5122 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005123 const Type *ClassTy = PointerTy->getClass();
5124
5125 // Iterate through all strict supersets of the pointee type's CVR
5126 // qualifiers.
5127 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5128 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5129 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005130
John McCall8ccfcb52009-09-24 19:53:00 +00005131 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005132 MemberPointerTypes.insert(
5133 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005134 }
5135
5136 return true;
5137}
5138
Douglas Gregora11693b2008-11-12 17:17:38 +00005139/// AddTypesConvertedFrom - Add each of the types to which the type @p
5140/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005141/// primarily interested in pointer types and enumeration types. We also
5142/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005143/// AllowUserConversions is true if we should look at the conversion
5144/// functions of a class type, and AllowExplicitConversions if we
5145/// should also include the explicit conversion functions of a class
5146/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005147void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005148BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005149 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005150 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005151 bool AllowExplicitConversions,
5152 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005153 // Only deal with canonical types.
5154 Ty = Context.getCanonicalType(Ty);
5155
5156 // Look through reference types; they aren't part of the type of an
5157 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005158 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005159 Ty = RefTy->getPointeeType();
5160
John McCall33ddac02011-01-19 10:06:00 +00005161 // If we're dealing with an array type, decay to the pointer.
5162 if (Ty->isArrayType())
5163 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5164
5165 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005166 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005167
Chandler Carruth00a38332010-12-13 01:44:01 +00005168 // Flag if we ever add a non-record type.
5169 const RecordType *TyRec = Ty->getAs<RecordType>();
5170 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5171
Chandler Carruth00a38332010-12-13 01:44:01 +00005172 // Flag if we encounter an arithmetic type.
5173 HasArithmeticOrEnumeralTypes =
5174 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5175
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005176 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5177 PointerTypes.insert(Ty);
5178 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005179 // Insert our type, and its more-qualified variants, into the set
5180 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005181 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005182 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005183 } else if (Ty->isMemberPointerType()) {
5184 // Member pointers are far easier, since the pointee can't be converted.
5185 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5186 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005187 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005188 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005189 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005190 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005191 // We treat vector types as arithmetic types in many contexts as an
5192 // extension.
5193 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005194 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005195 } else if (Ty->isNullPtrType()) {
5196 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005197 } else if (AllowUserConversions && TyRec) {
5198 // No conversion functions in incomplete types.
5199 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5200 return;
Mike Stump11289f42009-09-09 15:08:12 +00005201
Chandler Carruth00a38332010-12-13 01:44:01 +00005202 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5203 const UnresolvedSetImpl *Conversions
5204 = ClassDecl->getVisibleConversionFunctions();
5205 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5206 E = Conversions->end(); I != E; ++I) {
5207 NamedDecl *D = I.getDecl();
5208 if (isa<UsingShadowDecl>(D))
5209 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005210
Chandler Carruth00a38332010-12-13 01:44:01 +00005211 // Skip conversion function templates; they don't tell us anything
5212 // about which builtin types we can convert to.
5213 if (isa<FunctionTemplateDecl>(D))
5214 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005215
Chandler Carruth00a38332010-12-13 01:44:01 +00005216 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5217 if (AllowExplicitConversions || !Conv->isExplicit()) {
5218 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5219 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005220 }
5221 }
5222 }
5223}
5224
Douglas Gregor84605ae2009-08-24 13:43:27 +00005225/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5226/// the volatile- and non-volatile-qualified assignment operators for the
5227/// given type to the candidate set.
5228static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5229 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005230 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005231 unsigned NumArgs,
5232 OverloadCandidateSet &CandidateSet) {
5233 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005234
Douglas Gregor84605ae2009-08-24 13:43:27 +00005235 // T& operator=(T&, T)
5236 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5237 ParamTypes[1] = T;
5238 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5239 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005240
Douglas Gregor84605ae2009-08-24 13:43:27 +00005241 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5242 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005243 ParamTypes[0]
5244 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005245 ParamTypes[1] = T;
5246 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005247 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005248 }
5249}
Mike Stump11289f42009-09-09 15:08:12 +00005250
Sebastian Redl1054fae2009-10-25 17:03:50 +00005251/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5252/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005253static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5254 Qualifiers VRQuals;
5255 const RecordType *TyRec;
5256 if (const MemberPointerType *RHSMPType =
5257 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005258 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005259 else
5260 TyRec = ArgExpr->getType()->getAs<RecordType>();
5261 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005262 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005263 VRQuals.addVolatile();
5264 VRQuals.addRestrict();
5265 return VRQuals;
5266 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005267
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005268 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005269 if (!ClassDecl->hasDefinition())
5270 return VRQuals;
5271
John McCallad371252010-01-20 00:46:10 +00005272 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005273 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005274
John McCallad371252010-01-20 00:46:10 +00005275 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005276 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005277 NamedDecl *D = I.getDecl();
5278 if (isa<UsingShadowDecl>(D))
5279 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5280 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005281 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5282 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5283 CanTy = ResTypeRef->getPointeeType();
5284 // Need to go down the pointer/mempointer chain and add qualifiers
5285 // as see them.
5286 bool done = false;
5287 while (!done) {
5288 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5289 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005290 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005291 CanTy->getAs<MemberPointerType>())
5292 CanTy = ResTypeMPtr->getPointeeType();
5293 else
5294 done = true;
5295 if (CanTy.isVolatileQualified())
5296 VRQuals.addVolatile();
5297 if (CanTy.isRestrictQualified())
5298 VRQuals.addRestrict();
5299 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5300 return VRQuals;
5301 }
5302 }
5303 }
5304 return VRQuals;
5305}
John McCall52872982010-11-13 05:51:15 +00005306
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005307namespace {
John McCall52872982010-11-13 05:51:15 +00005308
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005309/// \brief Helper class to manage the addition of builtin operator overload
5310/// candidates. It provides shared state and utility methods used throughout
5311/// the process, as well as a helper method to add each group of builtin
5312/// operator overloads from the standard to a candidate set.
5313class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005314 // Common instance state available to all overload candidate addition methods.
5315 Sema &S;
5316 Expr **Args;
5317 unsigned NumArgs;
5318 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005319 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005320 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005321 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005322
Chandler Carruthc6586e52010-12-12 10:35:00 +00005323 // Define some constants used to index and iterate over the arithemetic types
5324 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005325 // The "promoted arithmetic types" are the arithmetic
5326 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005327 static const unsigned FirstIntegralType = 3;
5328 static const unsigned LastIntegralType = 18;
5329 static const unsigned FirstPromotedIntegralType = 3,
5330 LastPromotedIntegralType = 9;
5331 static const unsigned FirstPromotedArithmeticType = 0,
5332 LastPromotedArithmeticType = 9;
5333 static const unsigned NumArithmeticTypes = 18;
5334
Chandler Carruthc6586e52010-12-12 10:35:00 +00005335 /// \brief Get the canonical type for a given arithmetic type index.
5336 CanQualType getArithmeticType(unsigned index) {
5337 assert(index < NumArithmeticTypes);
5338 static CanQualType ASTContext::* const
5339 ArithmeticTypes[NumArithmeticTypes] = {
5340 // Start of promoted types.
5341 &ASTContext::FloatTy,
5342 &ASTContext::DoubleTy,
5343 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005344
Chandler Carruthc6586e52010-12-12 10:35:00 +00005345 // Start of integral types.
5346 &ASTContext::IntTy,
5347 &ASTContext::LongTy,
5348 &ASTContext::LongLongTy,
5349 &ASTContext::UnsignedIntTy,
5350 &ASTContext::UnsignedLongTy,
5351 &ASTContext::UnsignedLongLongTy,
5352 // End of promoted types.
5353
5354 &ASTContext::BoolTy,
5355 &ASTContext::CharTy,
5356 &ASTContext::WCharTy,
5357 &ASTContext::Char16Ty,
5358 &ASTContext::Char32Ty,
5359 &ASTContext::SignedCharTy,
5360 &ASTContext::ShortTy,
5361 &ASTContext::UnsignedCharTy,
5362 &ASTContext::UnsignedShortTy,
5363 // End of integral types.
5364 // FIXME: What about complex?
5365 };
5366 return S.Context.*ArithmeticTypes[index];
5367 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005368
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005369 /// \brief Gets the canonical type resulting from the usual arithemetic
5370 /// converions for the given arithmetic types.
5371 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5372 // Accelerator table for performing the usual arithmetic conversions.
5373 // The rules are basically:
5374 // - if either is floating-point, use the wider floating-point
5375 // - if same signedness, use the higher rank
5376 // - if same size, use unsigned of the higher rank
5377 // - use the larger type
5378 // These rules, together with the axiom that higher ranks are
5379 // never smaller, are sufficient to precompute all of these results
5380 // *except* when dealing with signed types of higher rank.
5381 // (we could precompute SLL x UI for all known platforms, but it's
5382 // better not to make any assumptions).
5383 enum PromotedType {
5384 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5385 };
5386 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5387 [LastPromotedArithmeticType] = {
5388 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5389 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5390 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5391 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5392 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5393 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5394 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5395 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5396 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5397 };
5398
5399 assert(L < LastPromotedArithmeticType);
5400 assert(R < LastPromotedArithmeticType);
5401 int Idx = ConversionsTable[L][R];
5402
5403 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005404 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005405
5406 // Slow path: we need to compare widths.
5407 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005408 CanQualType LT = getArithmeticType(L),
5409 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005410 unsigned LW = S.Context.getIntWidth(LT),
5411 RW = S.Context.getIntWidth(RT);
5412
5413 // If they're different widths, use the signed type.
5414 if (LW > RW) return LT;
5415 else if (LW < RW) return RT;
5416
5417 // Otherwise, use the unsigned type of the signed type's rank.
5418 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5419 assert(L == SLL || R == SLL);
5420 return S.Context.UnsignedLongLongTy;
5421 }
5422
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005423 /// \brief Helper method to factor out the common pattern of adding overloads
5424 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005425 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5426 bool HasVolatile) {
5427 QualType ParamTypes[2] = {
5428 S.Context.getLValueReferenceType(CandidateTy),
5429 S.Context.IntTy
5430 };
5431
5432 // Non-volatile version.
5433 if (NumArgs == 1)
5434 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5435 else
5436 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5437
5438 // Use a heuristic to reduce number of builtin candidates in the set:
5439 // add volatile version only if there are conversions to a volatile type.
5440 if (HasVolatile) {
5441 ParamTypes[0] =
5442 S.Context.getLValueReferenceType(
5443 S.Context.getVolatileType(CandidateTy));
5444 if (NumArgs == 1)
5445 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5446 else
5447 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5448 }
5449 }
5450
5451public:
5452 BuiltinOperatorOverloadBuilder(
5453 Sema &S, Expr **Args, unsigned NumArgs,
5454 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005455 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005456 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005457 OverloadCandidateSet &CandidateSet)
5458 : S(S), Args(Args), NumArgs(NumArgs),
5459 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005460 HasArithmeticOrEnumeralCandidateType(
5461 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005462 CandidateTypes(CandidateTypes),
5463 CandidateSet(CandidateSet) {
5464 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005465 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005466 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005467 assert(getArithmeticType(LastPromotedIntegralType - 1)
5468 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005469 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005470 assert(getArithmeticType(FirstPromotedArithmeticType)
5471 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005472 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005473 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5474 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005475 "Invalid last promoted arithmetic type");
5476 }
5477
5478 // C++ [over.built]p3:
5479 //
5480 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5481 // is either volatile or empty, there exist candidate operator
5482 // functions of the form
5483 //
5484 // VQ T& operator++(VQ T&);
5485 // T operator++(VQ T&, int);
5486 //
5487 // C++ [over.built]p4:
5488 //
5489 // For every pair (T, VQ), where T is an arithmetic type other
5490 // than bool, and VQ is either volatile or empty, there exist
5491 // candidate operator functions of the form
5492 //
5493 // VQ T& operator--(VQ T&);
5494 // T operator--(VQ T&, int);
5495 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005496 if (!HasArithmeticOrEnumeralCandidateType)
5497 return;
5498
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005499 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5500 Arith < NumArithmeticTypes; ++Arith) {
5501 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005502 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005503 VisibleTypeConversionsQuals.hasVolatile());
5504 }
5505 }
5506
5507 // C++ [over.built]p5:
5508 //
5509 // For every pair (T, VQ), where T is a cv-qualified or
5510 // cv-unqualified object type, and VQ is either volatile or
5511 // empty, there exist candidate operator functions of the form
5512 //
5513 // T*VQ& operator++(T*VQ&);
5514 // T*VQ& operator--(T*VQ&);
5515 // T* operator++(T*VQ&, int);
5516 // T* operator--(T*VQ&, int);
5517 void addPlusPlusMinusMinusPointerOverloads() {
5518 for (BuiltinCandidateTypeSet::iterator
5519 Ptr = CandidateTypes[0].pointer_begin(),
5520 PtrEnd = CandidateTypes[0].pointer_end();
5521 Ptr != PtrEnd; ++Ptr) {
5522 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005523 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005524 continue;
5525
5526 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5527 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5528 VisibleTypeConversionsQuals.hasVolatile()));
5529 }
5530 }
5531
5532 // C++ [over.built]p6:
5533 // For every cv-qualified or cv-unqualified object type T, there
5534 // exist candidate operator functions of the form
5535 //
5536 // T& operator*(T*);
5537 //
5538 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005539 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005540 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005541 // T& operator*(T*);
5542 void addUnaryStarPointerOverloads() {
5543 for (BuiltinCandidateTypeSet::iterator
5544 Ptr = CandidateTypes[0].pointer_begin(),
5545 PtrEnd = CandidateTypes[0].pointer_end();
5546 Ptr != PtrEnd; ++Ptr) {
5547 QualType ParamTy = *Ptr;
5548 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005549 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5550 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005551
Douglas Gregor02824322011-01-26 19:30:28 +00005552 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5553 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5554 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005555
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005556 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5557 &ParamTy, Args, 1, CandidateSet);
5558 }
5559 }
5560
5561 // C++ [over.built]p9:
5562 // For every promoted arithmetic type T, there exist candidate
5563 // operator functions of the form
5564 //
5565 // T operator+(T);
5566 // T operator-(T);
5567 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005568 if (!HasArithmeticOrEnumeralCandidateType)
5569 return;
5570
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005571 for (unsigned Arith = FirstPromotedArithmeticType;
5572 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005573 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005574 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5575 }
5576
5577 // Extension: We also add these operators for vector types.
5578 for (BuiltinCandidateTypeSet::iterator
5579 Vec = CandidateTypes[0].vector_begin(),
5580 VecEnd = CandidateTypes[0].vector_end();
5581 Vec != VecEnd; ++Vec) {
5582 QualType VecTy = *Vec;
5583 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5584 }
5585 }
5586
5587 // C++ [over.built]p8:
5588 // For every type T, there exist candidate operator functions of
5589 // the form
5590 //
5591 // T* operator+(T*);
5592 void addUnaryPlusPointerOverloads() {
5593 for (BuiltinCandidateTypeSet::iterator
5594 Ptr = CandidateTypes[0].pointer_begin(),
5595 PtrEnd = CandidateTypes[0].pointer_end();
5596 Ptr != PtrEnd; ++Ptr) {
5597 QualType ParamTy = *Ptr;
5598 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5599 }
5600 }
5601
5602 // C++ [over.built]p10:
5603 // For every promoted integral type T, there exist candidate
5604 // operator functions of the form
5605 //
5606 // T operator~(T);
5607 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005608 if (!HasArithmeticOrEnumeralCandidateType)
5609 return;
5610
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005611 for (unsigned Int = FirstPromotedIntegralType;
5612 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005613 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005614 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5615 }
5616
5617 // Extension: We also add this operator for vector types.
5618 for (BuiltinCandidateTypeSet::iterator
5619 Vec = CandidateTypes[0].vector_begin(),
5620 VecEnd = CandidateTypes[0].vector_end();
5621 Vec != VecEnd; ++Vec) {
5622 QualType VecTy = *Vec;
5623 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5624 }
5625 }
5626
5627 // C++ [over.match.oper]p16:
5628 // For every pointer to member type T, there exist candidate operator
5629 // functions of the form
5630 //
5631 // bool operator==(T,T);
5632 // bool operator!=(T,T);
5633 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5634 /// Set of (canonical) types that we've already handled.
5635 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5636
5637 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5638 for (BuiltinCandidateTypeSet::iterator
5639 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5640 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5641 MemPtr != MemPtrEnd;
5642 ++MemPtr) {
5643 // Don't add the same builtin candidate twice.
5644 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5645 continue;
5646
5647 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5648 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5649 CandidateSet);
5650 }
5651 }
5652 }
5653
5654 // C++ [over.built]p15:
5655 //
Douglas Gregor80af3132011-05-21 23:15:46 +00005656 // For every T, where T is an enumeration type, a pointer type, or
5657 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005658 //
5659 // bool operator<(T, T);
5660 // bool operator>(T, T);
5661 // bool operator<=(T, T);
5662 // bool operator>=(T, T);
5663 // bool operator==(T, T);
5664 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005665 void addRelationalPointerOrEnumeralOverloads() {
5666 // C++ [over.built]p1:
5667 // If there is a user-written candidate with the same name and parameter
5668 // types as a built-in candidate operator function, the built-in operator
5669 // function is hidden and is not included in the set of candidate
5670 // functions.
5671 //
5672 // The text is actually in a note, but if we don't implement it then we end
5673 // up with ambiguities when the user provides an overloaded operator for
5674 // an enumeration type. Note that only enumeration types have this problem,
5675 // so we track which enumeration types we've seen operators for. Also, the
5676 // only other overloaded operator with enumeration argumenst, operator=,
5677 // cannot be overloaded for enumeration types, so this is the only place
5678 // where we must suppress candidates like this.
5679 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5680 UserDefinedBinaryOperators;
5681
5682 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5683 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5684 CandidateTypes[ArgIdx].enumeration_end()) {
5685 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5686 CEnd = CandidateSet.end();
5687 C != CEnd; ++C) {
5688 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5689 continue;
5690
5691 QualType FirstParamType =
5692 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5693 QualType SecondParamType =
5694 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5695
5696 // Skip if either parameter isn't of enumeral type.
5697 if (!FirstParamType->isEnumeralType() ||
5698 !SecondParamType->isEnumeralType())
5699 continue;
5700
5701 // Add this operator to the set of known user-defined operators.
5702 UserDefinedBinaryOperators.insert(
5703 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5704 S.Context.getCanonicalType(SecondParamType)));
5705 }
5706 }
5707 }
5708
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005709 /// Set of (canonical) types that we've already handled.
5710 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5711
5712 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5713 for (BuiltinCandidateTypeSet::iterator
5714 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5715 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5716 Ptr != PtrEnd; ++Ptr) {
5717 // Don't add the same builtin candidate twice.
5718 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5719 continue;
5720
5721 QualType ParamTypes[2] = { *Ptr, *Ptr };
5722 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5723 CandidateSet);
5724 }
5725 for (BuiltinCandidateTypeSet::iterator
5726 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5727 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5728 Enum != EnumEnd; ++Enum) {
5729 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5730
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005731 // Don't add the same builtin candidate twice, or if a user defined
5732 // candidate exists.
5733 if (!AddedTypes.insert(CanonType) ||
5734 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5735 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005736 continue;
5737
5738 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005739 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5740 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005741 }
Douglas Gregor80af3132011-05-21 23:15:46 +00005742
5743 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5744 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5745 if (AddedTypes.insert(NullPtrTy) &&
5746 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5747 NullPtrTy))) {
5748 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5749 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5750 CandidateSet);
5751 }
5752 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005753 }
5754 }
5755
5756 // C++ [over.built]p13:
5757 //
5758 // For every cv-qualified or cv-unqualified object type T
5759 // there exist candidate operator functions of the form
5760 //
5761 // T* operator+(T*, ptrdiff_t);
5762 // T& operator[](T*, ptrdiff_t); [BELOW]
5763 // T* operator-(T*, ptrdiff_t);
5764 // T* operator+(ptrdiff_t, T*);
5765 // T& operator[](ptrdiff_t, T*); [BELOW]
5766 //
5767 // C++ [over.built]p14:
5768 //
5769 // For every T, where T is a pointer to object type, there
5770 // exist candidate operator functions of the form
5771 //
5772 // ptrdiff_t operator-(T, T);
5773 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5774 /// Set of (canonical) types that we've already handled.
5775 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5776
5777 for (int Arg = 0; Arg < 2; ++Arg) {
5778 QualType AsymetricParamTypes[2] = {
5779 S.Context.getPointerDiffType(),
5780 S.Context.getPointerDiffType(),
5781 };
5782 for (BuiltinCandidateTypeSet::iterator
5783 Ptr = CandidateTypes[Arg].pointer_begin(),
5784 PtrEnd = CandidateTypes[Arg].pointer_end();
5785 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005786 QualType PointeeTy = (*Ptr)->getPointeeType();
5787 if (!PointeeTy->isObjectType())
5788 continue;
5789
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005790 AsymetricParamTypes[Arg] = *Ptr;
5791 if (Arg == 0 || Op == OO_Plus) {
5792 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5793 // T* operator+(ptrdiff_t, T*);
5794 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5795 CandidateSet);
5796 }
5797 if (Op == OO_Minus) {
5798 // ptrdiff_t operator-(T, T);
5799 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5800 continue;
5801
5802 QualType ParamTypes[2] = { *Ptr, *Ptr };
5803 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5804 Args, 2, CandidateSet);
5805 }
5806 }
5807 }
5808 }
5809
5810 // C++ [over.built]p12:
5811 //
5812 // For every pair of promoted arithmetic types L and R, there
5813 // exist candidate operator functions of the form
5814 //
5815 // LR operator*(L, R);
5816 // LR operator/(L, R);
5817 // LR operator+(L, R);
5818 // LR operator-(L, R);
5819 // bool operator<(L, R);
5820 // bool operator>(L, R);
5821 // bool operator<=(L, R);
5822 // bool operator>=(L, R);
5823 // bool operator==(L, R);
5824 // bool operator!=(L, R);
5825 //
5826 // where LR is the result of the usual arithmetic conversions
5827 // between types L and R.
5828 //
5829 // C++ [over.built]p24:
5830 //
5831 // For every pair of promoted arithmetic types L and R, there exist
5832 // candidate operator functions of the form
5833 //
5834 // LR operator?(bool, L, R);
5835 //
5836 // where LR is the result of the usual arithmetic conversions
5837 // between types L and R.
5838 // Our candidates ignore the first parameter.
5839 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005840 if (!HasArithmeticOrEnumeralCandidateType)
5841 return;
5842
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005843 for (unsigned Left = FirstPromotedArithmeticType;
5844 Left < LastPromotedArithmeticType; ++Left) {
5845 for (unsigned Right = FirstPromotedArithmeticType;
5846 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005847 QualType LandR[2] = { getArithmeticType(Left),
5848 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005849 QualType Result =
5850 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005851 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005852 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5853 }
5854 }
5855
5856 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5857 // conditional operator for vector types.
5858 for (BuiltinCandidateTypeSet::iterator
5859 Vec1 = CandidateTypes[0].vector_begin(),
5860 Vec1End = CandidateTypes[0].vector_end();
5861 Vec1 != Vec1End; ++Vec1) {
5862 for (BuiltinCandidateTypeSet::iterator
5863 Vec2 = CandidateTypes[1].vector_begin(),
5864 Vec2End = CandidateTypes[1].vector_end();
5865 Vec2 != Vec2End; ++Vec2) {
5866 QualType LandR[2] = { *Vec1, *Vec2 };
5867 QualType Result = S.Context.BoolTy;
5868 if (!isComparison) {
5869 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5870 Result = *Vec1;
5871 else
5872 Result = *Vec2;
5873 }
5874
5875 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5876 }
5877 }
5878 }
5879
5880 // C++ [over.built]p17:
5881 //
5882 // For every pair of promoted integral types L and R, there
5883 // exist candidate operator functions of the form
5884 //
5885 // LR operator%(L, R);
5886 // LR operator&(L, R);
5887 // LR operator^(L, R);
5888 // LR operator|(L, R);
5889 // L operator<<(L, R);
5890 // L operator>>(L, R);
5891 //
5892 // where LR is the result of the usual arithmetic conversions
5893 // between types L and R.
5894 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005895 if (!HasArithmeticOrEnumeralCandidateType)
5896 return;
5897
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005898 for (unsigned Left = FirstPromotedIntegralType;
5899 Left < LastPromotedIntegralType; ++Left) {
5900 for (unsigned Right = FirstPromotedIntegralType;
5901 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005902 QualType LandR[2] = { getArithmeticType(Left),
5903 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005904 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5905 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005906 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005907 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5908 }
5909 }
5910 }
5911
5912 // C++ [over.built]p20:
5913 //
5914 // For every pair (T, VQ), where T is an enumeration or
5915 // pointer to member type and VQ is either volatile or
5916 // empty, there exist candidate operator functions of the form
5917 //
5918 // VQ T& operator=(VQ T&, T);
5919 void addAssignmentMemberPointerOrEnumeralOverloads() {
5920 /// Set of (canonical) types that we've already handled.
5921 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5922
5923 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5924 for (BuiltinCandidateTypeSet::iterator
5925 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5926 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5927 Enum != EnumEnd; ++Enum) {
5928 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5929 continue;
5930
5931 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5932 CandidateSet);
5933 }
5934
5935 for (BuiltinCandidateTypeSet::iterator
5936 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5937 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5938 MemPtr != MemPtrEnd; ++MemPtr) {
5939 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5940 continue;
5941
5942 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5943 CandidateSet);
5944 }
5945 }
5946 }
5947
5948 // C++ [over.built]p19:
5949 //
5950 // For every pair (T, VQ), where T is any type and VQ is either
5951 // volatile or empty, there exist candidate operator functions
5952 // of the form
5953 //
5954 // T*VQ& operator=(T*VQ&, T*);
5955 //
5956 // C++ [over.built]p21:
5957 //
5958 // For every pair (T, VQ), where T is a cv-qualified or
5959 // cv-unqualified object type and VQ is either volatile or
5960 // empty, there exist candidate operator functions of the form
5961 //
5962 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5963 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5964 void addAssignmentPointerOverloads(bool isEqualOp) {
5965 /// Set of (canonical) types that we've already handled.
5966 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5967
5968 for (BuiltinCandidateTypeSet::iterator
5969 Ptr = CandidateTypes[0].pointer_begin(),
5970 PtrEnd = CandidateTypes[0].pointer_end();
5971 Ptr != PtrEnd; ++Ptr) {
5972 // If this is operator=, keep track of the builtin candidates we added.
5973 if (isEqualOp)
5974 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005975 else if (!(*Ptr)->getPointeeType()->isObjectType())
5976 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005977
5978 // non-volatile version
5979 QualType ParamTypes[2] = {
5980 S.Context.getLValueReferenceType(*Ptr),
5981 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5982 };
5983 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5984 /*IsAssigmentOperator=*/ isEqualOp);
5985
5986 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5987 VisibleTypeConversionsQuals.hasVolatile()) {
5988 // volatile version
5989 ParamTypes[0] =
5990 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5991 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5992 /*IsAssigmentOperator=*/isEqualOp);
5993 }
5994 }
5995
5996 if (isEqualOp) {
5997 for (BuiltinCandidateTypeSet::iterator
5998 Ptr = CandidateTypes[1].pointer_begin(),
5999 PtrEnd = CandidateTypes[1].pointer_end();
6000 Ptr != PtrEnd; ++Ptr) {
6001 // Make sure we don't add the same candidate twice.
6002 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6003 continue;
6004
Chandler Carruth8e543b32010-12-12 08:17:55 +00006005 QualType ParamTypes[2] = {
6006 S.Context.getLValueReferenceType(*Ptr),
6007 *Ptr,
6008 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006009
6010 // non-volatile version
6011 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6012 /*IsAssigmentOperator=*/true);
6013
6014 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6015 VisibleTypeConversionsQuals.hasVolatile()) {
6016 // volatile version
6017 ParamTypes[0] =
6018 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006019 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6020 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006021 }
6022 }
6023 }
6024 }
6025
6026 // C++ [over.built]p18:
6027 //
6028 // For every triple (L, VQ, R), where L is an arithmetic type,
6029 // VQ is either volatile or empty, and R is a promoted
6030 // arithmetic type, there exist candidate operator functions of
6031 // the form
6032 //
6033 // VQ L& operator=(VQ L&, R);
6034 // VQ L& operator*=(VQ L&, R);
6035 // VQ L& operator/=(VQ L&, R);
6036 // VQ L& operator+=(VQ L&, R);
6037 // VQ L& operator-=(VQ L&, R);
6038 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006039 if (!HasArithmeticOrEnumeralCandidateType)
6040 return;
6041
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006042 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6043 for (unsigned Right = FirstPromotedArithmeticType;
6044 Right < LastPromotedArithmeticType; ++Right) {
6045 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006046 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006047
6048 // Add this built-in operator as a candidate (VQ is empty).
6049 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006050 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006051 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6052 /*IsAssigmentOperator=*/isEqualOp);
6053
6054 // Add this built-in operator as a candidate (VQ is 'volatile').
6055 if (VisibleTypeConversionsQuals.hasVolatile()) {
6056 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006057 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006058 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006059 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6060 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006061 /*IsAssigmentOperator=*/isEqualOp);
6062 }
6063 }
6064 }
6065
6066 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6067 for (BuiltinCandidateTypeSet::iterator
6068 Vec1 = CandidateTypes[0].vector_begin(),
6069 Vec1End = CandidateTypes[0].vector_end();
6070 Vec1 != Vec1End; ++Vec1) {
6071 for (BuiltinCandidateTypeSet::iterator
6072 Vec2 = CandidateTypes[1].vector_begin(),
6073 Vec2End = CandidateTypes[1].vector_end();
6074 Vec2 != Vec2End; ++Vec2) {
6075 QualType ParamTypes[2];
6076 ParamTypes[1] = *Vec2;
6077 // Add this built-in operator as a candidate (VQ is empty).
6078 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6079 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6080 /*IsAssigmentOperator=*/isEqualOp);
6081
6082 // Add this built-in operator as a candidate (VQ is 'volatile').
6083 if (VisibleTypeConversionsQuals.hasVolatile()) {
6084 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6085 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006086 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6087 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006088 /*IsAssigmentOperator=*/isEqualOp);
6089 }
6090 }
6091 }
6092 }
6093
6094 // C++ [over.built]p22:
6095 //
6096 // For every triple (L, VQ, R), where L is an integral type, VQ
6097 // is either volatile or empty, and R is a promoted integral
6098 // type, there exist candidate operator functions of the form
6099 //
6100 // VQ L& operator%=(VQ L&, R);
6101 // VQ L& operator<<=(VQ L&, R);
6102 // VQ L& operator>>=(VQ L&, R);
6103 // VQ L& operator&=(VQ L&, R);
6104 // VQ L& operator^=(VQ L&, R);
6105 // VQ L& operator|=(VQ L&, R);
6106 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006107 if (!HasArithmeticOrEnumeralCandidateType)
6108 return;
6109
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006110 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6111 for (unsigned Right = FirstPromotedIntegralType;
6112 Right < LastPromotedIntegralType; ++Right) {
6113 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006114 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006115
6116 // Add this built-in operator as a candidate (VQ is empty).
6117 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006118 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006119 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6120 if (VisibleTypeConversionsQuals.hasVolatile()) {
6121 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006122 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006123 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6124 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6125 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6126 CandidateSet);
6127 }
6128 }
6129 }
6130 }
6131
6132 // C++ [over.operator]p23:
6133 //
6134 // There also exist candidate operator functions of the form
6135 //
6136 // bool operator!(bool);
6137 // bool operator&&(bool, bool);
6138 // bool operator||(bool, bool);
6139 void addExclaimOverload() {
6140 QualType ParamTy = S.Context.BoolTy;
6141 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6142 /*IsAssignmentOperator=*/false,
6143 /*NumContextualBoolArguments=*/1);
6144 }
6145 void addAmpAmpOrPipePipeOverload() {
6146 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6147 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6148 /*IsAssignmentOperator=*/false,
6149 /*NumContextualBoolArguments=*/2);
6150 }
6151
6152 // C++ [over.built]p13:
6153 //
6154 // For every cv-qualified or cv-unqualified object type T there
6155 // exist candidate operator functions of the form
6156 //
6157 // T* operator+(T*, ptrdiff_t); [ABOVE]
6158 // T& operator[](T*, ptrdiff_t);
6159 // T* operator-(T*, ptrdiff_t); [ABOVE]
6160 // T* operator+(ptrdiff_t, T*); [ABOVE]
6161 // T& operator[](ptrdiff_t, T*);
6162 void addSubscriptOverloads() {
6163 for (BuiltinCandidateTypeSet::iterator
6164 Ptr = CandidateTypes[0].pointer_begin(),
6165 PtrEnd = CandidateTypes[0].pointer_end();
6166 Ptr != PtrEnd; ++Ptr) {
6167 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6168 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006169 if (!PointeeType->isObjectType())
6170 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006171
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006172 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6173
6174 // T& operator[](T*, ptrdiff_t)
6175 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6176 }
6177
6178 for (BuiltinCandidateTypeSet::iterator
6179 Ptr = CandidateTypes[1].pointer_begin(),
6180 PtrEnd = CandidateTypes[1].pointer_end();
6181 Ptr != PtrEnd; ++Ptr) {
6182 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6183 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006184 if (!PointeeType->isObjectType())
6185 continue;
6186
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006187 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6188
6189 // T& operator[](ptrdiff_t, T*)
6190 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6191 }
6192 }
6193
6194 // C++ [over.built]p11:
6195 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6196 // C1 is the same type as C2 or is a derived class of C2, T is an object
6197 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6198 // there exist candidate operator functions of the form
6199 //
6200 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6201 //
6202 // where CV12 is the union of CV1 and CV2.
6203 void addArrowStarOverloads() {
6204 for (BuiltinCandidateTypeSet::iterator
6205 Ptr = CandidateTypes[0].pointer_begin(),
6206 PtrEnd = CandidateTypes[0].pointer_end();
6207 Ptr != PtrEnd; ++Ptr) {
6208 QualType C1Ty = (*Ptr);
6209 QualType C1;
6210 QualifierCollector Q1;
6211 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6212 if (!isa<RecordType>(C1))
6213 continue;
6214 // heuristic to reduce number of builtin candidates in the set.
6215 // Add volatile/restrict version only if there are conversions to a
6216 // volatile/restrict type.
6217 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6218 continue;
6219 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6220 continue;
6221 for (BuiltinCandidateTypeSet::iterator
6222 MemPtr = CandidateTypes[1].member_pointer_begin(),
6223 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6224 MemPtr != MemPtrEnd; ++MemPtr) {
6225 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6226 QualType C2 = QualType(mptr->getClass(), 0);
6227 C2 = C2.getUnqualifiedType();
6228 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6229 break;
6230 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6231 // build CV12 T&
6232 QualType T = mptr->getPointeeType();
6233 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6234 T.isVolatileQualified())
6235 continue;
6236 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6237 T.isRestrictQualified())
6238 continue;
6239 T = Q1.apply(S.Context, T);
6240 QualType ResultTy = S.Context.getLValueReferenceType(T);
6241 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6242 }
6243 }
6244 }
6245
6246 // Note that we don't consider the first argument, since it has been
6247 // contextually converted to bool long ago. The candidates below are
6248 // therefore added as binary.
6249 //
6250 // C++ [over.built]p25:
6251 // For every type T, where T is a pointer, pointer-to-member, or scoped
6252 // enumeration type, there exist candidate operator functions of the form
6253 //
6254 // T operator?(bool, T, T);
6255 //
6256 void addConditionalOperatorOverloads() {
6257 /// Set of (canonical) types that we've already handled.
6258 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6259
6260 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6261 for (BuiltinCandidateTypeSet::iterator
6262 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6263 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6264 Ptr != PtrEnd; ++Ptr) {
6265 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6266 continue;
6267
6268 QualType ParamTypes[2] = { *Ptr, *Ptr };
6269 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6270 }
6271
6272 for (BuiltinCandidateTypeSet::iterator
6273 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6274 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6275 MemPtr != MemPtrEnd; ++MemPtr) {
6276 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6277 continue;
6278
6279 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6280 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6281 }
6282
6283 if (S.getLangOptions().CPlusPlus0x) {
6284 for (BuiltinCandidateTypeSet::iterator
6285 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6286 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6287 Enum != EnumEnd; ++Enum) {
6288 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6289 continue;
6290
6291 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6292 continue;
6293
6294 QualType ParamTypes[2] = { *Enum, *Enum };
6295 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6296 }
6297 }
6298 }
6299 }
6300};
6301
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006302} // end anonymous namespace
6303
6304/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6305/// operator overloads to the candidate set (C++ [over.built]), based
6306/// on the operator @p Op and the arguments given. For example, if the
6307/// operator is a binary '+', this routine might add "int
6308/// operator+(int, int)" to cover integer addition.
6309void
6310Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6311 SourceLocation OpLoc,
6312 Expr **Args, unsigned NumArgs,
6313 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006314 // Find all of the types that the arguments can convert to, but only
6315 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006316 // that make use of these types. Also record whether we encounter non-record
6317 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006318 Qualifiers VisibleTypeConversionsQuals;
6319 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006320 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6321 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006322
6323 bool HasNonRecordCandidateType = false;
6324 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006325 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006326 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6327 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6328 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6329 OpLoc,
6330 true,
6331 (Op == OO_Exclaim ||
6332 Op == OO_AmpAmp ||
6333 Op == OO_PipePipe),
6334 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006335 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6336 CandidateTypes[ArgIdx].hasNonRecordTypes();
6337 HasArithmeticOrEnumeralCandidateType =
6338 HasArithmeticOrEnumeralCandidateType ||
6339 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006340 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006341
Chandler Carruth00a38332010-12-13 01:44:01 +00006342 // Exit early when no non-record types have been added to the candidate set
6343 // for any of the arguments to the operator.
6344 if (!HasNonRecordCandidateType)
6345 return;
6346
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006347 // Setup an object to manage the common state for building overloads.
6348 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6349 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006350 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006351 CandidateTypes, CandidateSet);
6352
6353 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006354 switch (Op) {
6355 case OO_None:
6356 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00006357 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00006358
Chandler Carruth5184de02010-12-12 08:51:33 +00006359 case OO_New:
6360 case OO_Delete:
6361 case OO_Array_New:
6362 case OO_Array_Delete:
6363 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00006364 llvm_unreachable(
6365 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00006366
6367 case OO_Comma:
6368 case OO_Arrow:
6369 // C++ [over.match.oper]p3:
6370 // -- For the operator ',', the unary operator '&', or the
6371 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006372 break;
6373
6374 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006375 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006376 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006377 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006378
6379 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006380 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006381 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006382 } else {
6383 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6384 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6385 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006386 break;
6387
Chandler Carruth5184de02010-12-12 08:51:33 +00006388 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006389 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006390 OpBuilder.addUnaryStarPointerOverloads();
6391 else
6392 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6393 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006394
Chandler Carruth5184de02010-12-12 08:51:33 +00006395 case OO_Slash:
6396 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006397 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006398
6399 case OO_PlusPlus:
6400 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006401 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6402 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006403 break;
6404
Douglas Gregor84605ae2009-08-24 13:43:27 +00006405 case OO_EqualEqual:
6406 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006407 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006408 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006409
Douglas Gregora11693b2008-11-12 17:17:38 +00006410 case OO_Less:
6411 case OO_Greater:
6412 case OO_LessEqual:
6413 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006414 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006415 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6416 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006417
Douglas Gregora11693b2008-11-12 17:17:38 +00006418 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006419 case OO_Caret:
6420 case OO_Pipe:
6421 case OO_LessLess:
6422 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006423 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006424 break;
6425
Chandler Carruth5184de02010-12-12 08:51:33 +00006426 case OO_Amp: // '&' is either unary or binary
6427 if (NumArgs == 1)
6428 // C++ [over.match.oper]p3:
6429 // -- For the operator ',', the unary operator '&', or the
6430 // operator '->', the built-in candidates set is empty.
6431 break;
6432
6433 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6434 break;
6435
6436 case OO_Tilde:
6437 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6438 break;
6439
Douglas Gregora11693b2008-11-12 17:17:38 +00006440 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006441 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006442 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006443
6444 case OO_PlusEqual:
6445 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006446 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006447 // Fall through.
6448
6449 case OO_StarEqual:
6450 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006451 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006452 break;
6453
6454 case OO_PercentEqual:
6455 case OO_LessLessEqual:
6456 case OO_GreaterGreaterEqual:
6457 case OO_AmpEqual:
6458 case OO_CaretEqual:
6459 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006460 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006461 break;
6462
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006463 case OO_Exclaim:
6464 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006465 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006466
Douglas Gregora11693b2008-11-12 17:17:38 +00006467 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006468 case OO_PipePipe:
6469 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006470 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006471
6472 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006473 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006474 break;
6475
6476 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006477 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006478 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006479
6480 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006481 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006482 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6483 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006484 }
6485}
6486
Douglas Gregore254f902009-02-04 00:32:51 +00006487/// \brief Add function candidates found via argument-dependent lookup
6488/// to the set of overloading candidates.
6489///
6490/// This routine performs argument-dependent name lookup based on the
6491/// given function name (which may also be an operator name) and adds
6492/// all of the overload candidates found by ADL to the overload
6493/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006494void
Douglas Gregore254f902009-02-04 00:32:51 +00006495Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006496 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006497 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006498 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006499 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006500 bool PartialOverloading,
6501 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006502 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006503
John McCall91f61fc2010-01-26 06:04:06 +00006504 // FIXME: This approach for uniquing ADL results (and removing
6505 // redundant candidates from the set) relies on pointer-equality,
6506 // which means we need to key off the canonical decl. However,
6507 // always going back to the canonical decl might not get us the
6508 // right set of default arguments. What default arguments are
6509 // we supposed to consider on ADL candidates, anyway?
6510
Douglas Gregorcabea402009-09-22 15:41:20 +00006511 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006512 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6513 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006514
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006515 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006516 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6517 CandEnd = CandidateSet.end();
6518 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006519 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006520 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006521 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006522 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006523 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006524
6525 // For each of the ADL candidates we found, add it to the overload
6526 // set.
John McCall8fe68082010-01-26 07:16:45 +00006527 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006528 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006529 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006530 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006531 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006532
John McCalla0296f72010-03-19 07:35:19 +00006533 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006534 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006535 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006536 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006537 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006538 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006539 }
Douglas Gregore254f902009-02-04 00:32:51 +00006540}
6541
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006542/// isBetterOverloadCandidate - Determines whether the first overload
6543/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006544bool
John McCall5c32be02010-08-24 20:38:10 +00006545isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006546 const OverloadCandidate &Cand1,
6547 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006548 SourceLocation Loc,
6549 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006550 // Define viable functions to be better candidates than non-viable
6551 // functions.
6552 if (!Cand2.Viable)
6553 return Cand1.Viable;
6554 else if (!Cand1.Viable)
6555 return false;
6556
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006557 // C++ [over.match.best]p1:
6558 //
6559 // -- if F is a static member function, ICS1(F) is defined such
6560 // that ICS1(F) is neither better nor worse than ICS1(G) for
6561 // any function G, and, symmetrically, ICS1(G) is neither
6562 // better nor worse than ICS1(F).
6563 unsigned StartArg = 0;
6564 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6565 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006566
Douglas Gregord3cb3562009-07-07 23:38:56 +00006567 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006568 // A viable function F1 is defined to be a better function than another
6569 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006570 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006571 unsigned NumArgs = Cand1.Conversions.size();
6572 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6573 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006574 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006575 switch (CompareImplicitConversionSequences(S,
6576 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006577 Cand2.Conversions[ArgIdx])) {
6578 case ImplicitConversionSequence::Better:
6579 // Cand1 has a better conversion sequence.
6580 HasBetterConversion = true;
6581 break;
6582
6583 case ImplicitConversionSequence::Worse:
6584 // Cand1 can't be better than Cand2.
6585 return false;
6586
6587 case ImplicitConversionSequence::Indistinguishable:
6588 // Do nothing.
6589 break;
6590 }
6591 }
6592
Mike Stump11289f42009-09-09 15:08:12 +00006593 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006594 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006595 if (HasBetterConversion)
6596 return true;
6597
Mike Stump11289f42009-09-09 15:08:12 +00006598 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006599 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006600 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006601 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6602 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006603
6604 // -- F1 and F2 are function template specializations, and the function
6605 // template for F1 is more specialized than the template for F2
6606 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006607 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006608 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006609 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006610 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006611 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6612 Cand2.Function->getPrimaryTemplate(),
6613 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006614 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006615 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006616 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006617 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006618 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006619
Douglas Gregora1f013e2008-11-07 22:36:19 +00006620 // -- the context is an initialization by user-defined conversion
6621 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6622 // from the return type of F1 to the destination type (i.e.,
6623 // the type of the entity being initialized) is a better
6624 // conversion sequence than the standard conversion sequence
6625 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006626 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006627 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006628 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006629 switch (CompareStandardConversionSequences(S,
6630 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006631 Cand2.FinalConversion)) {
6632 case ImplicitConversionSequence::Better:
6633 // Cand1 has a better conversion sequence.
6634 return true;
6635
6636 case ImplicitConversionSequence::Worse:
6637 // Cand1 can't be better than Cand2.
6638 return false;
6639
6640 case ImplicitConversionSequence::Indistinguishable:
6641 // Do nothing
6642 break;
6643 }
6644 }
6645
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006646 return false;
6647}
6648
Mike Stump11289f42009-09-09 15:08:12 +00006649/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006650/// within an overload candidate set.
6651///
6652/// \param CandidateSet the set of candidate functions.
6653///
6654/// \param Loc the location of the function name (or operator symbol) for
6655/// which overload resolution occurs.
6656///
Mike Stump11289f42009-09-09 15:08:12 +00006657/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006658/// function, Best points to the candidate function found.
6659///
6660/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006661OverloadingResult
6662OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006663 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00006664 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006665 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006666 Best = end();
6667 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6668 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006669 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006670 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006671 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006672 }
6673
6674 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006675 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006676 return OR_No_Viable_Function;
6677
6678 // Make sure that this function is better than every other viable
6679 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006680 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006681 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006682 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006683 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006684 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006685 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006686 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006687 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006688 }
Mike Stump11289f42009-09-09 15:08:12 +00006689
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006690 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006691 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00006692 (Best->Function->isDeleted() ||
6693 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006694 return OR_Deleted;
6695
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006696 return OR_Success;
6697}
6698
John McCall53262c92010-01-12 02:15:36 +00006699namespace {
6700
6701enum OverloadCandidateKind {
6702 oc_function,
6703 oc_method,
6704 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006705 oc_function_template,
6706 oc_method_template,
6707 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006708 oc_implicit_default_constructor,
6709 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006710 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006711 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006712 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00006713 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006714};
6715
John McCalle1ac8d12010-01-13 00:25:19 +00006716OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6717 FunctionDecl *Fn,
6718 std::string &Description) {
6719 bool isTemplate = false;
6720
6721 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6722 isTemplate = true;
6723 Description = S.getTemplateArgumentBindingsText(
6724 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6725 }
John McCallfd0b2f82010-01-06 09:43:14 +00006726
6727 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006728 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006729 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006730
Sebastian Redl08905022011-02-05 19:23:19 +00006731 if (Ctor->getInheritedConstructor())
6732 return oc_implicit_inherited_constructor;
6733
Alexis Hunt119c10e2011-05-25 23:16:36 +00006734 if (Ctor->isDefaultConstructor())
6735 return oc_implicit_default_constructor;
6736
6737 if (Ctor->isMoveConstructor())
6738 return oc_implicit_move_constructor;
6739
6740 assert(Ctor->isCopyConstructor() &&
6741 "unexpected sort of implicit constructor");
6742 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006743 }
6744
6745 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6746 // This actually gets spelled 'candidate function' for now, but
6747 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006748 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006749 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006750
Alexis Hunt119c10e2011-05-25 23:16:36 +00006751 if (Meth->isMoveAssignmentOperator())
6752 return oc_implicit_move_assignment;
6753
Douglas Gregorec3bec02010-09-27 22:37:28 +00006754 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006755 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006756 return oc_implicit_copy_assignment;
6757 }
6758
John McCalle1ac8d12010-01-13 00:25:19 +00006759 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006760}
6761
Sebastian Redl08905022011-02-05 19:23:19 +00006762void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6763 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6764 if (!Ctor) return;
6765
6766 Ctor = Ctor->getInheritedConstructor();
6767 if (!Ctor) return;
6768
6769 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6770}
6771
John McCall53262c92010-01-12 02:15:36 +00006772} // end anonymous namespace
6773
6774// Notes the location of an overload candidate.
6775void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006776 std::string FnDesc;
6777 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6778 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6779 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00006780 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00006781}
6782
Douglas Gregorb491ed32011-02-19 21:32:49 +00006783//Notes the location of all overload candidates designated through
6784// OverloadedExpr
6785void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6786 assert(OverloadedExpr->getType() == Context.OverloadTy);
6787
6788 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6789 OverloadExpr *OvlExpr = Ovl.Expression;
6790
6791 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6792 IEnd = OvlExpr->decls_end();
6793 I != IEnd; ++I) {
6794 if (FunctionTemplateDecl *FunTmpl =
6795 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6796 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6797 } else if (FunctionDecl *Fun
6798 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6799 NoteOverloadCandidate(Fun);
6800 }
6801 }
6802}
6803
John McCall0d1da222010-01-12 00:44:57 +00006804/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6805/// "lead" diagnostic; it will be given two arguments, the source and
6806/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006807void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6808 Sema &S,
6809 SourceLocation CaretLoc,
6810 const PartialDiagnostic &PDiag) const {
6811 S.Diag(CaretLoc, PDiag)
6812 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006813 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006814 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6815 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006816 }
John McCall12f97bc2010-01-08 04:41:39 +00006817}
6818
John McCall0d1da222010-01-12 00:44:57 +00006819namespace {
6820
John McCall6a61b522010-01-13 09:16:55 +00006821void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6822 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6823 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006824 assert(Cand->Function && "for now, candidate must be a function");
6825 FunctionDecl *Fn = Cand->Function;
6826
6827 // There's a conversion slot for the object argument if this is a
6828 // non-constructor method. Note that 'I' corresponds the
6829 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006830 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006831 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006832 if (I == 0)
6833 isObjectArgument = true;
6834 else
6835 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006836 }
6837
John McCalle1ac8d12010-01-13 00:25:19 +00006838 std::string FnDesc;
6839 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6840
John McCall6a61b522010-01-13 09:16:55 +00006841 Expr *FromExpr = Conv.Bad.FromExpr;
6842 QualType FromTy = Conv.Bad.getFromType();
6843 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006844
John McCallfb7ad0f2010-02-02 02:42:52 +00006845 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006846 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006847 Expr *E = FromExpr->IgnoreParens();
6848 if (isa<UnaryOperator>(E))
6849 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006850 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006851
6852 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6853 << (unsigned) FnKind << FnDesc
6854 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6855 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006856 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00006857 return;
6858 }
6859
John McCall6d174642010-01-23 08:10:49 +00006860 // Do some hand-waving analysis to see if the non-viability is due
6861 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006862 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6863 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6864 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6865 CToTy = RT->getPointeeType();
6866 else {
6867 // TODO: detect and diagnose the full richness of const mismatches.
6868 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6869 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6870 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6871 }
6872
6873 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6874 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6875 // It is dumb that we have to do this here.
6876 while (isa<ArrayType>(CFromTy))
6877 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6878 while (isa<ArrayType>(CToTy))
6879 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6880
6881 Qualifiers FromQs = CFromTy.getQualifiers();
6882 Qualifiers ToQs = CToTy.getQualifiers();
6883
6884 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6885 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6886 << (unsigned) FnKind << FnDesc
6887 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6888 << FromTy
6889 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6890 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006891 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006892 return;
6893 }
6894
John McCall31168b02011-06-15 23:02:42 +00006895 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00006896 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00006897 << (unsigned) FnKind << FnDesc
6898 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6899 << FromTy
6900 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
6901 << (unsigned) isObjectArgument << I+1;
6902 MaybeEmitInheritedConstructorNote(S, Fn);
6903 return;
6904 }
6905
Douglas Gregoraec25842011-04-26 23:16:46 +00006906 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
6907 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
6908 << (unsigned) FnKind << FnDesc
6909 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6910 << FromTy
6911 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
6912 << (unsigned) isObjectArgument << I+1;
6913 MaybeEmitInheritedConstructorNote(S, Fn);
6914 return;
6915 }
6916
John McCall47000992010-01-14 03:28:57 +00006917 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6918 assert(CVR && "unexpected qualifiers mismatch");
6919
6920 if (isObjectArgument) {
6921 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6922 << (unsigned) FnKind << FnDesc
6923 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6924 << FromTy << (CVR - 1);
6925 } else {
6926 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6927 << (unsigned) FnKind << FnDesc
6928 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6929 << FromTy << (CVR - 1) << I+1;
6930 }
Sebastian Redl08905022011-02-05 19:23:19 +00006931 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006932 return;
6933 }
6934
Sebastian Redla72462c2011-09-24 17:48:32 +00006935 // Special diagnostic for failure to convert an initializer list, since
6936 // telling the user that it has type void is not useful.
6937 if (FromExpr && isa<InitListExpr>(FromExpr)) {
6938 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
6939 << (unsigned) FnKind << FnDesc
6940 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6941 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6942 MaybeEmitInheritedConstructorNote(S, Fn);
6943 return;
6944 }
6945
John McCall6d174642010-01-23 08:10:49 +00006946 // Diagnose references or pointers to incomplete types differently,
6947 // since it's far from impossible that the incompleteness triggered
6948 // the failure.
6949 QualType TempFromTy = FromTy.getNonReferenceType();
6950 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6951 TempFromTy = PTy->getPointeeType();
6952 if (TempFromTy->isIncompleteType()) {
6953 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6954 << (unsigned) FnKind << FnDesc
6955 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6956 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006957 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00006958 return;
6959 }
6960
Douglas Gregor56f2e342010-06-30 23:01:39 +00006961 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006962 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006963 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6964 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6965 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6966 FromPtrTy->getPointeeType()) &&
6967 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6968 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006969 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00006970 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006971 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006972 }
6973 } else if (const ObjCObjectPointerType *FromPtrTy
6974 = FromTy->getAs<ObjCObjectPointerType>()) {
6975 if (const ObjCObjectPointerType *ToPtrTy
6976 = ToTy->getAs<ObjCObjectPointerType>())
6977 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6978 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6979 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6980 FromPtrTy->getPointeeType()) &&
6981 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006982 BaseToDerivedConversion = 2;
6983 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6984 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6985 !FromTy->isIncompleteType() &&
6986 !ToRefTy->getPointeeType()->isIncompleteType() &&
6987 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6988 BaseToDerivedConversion = 3;
6989 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006990
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006991 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006992 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006993 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006994 << (unsigned) FnKind << FnDesc
6995 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006996 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006997 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006998 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00006999 return;
7000 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007001
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007002 if (isa<ObjCObjectPointerType>(CFromTy) &&
7003 isa<PointerType>(CToTy)) {
7004 Qualifiers FromQs = CFromTy.getQualifiers();
7005 Qualifiers ToQs = CToTy.getQualifiers();
7006 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7007 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7008 << (unsigned) FnKind << FnDesc
7009 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7010 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7011 MaybeEmitInheritedConstructorNote(S, Fn);
7012 return;
7013 }
7014 }
7015
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007016 // Emit the generic diagnostic and, optionally, add the hints to it.
7017 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7018 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007019 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007020 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7021 << (unsigned) (Cand->Fix.Kind);
7022
7023 // If we can fix the conversion, suggest the FixIts.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007024 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007025 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7026 HI != HE; ++HI)
7027 FDiag << *HI;
7028 S.Diag(Fn->getLocation(), FDiag);
7029
Sebastian Redl08905022011-02-05 19:23:19 +00007030 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007031}
7032
7033void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7034 unsigned NumFormalArgs) {
7035 // TODO: treat calls to a missing default constructor as a special case
7036
7037 FunctionDecl *Fn = Cand->Function;
7038 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7039
7040 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007041
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00007042 // With invalid overloaded operators, it's possible that we think we
7043 // have an arity mismatch when it fact it looks like we have the
7044 // right number of arguments, because only overloaded operators have
7045 // the weird behavior of overloading member and non-member functions.
7046 // Just don't report anything.
7047 if (Fn->isInvalidDecl() &&
7048 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7049 return;
7050
John McCall6a61b522010-01-13 09:16:55 +00007051 // at least / at most / exactly
7052 unsigned mode, modeCount;
7053 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007054 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7055 (Cand->FailureKind == ovl_fail_bad_deduction &&
7056 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007057 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00007058 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00007059 mode = 0; // "at least"
7060 else
7061 mode = 2; // "exactly"
7062 modeCount = MinParams;
7063 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007064 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7065 (Cand->FailureKind == ovl_fail_bad_deduction &&
7066 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00007067 if (MinParams != FnTy->getNumArgs())
7068 mode = 1; // "at most"
7069 else
7070 mode = 2; // "exactly"
7071 modeCount = FnTy->getNumArgs();
7072 }
7073
7074 std::string Description;
7075 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7076
7077 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007078 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00007079 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00007080 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007081}
7082
John McCall8b9ed552010-02-01 18:53:26 +00007083/// Diagnose a failed template-argument deduction.
7084void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7085 Expr **Args, unsigned NumArgs) {
7086 FunctionDecl *Fn = Cand->Function; // pattern
7087
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007088 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007089 NamedDecl *ParamD;
7090 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7091 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7092 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007093 switch (Cand->DeductionFailure.Result) {
7094 case Sema::TDK_Success:
7095 llvm_unreachable("TDK_success while diagnosing bad deduction");
7096
7097 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007098 assert(ParamD && "no parameter found for incomplete deduction result");
7099 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7100 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007101 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007102 return;
7103 }
7104
John McCall42d7d192010-08-05 09:05:08 +00007105 case Sema::TDK_Underqualified: {
7106 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7107 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7108
7109 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7110
7111 // Param will have been canonicalized, but it should just be a
7112 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007113 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007114 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007115 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007116 assert(S.Context.hasSameType(Param, NonCanonParam));
7117
7118 // Arg has also been canonicalized, but there's nothing we can do
7119 // about that. It also doesn't matter as much, because it won't
7120 // have any template parameters in it (because deduction isn't
7121 // done on dependent types).
7122 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7123
7124 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7125 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007126 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007127 return;
7128 }
7129
7130 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007131 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007132 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007133 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007134 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007135 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007136 which = 1;
7137 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007138 which = 2;
7139 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007140
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007141 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007142 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007143 << *Cand->DeductionFailure.getFirstArg()
7144 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007145 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007146 return;
7147 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007148
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007149 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007150 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007151 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007152 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007153 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7154 << ParamD->getDeclName();
7155 else {
7156 int index = 0;
7157 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7158 index = TTP->getIndex();
7159 else if (NonTypeTemplateParmDecl *NTTP
7160 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7161 index = NTTP->getIndex();
7162 else
7163 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007164 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007165 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7166 << (index + 1);
7167 }
Sebastian Redl08905022011-02-05 19:23:19 +00007168 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007169 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007170
Douglas Gregor02eb4832010-05-08 18:13:28 +00007171 case Sema::TDK_TooManyArguments:
7172 case Sema::TDK_TooFewArguments:
7173 DiagnoseArityMismatch(S, Cand, NumArgs);
7174 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007175
7176 case Sema::TDK_InstantiationDepth:
7177 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007178 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007179 return;
7180
7181 case Sema::TDK_SubstitutionFailure: {
7182 std::string ArgString;
7183 if (TemplateArgumentList *Args
7184 = Cand->DeductionFailure.getTemplateArgumentList())
7185 ArgString = S.getTemplateArgumentBindingsText(
7186 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7187 *Args);
7188 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7189 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007190 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007191 return;
7192 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007193
John McCall8b9ed552010-02-01 18:53:26 +00007194 // TODO: diagnose these individually, then kill off
7195 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007196 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007197 case Sema::TDK_FailedOverloadResolution:
7198 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007199 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007200 return;
7201 }
7202}
7203
7204/// Generates a 'note' diagnostic for an overload candidate. We've
7205/// already generated a primary error at the call site.
7206///
7207/// It really does need to be a single diagnostic with its caret
7208/// pointed at the candidate declaration. Yes, this creates some
7209/// major challenges of technical writing. Yes, this makes pointing
7210/// out problems with specific arguments quite awkward. It's still
7211/// better than generating twenty screens of text for every failed
7212/// overload.
7213///
7214/// It would be great to be able to express per-candidate problems
7215/// more richly for those diagnostic clients that cared, but we'd
7216/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007217void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7218 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007219 FunctionDecl *Fn = Cand->Function;
7220
John McCall12f97bc2010-01-08 04:41:39 +00007221 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007222 if (Cand->Viable && (Fn->isDeleted() ||
7223 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007224 std::string FnDesc;
7225 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007226
7227 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007228 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007229 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007230 return;
John McCall12f97bc2010-01-08 04:41:39 +00007231 }
7232
John McCalle1ac8d12010-01-13 00:25:19 +00007233 // We don't really have anything else to say about viable candidates.
7234 if (Cand->Viable) {
7235 S.NoteOverloadCandidate(Fn);
7236 return;
7237 }
John McCall0d1da222010-01-12 00:44:57 +00007238
John McCall6a61b522010-01-13 09:16:55 +00007239 switch (Cand->FailureKind) {
7240 case ovl_fail_too_many_arguments:
7241 case ovl_fail_too_few_arguments:
7242 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007243
John McCall6a61b522010-01-13 09:16:55 +00007244 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007245 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7246
John McCallfe796dd2010-01-23 05:17:32 +00007247 case ovl_fail_trivial_conversion:
7248 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007249 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007250 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007251
John McCall65eb8792010-02-25 01:37:24 +00007252 case ovl_fail_bad_conversion: {
7253 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7254 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007255 if (Cand->Conversions[I].isBad())
7256 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007257
John McCall6a61b522010-01-13 09:16:55 +00007258 // FIXME: this currently happens when we're called from SemaInit
7259 // when user-conversion overload fails. Figure out how to handle
7260 // those conditions and diagnose them well.
7261 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007262 }
John McCall65eb8792010-02-25 01:37:24 +00007263 }
John McCalld3224162010-01-08 00:58:21 +00007264}
7265
7266void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7267 // Desugar the type of the surrogate down to a function type,
7268 // retaining as many typedefs as possible while still showing
7269 // the function type (and, therefore, its parameter types).
7270 QualType FnType = Cand->Surrogate->getConversionType();
7271 bool isLValueReference = false;
7272 bool isRValueReference = false;
7273 bool isPointer = false;
7274 if (const LValueReferenceType *FnTypeRef =
7275 FnType->getAs<LValueReferenceType>()) {
7276 FnType = FnTypeRef->getPointeeType();
7277 isLValueReference = true;
7278 } else if (const RValueReferenceType *FnTypeRef =
7279 FnType->getAs<RValueReferenceType>()) {
7280 FnType = FnTypeRef->getPointeeType();
7281 isRValueReference = true;
7282 }
7283 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7284 FnType = FnTypePtr->getPointeeType();
7285 isPointer = true;
7286 }
7287 // Desugar down to a function type.
7288 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7289 // Reconstruct the pointer/reference as appropriate.
7290 if (isPointer) FnType = S.Context.getPointerType(FnType);
7291 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7292 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7293
7294 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7295 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007296 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007297}
7298
7299void NoteBuiltinOperatorCandidate(Sema &S,
7300 const char *Opc,
7301 SourceLocation OpLoc,
7302 OverloadCandidate *Cand) {
7303 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7304 std::string TypeStr("operator");
7305 TypeStr += Opc;
7306 TypeStr += "(";
7307 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7308 if (Cand->Conversions.size() == 1) {
7309 TypeStr += ")";
7310 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7311 } else {
7312 TypeStr += ", ";
7313 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7314 TypeStr += ")";
7315 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7316 }
7317}
7318
7319void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7320 OverloadCandidate *Cand) {
7321 unsigned NoOperands = Cand->Conversions.size();
7322 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7323 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007324 if (ICS.isBad()) break; // all meaningless after first invalid
7325 if (!ICS.isAmbiguous()) continue;
7326
John McCall5c32be02010-08-24 20:38:10 +00007327 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007328 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007329 }
7330}
7331
John McCall3712d9e2010-01-15 23:32:50 +00007332SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7333 if (Cand->Function)
7334 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007335 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007336 return Cand->Surrogate->getLocation();
7337 return SourceLocation();
7338}
7339
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007340static unsigned
7341RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00007342 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007343 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00007344 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007345
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007346 case Sema::TDK_Incomplete:
7347 return 1;
7348
7349 case Sema::TDK_Underqualified:
7350 case Sema::TDK_Inconsistent:
7351 return 2;
7352
7353 case Sema::TDK_SubstitutionFailure:
7354 case Sema::TDK_NonDeducedMismatch:
7355 return 3;
7356
7357 case Sema::TDK_InstantiationDepth:
7358 case Sema::TDK_FailedOverloadResolution:
7359 return 4;
7360
7361 case Sema::TDK_InvalidExplicitArguments:
7362 return 5;
7363
7364 case Sema::TDK_TooManyArguments:
7365 case Sema::TDK_TooFewArguments:
7366 return 6;
7367 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007368 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007369}
7370
John McCallad2587a2010-01-12 00:48:53 +00007371struct CompareOverloadCandidatesForDisplay {
7372 Sema &S;
7373 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007374
7375 bool operator()(const OverloadCandidate *L,
7376 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007377 // Fast-path this check.
7378 if (L == R) return false;
7379
John McCall12f97bc2010-01-08 04:41:39 +00007380 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007381 if (L->Viable) {
7382 if (!R->Viable) return true;
7383
7384 // TODO: introduce a tri-valued comparison for overload
7385 // candidates. Would be more worthwhile if we had a sort
7386 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007387 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7388 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007389 } else if (R->Viable)
7390 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007391
John McCall3712d9e2010-01-15 23:32:50 +00007392 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007393
John McCall3712d9e2010-01-15 23:32:50 +00007394 // Criteria by which we can sort non-viable candidates:
7395 if (!L->Viable) {
7396 // 1. Arity mismatches come after other candidates.
7397 if (L->FailureKind == ovl_fail_too_many_arguments ||
7398 L->FailureKind == ovl_fail_too_few_arguments)
7399 return false;
7400 if (R->FailureKind == ovl_fail_too_many_arguments ||
7401 R->FailureKind == ovl_fail_too_few_arguments)
7402 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007403
John McCallfe796dd2010-01-23 05:17:32 +00007404 // 2. Bad conversions come first and are ordered by the number
7405 // of bad conversions and quality of good conversions.
7406 if (L->FailureKind == ovl_fail_bad_conversion) {
7407 if (R->FailureKind != ovl_fail_bad_conversion)
7408 return true;
7409
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007410 // The conversion that can be fixed with a smaller number of changes,
7411 // comes first.
7412 unsigned numLFixes = L->Fix.NumConversionsFixed;
7413 unsigned numRFixes = R->Fix.NumConversionsFixed;
7414 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7415 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007416 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007417 if (numLFixes < numRFixes)
7418 return true;
7419 else
7420 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007421 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007422
John McCallfe796dd2010-01-23 05:17:32 +00007423 // If there's any ordering between the defined conversions...
7424 // FIXME: this might not be transitive.
7425 assert(L->Conversions.size() == R->Conversions.size());
7426
7427 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007428 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7429 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007430 switch (CompareImplicitConversionSequences(S,
7431 L->Conversions[I],
7432 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007433 case ImplicitConversionSequence::Better:
7434 leftBetter++;
7435 break;
7436
7437 case ImplicitConversionSequence::Worse:
7438 leftBetter--;
7439 break;
7440
7441 case ImplicitConversionSequence::Indistinguishable:
7442 break;
7443 }
7444 }
7445 if (leftBetter > 0) return true;
7446 if (leftBetter < 0) return false;
7447
7448 } else if (R->FailureKind == ovl_fail_bad_conversion)
7449 return false;
7450
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007451 if (L->FailureKind == ovl_fail_bad_deduction) {
7452 if (R->FailureKind != ovl_fail_bad_deduction)
7453 return true;
7454
7455 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7456 return RankDeductionFailure(L->DeductionFailure)
7457 <= RankDeductionFailure(R->DeductionFailure);
7458 }
7459
John McCall3712d9e2010-01-15 23:32:50 +00007460 // TODO: others?
7461 }
7462
7463 // Sort everything else by location.
7464 SourceLocation LLoc = GetLocationForCandidate(L);
7465 SourceLocation RLoc = GetLocationForCandidate(R);
7466
7467 // Put candidates without locations (e.g. builtins) at the end.
7468 if (LLoc.isInvalid()) return false;
7469 if (RLoc.isInvalid()) return true;
7470
7471 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007472 }
7473};
7474
John McCallfe796dd2010-01-23 05:17:32 +00007475/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007476/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00007477void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7478 Expr **Args, unsigned NumArgs) {
7479 assert(!Cand->Viable);
7480
7481 // Don't do anything on failures other than bad conversion.
7482 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7483
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007484 // We only want the FixIts if all the arguments can be corrected.
7485 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00007486 // Use a implicit copy initialization to check conversion fixes.
7487 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007488
John McCallfe796dd2010-01-23 05:17:32 +00007489 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007490 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007491 unsigned ConvCount = Cand->Conversions.size();
7492 while (true) {
7493 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7494 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007495 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00007496 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00007497 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007498 }
John McCallfe796dd2010-01-23 05:17:32 +00007499 }
7500
7501 if (ConvIdx == ConvCount)
7502 return;
7503
John McCall65eb8792010-02-25 01:37:24 +00007504 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7505 "remaining conversion is initialized?");
7506
Douglas Gregoradc7a702010-04-16 17:45:54 +00007507 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007508 // operation somehow.
7509 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007510
7511 const FunctionProtoType* Proto;
7512 unsigned ArgIdx = ConvIdx;
7513
7514 if (Cand->IsSurrogate) {
7515 QualType ConvType
7516 = Cand->Surrogate->getConversionType().getNonReferenceType();
7517 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7518 ConvType = ConvPtrType->getPointeeType();
7519 Proto = ConvType->getAs<FunctionProtoType>();
7520 ArgIdx--;
7521 } else if (Cand->Function) {
7522 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7523 if (isa<CXXMethodDecl>(Cand->Function) &&
7524 !isa<CXXConstructorDecl>(Cand->Function))
7525 ArgIdx--;
7526 } else {
7527 // Builtin binary operator with a bad first conversion.
7528 assert(ConvCount <= 3);
7529 for (; ConvIdx != ConvCount; ++ConvIdx)
7530 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007531 = TryCopyInitialization(S, Args[ConvIdx],
7532 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007533 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007534 /*InOverloadResolution*/ true,
7535 /*AllowObjCWritebackConversion=*/
7536 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00007537 return;
7538 }
7539
7540 // Fill in the rest of the conversions.
7541 unsigned NumArgsInProto = Proto->getNumArgs();
7542 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007543 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00007544 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007545 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007546 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007547 /*InOverloadResolution=*/true,
7548 /*AllowObjCWritebackConversion=*/
7549 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007550 // Store the FixIt in the candidate if it exists.
7551 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00007552 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007553 }
John McCallfe796dd2010-01-23 05:17:32 +00007554 else
7555 Cand->Conversions[ConvIdx].setEllipsis();
7556 }
7557}
7558
John McCalld3224162010-01-08 00:58:21 +00007559} // end anonymous namespace
7560
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007561/// PrintOverloadCandidates - When overload resolution fails, prints
7562/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007563/// set.
John McCall5c32be02010-08-24 20:38:10 +00007564void OverloadCandidateSet::NoteCandidates(Sema &S,
7565 OverloadCandidateDisplayKind OCD,
7566 Expr **Args, unsigned NumArgs,
7567 const char *Opc,
7568 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007569 // Sort the candidates by viability and position. Sorting directly would
7570 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007571 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007572 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7573 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007574 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007575 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007576 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007577 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007578 if (Cand->Function || Cand->IsSurrogate)
7579 Cands.push_back(Cand);
7580 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7581 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007582 }
7583 }
7584
John McCallad2587a2010-01-12 00:48:53 +00007585 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007586 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007587
John McCall0d1da222010-01-12 00:44:57 +00007588 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007589
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007590 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00007591 const DiagnosticsEngine::OverloadsShown ShowOverloads =
7592 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007593 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007594 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7595 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007596
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007597 // Set an arbitrary limit on the number of candidate functions we'll spam
7598 // the user with. FIXME: This limit should depend on details of the
7599 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00007600 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007601 break;
7602 }
7603 ++CandsShown;
7604
John McCalld3224162010-01-08 00:58:21 +00007605 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007606 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007607 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007608 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007609 else {
7610 assert(Cand->Viable &&
7611 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007612 // Generally we only see ambiguities including viable builtin
7613 // operators if overload resolution got screwed up by an
7614 // ambiguous user-defined conversion.
7615 //
7616 // FIXME: It's quite possible for different conversions to see
7617 // different ambiguities, though.
7618 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007619 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007620 ReportedAmbiguousConversions = true;
7621 }
John McCalld3224162010-01-08 00:58:21 +00007622
John McCall0d1da222010-01-12 00:44:57 +00007623 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007624 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007625 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007626 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007627
7628 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007629 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007630}
7631
Douglas Gregorb491ed32011-02-19 21:32:49 +00007632// [PossiblyAFunctionType] --> [Return]
7633// NonFunctionType --> NonFunctionType
7634// R (A) --> R(A)
7635// R (*)(A) --> R (A)
7636// R (&)(A) --> R (A)
7637// R (S::*)(A) --> R (A)
7638QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7639 QualType Ret = PossiblyAFunctionType;
7640 if (const PointerType *ToTypePtr =
7641 PossiblyAFunctionType->getAs<PointerType>())
7642 Ret = ToTypePtr->getPointeeType();
7643 else if (const ReferenceType *ToTypeRef =
7644 PossiblyAFunctionType->getAs<ReferenceType>())
7645 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007646 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007647 PossiblyAFunctionType->getAs<MemberPointerType>())
7648 Ret = MemTypePtr->getPointeeType();
7649 Ret =
7650 Context.getCanonicalType(Ret).getUnqualifiedType();
7651 return Ret;
7652}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007653
Douglas Gregorb491ed32011-02-19 21:32:49 +00007654// A helper class to help with address of function resolution
7655// - allows us to avoid passing around all those ugly parameters
7656class AddressOfFunctionResolver
7657{
7658 Sema& S;
7659 Expr* SourceExpr;
7660 const QualType& TargetType;
7661 QualType TargetFunctionType; // Extracted function type from target type
7662
7663 bool Complain;
7664 //DeclAccessPair& ResultFunctionAccessPair;
7665 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007666
Douglas Gregorb491ed32011-02-19 21:32:49 +00007667 bool TargetTypeIsNonStaticMemberFunction;
7668 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007669
Douglas Gregorb491ed32011-02-19 21:32:49 +00007670 OverloadExpr::FindResult OvlExprInfo;
7671 OverloadExpr *OvlExpr;
7672 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007673 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007674
Douglas Gregorb491ed32011-02-19 21:32:49 +00007675public:
7676 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7677 const QualType& TargetType, bool Complain)
7678 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7679 Complain(Complain), Context(S.getASTContext()),
7680 TargetTypeIsNonStaticMemberFunction(
7681 !!TargetType->getAs<MemberPointerType>()),
7682 FoundNonTemplateFunction(false),
7683 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7684 OvlExpr(OvlExprInfo.Expression)
7685 {
7686 ExtractUnqualifiedFunctionTypeFromTargetType();
7687
7688 if (!TargetFunctionType->isFunctionType()) {
7689 if (OvlExpr->hasExplicitTemplateArgs()) {
7690 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00007691 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00007692 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00007693
7694 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7695 if (!Method->isStatic()) {
7696 // If the target type is a non-function type and the function
7697 // found is a non-static member function, pretend as if that was
7698 // the target, it's the only possible type to end up with.
7699 TargetTypeIsNonStaticMemberFunction = true;
7700
7701 // And skip adding the function if its not in the proper form.
7702 // We'll diagnose this due to an empty set of functions.
7703 if (!OvlExprInfo.HasFormOfMemberPointer)
7704 return;
7705 }
7706 }
7707
Douglas Gregorb491ed32011-02-19 21:32:49 +00007708 Matches.push_back(std::make_pair(dap,Fn));
7709 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007710 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007711 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007712 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007713
7714 if (OvlExpr->hasExplicitTemplateArgs())
7715 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007716
Douglas Gregorb491ed32011-02-19 21:32:49 +00007717 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7718 // C++ [over.over]p4:
7719 // If more than one function is selected, [...]
7720 if (Matches.size() > 1) {
7721 if (FoundNonTemplateFunction)
7722 EliminateAllTemplateMatches();
7723 else
7724 EliminateAllExceptMostSpecializedTemplate();
7725 }
7726 }
7727 }
7728
7729private:
7730 bool isTargetTypeAFunction() const {
7731 return TargetFunctionType->isFunctionType();
7732 }
7733
7734 // [ToType] [Return]
7735
7736 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7737 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7738 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7739 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7740 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7741 }
7742
7743 // return true if any matching specializations were found
7744 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7745 const DeclAccessPair& CurAccessFunPair) {
7746 if (CXXMethodDecl *Method
7747 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7748 // Skip non-static function templates when converting to pointer, and
7749 // static when converting to member pointer.
7750 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7751 return false;
7752 }
7753 else if (TargetTypeIsNonStaticMemberFunction)
7754 return false;
7755
7756 // C++ [over.over]p2:
7757 // If the name is a function template, template argument deduction is
7758 // done (14.8.2.2), and if the argument deduction succeeds, the
7759 // resulting template argument list is used to generate a single
7760 // function template specialization, which is added to the set of
7761 // overloaded functions considered.
7762 FunctionDecl *Specialization = 0;
7763 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7764 if (Sema::TemplateDeductionResult Result
7765 = S.DeduceTemplateArguments(FunctionTemplate,
7766 &OvlExplicitTemplateArgs,
7767 TargetFunctionType, Specialization,
7768 Info)) {
7769 // FIXME: make a note of the failed deduction for diagnostics.
7770 (void)Result;
7771 return false;
7772 }
7773
7774 // Template argument deduction ensures that we have an exact match.
7775 // This function template specicalization works.
7776 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7777 assert(TargetFunctionType
7778 == Context.getCanonicalType(Specialization->getType()));
7779 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7780 return true;
7781 }
7782
7783 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7784 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007785 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007786 // Skip non-static functions when converting to pointer, and static
7787 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007788 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7789 return false;
7790 }
7791 else if (TargetTypeIsNonStaticMemberFunction)
7792 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007793
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007794 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007795 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007796 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7797 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00007798 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
7799 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007800 Matches.push_back(std::make_pair(CurAccessFunPair,
7801 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007802 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007803 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007804 }
Mike Stump11289f42009-09-09 15:08:12 +00007805 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007806
7807 return false;
7808 }
7809
7810 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7811 bool Ret = false;
7812
7813 // If the overload expression doesn't have the form of a pointer to
7814 // member, don't try to convert it to a pointer-to-member type.
7815 if (IsInvalidFormOfPointerToMemberFunction())
7816 return false;
7817
7818 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7819 E = OvlExpr->decls_end();
7820 I != E; ++I) {
7821 // Look through any using declarations to find the underlying function.
7822 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7823
7824 // C++ [over.over]p3:
7825 // Non-member functions and static member functions match
7826 // targets of type "pointer-to-function" or "reference-to-function."
7827 // Nonstatic member functions match targets of
7828 // type "pointer-to-member-function."
7829 // Note that according to DR 247, the containing class does not matter.
7830 if (FunctionTemplateDecl *FunctionTemplate
7831 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7832 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7833 Ret = true;
7834 }
7835 // If we have explicit template arguments supplied, skip non-templates.
7836 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7837 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7838 Ret = true;
7839 }
7840 assert(Ret || Matches.empty());
7841 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007842 }
7843
Douglas Gregorb491ed32011-02-19 21:32:49 +00007844 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00007845 // [...] and any given function template specialization F1 is
7846 // eliminated if the set contains a second function template
7847 // specialization whose function template is more specialized
7848 // than the function template of F1 according to the partial
7849 // ordering rules of 14.5.5.2.
7850
7851 // The algorithm specified above is quadratic. We instead use a
7852 // two-pass algorithm (similar to the one used to identify the
7853 // best viable function in an overload set) that identifies the
7854 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007855
7856 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7857 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7858 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007859
John McCall58cc69d2010-01-27 01:50:18 +00007860 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007861 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7862 TPOC_Other, 0, SourceExpr->getLocStart(),
7863 S.PDiag(),
7864 S.PDiag(diag::err_addr_ovl_ambiguous)
7865 << Matches[0].second->getDeclName(),
7866 S.PDiag(diag::note_ovl_candidate)
7867 << (unsigned) oc_function_template,
7868 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007869
Douglas Gregorb491ed32011-02-19 21:32:49 +00007870 if (Result != MatchesCopy.end()) {
7871 // Make it the first and only element
7872 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7873 Matches[0].second = cast<FunctionDecl>(*Result);
7874 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00007875 }
7876 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007877
Douglas Gregorb491ed32011-02-19 21:32:49 +00007878 void EliminateAllTemplateMatches() {
7879 // [...] any function template specializations in the set are
7880 // eliminated if the set also contains a non-template function, [...]
7881 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7882 if (Matches[I].second->getPrimaryTemplate() == 0)
7883 ++I;
7884 else {
7885 Matches[I] = Matches[--N];
7886 Matches.set_size(N);
7887 }
7888 }
7889 }
7890
7891public:
7892 void ComplainNoMatchesFound() const {
7893 assert(Matches.empty());
7894 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7895 << OvlExpr->getName() << TargetFunctionType
7896 << OvlExpr->getSourceRange();
7897 S.NoteAllOverloadCandidates(OvlExpr);
7898 }
7899
7900 bool IsInvalidFormOfPointerToMemberFunction() const {
7901 return TargetTypeIsNonStaticMemberFunction &&
7902 !OvlExprInfo.HasFormOfMemberPointer;
7903 }
7904
7905 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7906 // TODO: Should we condition this on whether any functions might
7907 // have matched, or is it more appropriate to do that in callers?
7908 // TODO: a fixit wouldn't hurt.
7909 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7910 << TargetType << OvlExpr->getSourceRange();
7911 }
7912
7913 void ComplainOfInvalidConversion() const {
7914 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7915 << OvlExpr->getName() << TargetType;
7916 }
7917
7918 void ComplainMultipleMatchesFound() const {
7919 assert(Matches.size() > 1);
7920 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7921 << OvlExpr->getName()
7922 << OvlExpr->getSourceRange();
7923 S.NoteAllOverloadCandidates(OvlExpr);
7924 }
7925
7926 int getNumMatches() const { return Matches.size(); }
7927
7928 FunctionDecl* getMatchingFunctionDecl() const {
7929 if (Matches.size() != 1) return 0;
7930 return Matches[0].second;
7931 }
7932
7933 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7934 if (Matches.size() != 1) return 0;
7935 return &Matches[0].first;
7936 }
7937};
7938
7939/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7940/// an overloaded function (C++ [over.over]), where @p From is an
7941/// expression with overloaded function type and @p ToType is the type
7942/// we're trying to resolve to. For example:
7943///
7944/// @code
7945/// int f(double);
7946/// int f(int);
7947///
7948/// int (*pfd)(double) = f; // selects f(double)
7949/// @endcode
7950///
7951/// This routine returns the resulting FunctionDecl if it could be
7952/// resolved, and NULL otherwise. When @p Complain is true, this
7953/// routine will emit diagnostics if there is an error.
7954FunctionDecl *
7955Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7956 bool Complain,
7957 DeclAccessPair &FoundResult) {
7958
7959 assert(AddressOfExpr->getType() == Context.OverloadTy);
7960
7961 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7962 int NumMatches = Resolver.getNumMatches();
7963 FunctionDecl* Fn = 0;
7964 if ( NumMatches == 0 && Complain) {
7965 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7966 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7967 else
7968 Resolver.ComplainNoMatchesFound();
7969 }
7970 else if (NumMatches > 1 && Complain)
7971 Resolver.ComplainMultipleMatchesFound();
7972 else if (NumMatches == 1) {
7973 Fn = Resolver.getMatchingFunctionDecl();
7974 assert(Fn);
7975 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7976 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007977 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00007978 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007979 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007980
7981 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007982}
7983
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007984/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007985/// resolve that overloaded function expression down to a single function.
7986///
7987/// This routine can only resolve template-ids that refer to a single function
7988/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007989/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007990/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00007991FunctionDecl *
7992Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
7993 bool Complain,
7994 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007995 // C++ [over.over]p1:
7996 // [...] [Note: any redundant set of parentheses surrounding the
7997 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007998 // C++ [over.over]p1:
7999 // [...] The overloaded function name can be preceded by the &
8000 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008001
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008002 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00008003 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008004 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00008005
8006 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00008007 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008008
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008009 // Look through all of the overloaded functions, searching for one
8010 // whose type matches exactly.
8011 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008012 for (UnresolvedSetIterator I = ovl->decls_begin(),
8013 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008014 // C++0x [temp.arg.explicit]p3:
8015 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008016 // where deduction is not done, if a template argument list is
8017 // specified and it, along with any default template arguments,
8018 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008019 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00008020 FunctionTemplateDecl *FunctionTemplate
8021 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008022
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008023 // C++ [over.over]p2:
8024 // If the name is a function template, template argument deduction is
8025 // done (14.8.2.2), and if the argument deduction succeeds, the
8026 // resulting template argument list is used to generate a single
8027 // function template specialization, which is added to the set of
8028 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008029 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008030 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008031 if (TemplateDeductionResult Result
8032 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8033 Specialization, Info)) {
8034 // FIXME: make a note of the failed deduction for diagnostics.
8035 (void)Result;
8036 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008037 }
8038
John McCall0009fcc2011-04-26 20:42:42 +00008039 assert(Specialization && "no specialization and no error?");
8040
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008041 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008042 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008043 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00008044 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8045 << ovl->getName();
8046 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008047 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008048 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00008049 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008050
John McCall0009fcc2011-04-26 20:42:42 +00008051 Matched = Specialization;
8052 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008053 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008054
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008055 return Matched;
8056}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008057
Douglas Gregor1beec452011-03-12 01:48:56 +00008058
8059
8060
8061// Resolve and fix an overloaded expression that
8062// can be resolved because it identifies a single function
8063// template specialization
8064// Last three arguments should only be supplied if Complain = true
8065ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
John McCall0009fcc2011-04-26 20:42:42 +00008066 Expr *SrcExpr, bool doFunctionPointerConverion, bool complain,
Douglas Gregor1beec452011-03-12 01:48:56 +00008067 const SourceRange& OpRangeForComplaining,
8068 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00008069 unsigned DiagIDForComplaining) {
8070 assert(SrcExpr->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00008071
John McCall0009fcc2011-04-26 20:42:42 +00008072 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr);
Douglas Gregor1beec452011-03-12 01:48:56 +00008073
John McCall0009fcc2011-04-26 20:42:42 +00008074 DeclAccessPair found;
8075 ExprResult SingleFunctionExpression;
8076 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8077 ovl.Expression, /*complain*/ false, &found)) {
8078 if (DiagnoseUseOfDecl(fn, SrcExpr->getSourceRange().getBegin()))
8079 return ExprError();
8080
8081 // It is only correct to resolve to an instance method if we're
8082 // resolving a form that's permitted to be a pointer to member.
8083 // Otherwise we'll end up making a bound member expression, which
8084 // is illegal in all the contexts we resolve like this.
8085 if (!ovl.HasFormOfMemberPointer &&
8086 isa<CXXMethodDecl>(fn) &&
8087 cast<CXXMethodDecl>(fn)->isInstance()) {
8088 if (complain) {
8089 Diag(ovl.Expression->getExprLoc(),
8090 diag::err_invalid_use_of_bound_member_func)
8091 << ovl.Expression->getSourceRange();
8092 // TODO: I believe we only end up here if there's a mix of
8093 // static and non-static candidates (otherwise the expression
8094 // would have 'bound member' type, not 'overload' type).
8095 // Ideally we would note which candidate was chosen and why
8096 // the static candidates were rejected.
8097 }
8098
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008099 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00008100 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008101
John McCall0009fcc2011-04-26 20:42:42 +00008102 // Fix the expresion to refer to 'fn'.
8103 SingleFunctionExpression =
8104 Owned(FixOverloadedFunctionReference(SrcExpr, found, fn));
8105
8106 // If desired, do function-to-pointer decay.
8107 if (doFunctionPointerConverion)
8108 SingleFunctionExpression =
8109 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
8110 }
8111
8112 if (!SingleFunctionExpression.isUsable()) {
8113 if (complain) {
8114 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8115 << ovl.Expression->getName()
8116 << DestTypeForComplaining
8117 << OpRangeForComplaining
8118 << ovl.Expression->getQualifierLoc().getSourceRange();
8119 NoteAllOverloadCandidates(SrcExpr);
8120 }
8121 return ExprError();
8122 }
8123
8124 return SingleFunctionExpression;
Douglas Gregor1beec452011-03-12 01:48:56 +00008125}
8126
Douglas Gregorcabea402009-09-22 15:41:20 +00008127/// \brief Add a single candidate to the overload set.
8128static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00008129 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008130 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008131 Expr **Args, unsigned NumArgs,
8132 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008133 bool PartialOverloading,
8134 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00008135 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00008136 if (isa<UsingShadowDecl>(Callee))
8137 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8138
Douglas Gregorcabea402009-09-22 15:41:20 +00008139 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00008140 if (ExplicitTemplateArgs) {
8141 assert(!KnownValid && "Explicit template arguments?");
8142 return;
8143 }
John McCalla0296f72010-03-19 07:35:19 +00008144 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00008145 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008146 return;
John McCalld14a8642009-11-21 08:51:07 +00008147 }
8148
8149 if (FunctionTemplateDecl *FuncTemplate
8150 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00008151 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8152 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00008153 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00008154 return;
8155 }
8156
Richard Smith95ce4f62011-06-26 22:19:54 +00008157 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00008158}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008159
Douglas Gregorcabea402009-09-22 15:41:20 +00008160/// \brief Add the overload candidates named by callee and/or found by argument
8161/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00008162void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00008163 Expr **Args, unsigned NumArgs,
8164 OverloadCandidateSet &CandidateSet,
8165 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00008166
8167#ifndef NDEBUG
8168 // Verify that ArgumentDependentLookup is consistent with the rules
8169 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00008170 //
Douglas Gregorcabea402009-09-22 15:41:20 +00008171 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8172 // and let Y be the lookup set produced by argument dependent
8173 // lookup (defined as follows). If X contains
8174 //
8175 // -- a declaration of a class member, or
8176 //
8177 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00008178 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00008179 //
8180 // -- a declaration that is neither a function or a function
8181 // template
8182 //
8183 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00008184
John McCall57500772009-12-16 12:17:52 +00008185 if (ULE->requiresADL()) {
8186 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8187 E = ULE->decls_end(); I != E; ++I) {
8188 assert(!(*I)->getDeclContext()->isRecord());
8189 assert(isa<UsingShadowDecl>(*I) ||
8190 !(*I)->getDeclContext()->isFunctionOrMethod());
8191 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008192 }
8193 }
8194#endif
8195
John McCall57500772009-12-16 12:17:52 +00008196 // It would be nice to avoid this copy.
8197 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008198 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008199 if (ULE->hasExplicitTemplateArgs()) {
8200 ULE->copyTemplateArgumentsInto(TABuffer);
8201 ExplicitTemplateArgs = &TABuffer;
8202 }
8203
8204 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8205 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008206 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008207 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008208 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008209
John McCall57500772009-12-16 12:17:52 +00008210 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008211 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8212 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008213 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008214 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008215 PartialOverloading,
8216 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008217}
John McCalld681c392009-12-16 08:11:27 +00008218
Richard Smith998a5912011-06-05 22:42:48 +00008219/// Attempt to recover from an ill-formed use of a non-dependent name in a
8220/// template, where the non-dependent name was declared after the template
8221/// was defined. This is common in code written for a compilers which do not
8222/// correctly implement two-stage name lookup.
8223///
8224/// Returns true if a viable candidate was found and a diagnostic was issued.
8225static bool
8226DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8227 const CXXScopeSpec &SS, LookupResult &R,
8228 TemplateArgumentListInfo *ExplicitTemplateArgs,
8229 Expr **Args, unsigned NumArgs) {
8230 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8231 return false;
8232
8233 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8234 SemaRef.LookupQualifiedName(R, DC);
8235
8236 if (!R.empty()) {
8237 R.suppressDiagnostics();
8238
8239 if (isa<CXXRecordDecl>(DC)) {
8240 // Don't diagnose names we find in classes; we get much better
8241 // diagnostics for these from DiagnoseEmptyLookup.
8242 R.clear();
8243 return false;
8244 }
8245
8246 OverloadCandidateSet Candidates(FnLoc);
8247 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8248 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8249 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008250 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008251
8252 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008253 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008254 // No viable functions. Don't bother the user with notes for functions
8255 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008256 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008257 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008258 }
Richard Smith998a5912011-06-05 22:42:48 +00008259
8260 // Find the namespaces where ADL would have looked, and suggest
8261 // declaring the function there instead.
8262 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8263 Sema::AssociatedClassSet AssociatedClasses;
8264 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8265 AssociatedNamespaces,
8266 AssociatedClasses);
8267 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008268 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008269 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008270 for (Sema::AssociatedNamespaceSet::iterator
8271 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008272 end = AssociatedNamespaces.end(); it != end; ++it) {
8273 if (!Std->Encloses(*it))
8274 SuggestedNamespaces.insert(*it);
8275 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008276 } else {
8277 // Lacking the 'std::' namespace, use all of the associated namespaces.
8278 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008279 }
8280
8281 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8282 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008283 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008284 SemaRef.Diag(Best->Function->getLocation(),
8285 diag::note_not_found_by_two_phase_lookup)
8286 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008287 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008288 SemaRef.Diag(Best->Function->getLocation(),
8289 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008290 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008291 } else {
8292 // FIXME: It would be useful to list the associated namespaces here,
8293 // but the diagnostics infrastructure doesn't provide a way to produce
8294 // a localized representation of a list of items.
8295 SemaRef.Diag(Best->Function->getLocation(),
8296 diag::note_not_found_by_two_phase_lookup)
8297 << R.getLookupName() << 2;
8298 }
8299
8300 // Try to recover by calling this function.
8301 return true;
8302 }
8303
8304 R.clear();
8305 }
8306
8307 return false;
8308}
8309
8310/// Attempt to recover from ill-formed use of a non-dependent operator in a
8311/// template, where the non-dependent operator was declared after the template
8312/// was defined.
8313///
8314/// Returns true if a viable candidate was found and a diagnostic was issued.
8315static bool
8316DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8317 SourceLocation OpLoc,
8318 Expr **Args, unsigned NumArgs) {
8319 DeclarationName OpName =
8320 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8321 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8322 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8323 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8324}
8325
John McCalld681c392009-12-16 08:11:27 +00008326/// Attempts to recover from a call where no functions were found.
8327///
8328/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008329static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008330BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008331 UnresolvedLookupExpr *ULE,
8332 SourceLocation LParenLoc,
8333 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008334 SourceLocation RParenLoc,
8335 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008336
8337 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008338 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008339
John McCall57500772009-12-16 12:17:52 +00008340 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008341 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008342 if (ULE->hasExplicitTemplateArgs()) {
8343 ULE->copyTemplateArgumentsInto(TABuffer);
8344 ExplicitTemplateArgs = &TABuffer;
8345 }
8346
John McCalld681c392009-12-16 08:11:27 +00008347 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8348 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008349 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8350 ExplicitTemplateArgs, Args, NumArgs) &&
8351 (!EmptyLookup ||
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00008352 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00008353 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00008354 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008355
John McCall57500772009-12-16 12:17:52 +00008356 assert(!R.empty() && "lookup results empty despite recovery");
8357
8358 // Build an implicit member call if appropriate. Just drop the
8359 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008360 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008361 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008362 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8363 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008364 else if (ExplicitTemplateArgs)
8365 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8366 else
8367 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8368
8369 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008370 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008371
8372 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008373 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008374 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008375 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008376 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008377}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008378
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008379/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008380/// (which eventually refers to the declaration Func) and the call
8381/// arguments Args/NumArgs, attempt to resolve the function call down
8382/// to a specific function. If overload resolution succeeds, returns
8383/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008384/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008385/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008386ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008387Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008388 SourceLocation LParenLoc,
8389 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008390 SourceLocation RParenLoc,
8391 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008392#ifndef NDEBUG
8393 if (ULE->requiresADL()) {
8394 // To do ADL, we must have found an unqualified name.
8395 assert(!ULE->getQualifier() && "qualified name with ADL");
8396
8397 // We don't perform ADL for implicit declarations of builtins.
8398 // Verify that this was correctly set up.
8399 FunctionDecl *F;
8400 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8401 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8402 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00008403 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008404
John McCall57500772009-12-16 12:17:52 +00008405 // We don't perform ADL in C.
8406 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008407 } else
8408 assert(!ULE->isStdAssociatedNamespace() &&
8409 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008410#endif
8411
John McCallbc077cf2010-02-08 23:07:23 +00008412 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008413
John McCall57500772009-12-16 12:17:52 +00008414 // Add the functions denoted by the callee to the set of candidate
8415 // functions, including those from argument-dependent lookup.
8416 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008417
8418 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008419 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8420 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00008421 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008422 // In Microsoft mode, if we are inside a template class member function then
8423 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00008424 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008425 // classes.
8426 if (getLangOptions().MicrosoftExt && CurContext->isDependentContext() &&
8427 isa<CXXMethodDecl>(CurContext)) {
8428 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8429 Context.DependentTy, VK_RValue,
8430 RParenLoc);
8431 CE->setTypeDependent(true);
8432 return Owned(CE);
8433 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008434 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008435 RParenLoc, /*EmptyLookup=*/true);
Francois Pichetbcf64712011-09-07 00:14:57 +00008436 }
John McCalld681c392009-12-16 08:11:27 +00008437
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008438 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008439 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008440 case OR_Success: {
8441 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008442 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008443 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008444 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
8445 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008446 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008447 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8448 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008449 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008450
Richard Smith998a5912011-06-05 22:42:48 +00008451 case OR_No_Viable_Function: {
8452 // Try to recover by looking for viable functions which the user might
8453 // have meant to call.
8454 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8455 Args, NumArgs, RParenLoc,
8456 /*EmptyLookup=*/false);
8457 if (!Recovery.isInvalid())
8458 return Recovery;
8459
Chris Lattner45d9d602009-02-17 07:29:20 +00008460 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008461 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008462 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008463 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008464 break;
Richard Smith998a5912011-06-05 22:42:48 +00008465 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008466
8467 case OR_Ambiguous:
8468 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008469 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008470 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008471 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008472
8473 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008474 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008475 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8476 << Best->Function->isDeleted()
8477 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008478 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008479 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008480 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8481 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008482 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008483 }
8484
Douglas Gregorb412e172010-07-25 18:17:45 +00008485 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00008486 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008487}
8488
John McCall4c4c1df2010-01-26 03:27:55 +00008489static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00008490 return Functions.size() > 1 ||
8491 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8492}
8493
Douglas Gregor084d8552009-03-13 23:49:33 +00008494/// \brief Create a unary operation that may resolve to an overloaded
8495/// operator.
8496///
8497/// \param OpLoc The location of the operator itself (e.g., '*').
8498///
8499/// \param OpcIn The UnaryOperator::Opcode that describes this
8500/// operator.
8501///
8502/// \param Functions The set of non-member functions that will be
8503/// considered by overload resolution. The caller needs to build this
8504/// set based on the context using, e.g.,
8505/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8506/// set should not contain any member functions; those will be added
8507/// by CreateOverloadedUnaryOp().
8508///
8509/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00008510ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00008511Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8512 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00008513 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008514 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00008515
8516 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8517 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8518 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008519 // TODO: provide better source location info.
8520 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008521
John Wiegley01296292011-04-08 18:41:53 +00008522 if (Input->getObjectKind() == OK_ObjCProperty) {
8523 ExprResult Result = ConvertPropertyForRValue(Input);
8524 if (Result.isInvalid())
8525 return ExprError();
8526 Input = Result.take();
8527 }
John McCalle26a8722010-12-04 08:14:53 +00008528
Douglas Gregor084d8552009-03-13 23:49:33 +00008529 Expr *Args[2] = { Input, 0 };
8530 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00008531
Douglas Gregor084d8552009-03-13 23:49:33 +00008532 // For post-increment and post-decrement, add the implicit '0' as
8533 // the second argument, so that we know this is a post-increment or
8534 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00008535 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008536 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008537 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8538 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00008539 NumArgs = 2;
8540 }
8541
8542 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00008543 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00008544 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008545 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00008546 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008547 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00008548 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008549
John McCall58cc69d2010-01-27 01:50:18 +00008550 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00008551 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008552 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008553 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008554 /*ADL*/ true, IsOverloaded(Fns),
8555 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00008556 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008557 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00008558 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008559 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00008560 OpLoc));
8561 }
8562
8563 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008564 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008565
8566 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008567 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00008568
8569 // Add operator candidates that are member functions.
8570 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8571
John McCall4c4c1df2010-01-26 03:27:55 +00008572 // Add candidates from ADL.
8573 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00008574 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00008575 /*ExplicitTemplateArgs*/ 0,
8576 CandidateSet);
8577
Douglas Gregor084d8552009-03-13 23:49:33 +00008578 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008579 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00008580
8581 // Perform overload resolution.
8582 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008583 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008584 case OR_Success: {
8585 // We found a built-in operator or an overloaded operator.
8586 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00008587
Douglas Gregor084d8552009-03-13 23:49:33 +00008588 if (FnDecl) {
8589 // We matched an overloaded operator. Build a call to that
8590 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00008591
Chandler Carruth30141632011-02-25 19:41:05 +00008592 MarkDeclarationReferenced(OpLoc, FnDecl);
8593
Douglas Gregor084d8552009-03-13 23:49:33 +00008594 // Convert the arguments.
8595 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00008596 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008597
John Wiegley01296292011-04-08 18:41:53 +00008598 ExprResult InputRes =
8599 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8600 Best->FoundDecl, Method);
8601 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008602 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008603 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008604 } else {
8605 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008606 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00008607 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008608 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00008609 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008610 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00008611 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00008612 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008613 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008614 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008615 }
8616
John McCall4fa0d5f2010-05-06 18:15:07 +00008617 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8618
John McCall7decc9e2010-11-18 06:31:45 +00008619 // Determine the result type.
8620 QualType ResultTy = FnDecl->getResultType();
8621 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8622 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00008623
Douglas Gregor084d8552009-03-13 23:49:33 +00008624 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008625 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl);
8626 if (FnExpr.isInvalid())
8627 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00008628
Eli Friedman030eee42009-11-18 03:58:17 +00008629 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00008630 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008631 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008632 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00008633
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008634 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00008635 FnDecl))
8636 return ExprError();
8637
John McCallb268a282010-08-23 23:25:46 +00008638 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00008639 } else {
8640 // We matched a built-in operator. Convert the arguments, then
8641 // break out so that we will build the appropriate built-in
8642 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008643 ExprResult InputRes =
8644 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8645 Best->Conversions[0], AA_Passing);
8646 if (InputRes.isInvalid())
8647 return ExprError();
8648 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008649 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00008650 }
John Wiegley01296292011-04-08 18:41:53 +00008651 }
8652
8653 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00008654 // This is an erroneous use of an operator which can be overloaded by
8655 // a non-member function. Check for non-member operators which were
8656 // defined too late to be candidates.
8657 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8658 // FIXME: Recover by calling the found function.
8659 return ExprError();
8660
John Wiegley01296292011-04-08 18:41:53 +00008661 // No viable function; fall through to handling this as a
8662 // built-in operator, which will produce an error message for us.
8663 break;
8664
8665 case OR_Ambiguous:
8666 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8667 << UnaryOperator::getOpcodeStr(Opc)
8668 << Input->getType()
8669 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008670 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00008671 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8672 return ExprError();
8673
8674 case OR_Deleted:
8675 Diag(OpLoc, diag::err_ovl_deleted_oper)
8676 << Best->Function->isDeleted()
8677 << UnaryOperator::getOpcodeStr(Opc)
8678 << getDeletedOrUnavailableSuffix(Best->Function)
8679 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008680 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
8681 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00008682 return ExprError();
8683 }
Douglas Gregor084d8552009-03-13 23:49:33 +00008684
8685 // Either we found no viable overloaded operator or we matched a
8686 // built-in operator. In either case, fall through to trying to
8687 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00008688 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008689}
8690
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008691/// \brief Create a binary operation that may resolve to an overloaded
8692/// operator.
8693///
8694/// \param OpLoc The location of the operator itself (e.g., '+').
8695///
8696/// \param OpcIn The BinaryOperator::Opcode that describes this
8697/// operator.
8698///
8699/// \param Functions The set of non-member functions that will be
8700/// considered by overload resolution. The caller needs to build this
8701/// set based on the context using, e.g.,
8702/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8703/// set should not contain any member functions; those will be added
8704/// by CreateOverloadedBinOp().
8705///
8706/// \param LHS Left-hand argument.
8707/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00008708ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008709Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008710 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00008711 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008712 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008713 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00008714 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008715
8716 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8717 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8718 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8719
8720 // If either side is type-dependent, create an appropriate dependent
8721 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00008722 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00008723 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008724 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00008725 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00008726 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00008727 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00008728 Context.DependentTy,
8729 VK_RValue, OK_Ordinary,
8730 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008731
Douglas Gregor5287f092009-11-05 00:51:44 +00008732 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8733 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008734 VK_LValue,
8735 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00008736 Context.DependentTy,
8737 Context.DependentTy,
8738 OpLoc));
8739 }
John McCall4c4c1df2010-01-26 03:27:55 +00008740
8741 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00008742 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008743 // TODO: provide better source location info in DNLoc component.
8744 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00008745 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00008746 = UnresolvedLookupExpr::Create(Context, NamingClass,
8747 NestedNameSpecifierLoc(), OpNameInfo,
8748 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008749 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008750 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00008751 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008752 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008753 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008754 OpLoc));
8755 }
8756
John McCalle26a8722010-12-04 08:14:53 +00008757 // Always do property rvalue conversions on the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008758 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8759 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8760 if (Result.isInvalid())
8761 return ExprError();
8762 Args[1] = Result.take();
8763 }
John McCalle26a8722010-12-04 08:14:53 +00008764
8765 // The LHS is more complicated.
8766 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8767
8768 // There's a tension for assignment operators between primitive
8769 // property assignment and the overloaded operators.
8770 if (BinaryOperator::isAssignmentOp(Opc)) {
8771 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8772
8773 // Is the property "logically" settable?
8774 bool Settable = (PRE->isExplicitProperty() ||
8775 PRE->getImplicitPropertySetter());
8776
8777 // To avoid gratuitously inventing semantics, use the primitive
8778 // unless it isn't. Thoughts in case we ever really care:
8779 // - If the property isn't logically settable, we have to
8780 // load and hope.
8781 // - If the property is settable and this is simple assignment,
8782 // we really should use the primitive.
8783 // - If the property is settable, then we could try overloading
8784 // on a generic lvalue of the appropriate type; if it works
8785 // out to a builtin candidate, we would do that same operation
8786 // on the property, and otherwise just error.
8787 if (Settable)
8788 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8789 }
8790
John Wiegley01296292011-04-08 18:41:53 +00008791 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8792 if (Result.isInvalid())
8793 return ExprError();
8794 Args[0] = Result.take();
John McCalle26a8722010-12-04 08:14:53 +00008795 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008796
Sebastian Redl6a96bf72009-11-18 23:10:33 +00008797 // If this is the assignment operator, we only perform overload resolution
8798 // if the left-hand side is a class or enumeration type. This is actually
8799 // a hack. The standard requires that we do overload resolution between the
8800 // various built-in candidates, but as DR507 points out, this can lead to
8801 // problems. So we do it this way, which pretty much follows what GCC does.
8802 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00008803 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00008804 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008805
John McCalle26a8722010-12-04 08:14:53 +00008806 // If this is the .* operator, which is not overloadable, just
8807 // create a built-in binary operator.
8808 if (Opc == BO_PtrMemD)
8809 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8810
Douglas Gregor084d8552009-03-13 23:49:33 +00008811 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008812 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008813
8814 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008815 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008816
8817 // Add operator candidates that are member functions.
8818 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8819
John McCall4c4c1df2010-01-26 03:27:55 +00008820 // Add candidates from ADL.
8821 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8822 Args, 2,
8823 /*ExplicitTemplateArgs*/ 0,
8824 CandidateSet);
8825
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008826 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008827 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008828
8829 // Perform overload resolution.
8830 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008831 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00008832 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008833 // We found a built-in operator or an overloaded operator.
8834 FunctionDecl *FnDecl = Best->Function;
8835
8836 if (FnDecl) {
8837 // We matched an overloaded operator. Build a call to that
8838 // operator.
8839
Chandler Carruth30141632011-02-25 19:41:05 +00008840 MarkDeclarationReferenced(OpLoc, FnDecl);
8841
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008842 // Convert the arguments.
8843 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00008844 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00008845 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008846
Chandler Carruth8e543b32010-12-12 08:17:55 +00008847 ExprResult Arg1 =
8848 PerformCopyInitialization(
8849 InitializedEntity::InitializeParameter(Context,
8850 FnDecl->getParamDecl(0)),
8851 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008852 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008853 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008854
John Wiegley01296292011-04-08 18:41:53 +00008855 ExprResult Arg0 =
8856 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8857 Best->FoundDecl, Method);
8858 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008859 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008860 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008861 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008862 } else {
8863 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00008864 ExprResult Arg0 = PerformCopyInitialization(
8865 InitializedEntity::InitializeParameter(Context,
8866 FnDecl->getParamDecl(0)),
8867 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008868 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008869 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008870
Chandler Carruth8e543b32010-12-12 08:17:55 +00008871 ExprResult Arg1 =
8872 PerformCopyInitialization(
8873 InitializedEntity::InitializeParameter(Context,
8874 FnDecl->getParamDecl(1)),
8875 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008876 if (Arg1.isInvalid())
8877 return ExprError();
8878 Args[0] = LHS = Arg0.takeAs<Expr>();
8879 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008880 }
8881
John McCall4fa0d5f2010-05-06 18:15:07 +00008882 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8883
John McCall7decc9e2010-11-18 06:31:45 +00008884 // Determine the result type.
8885 QualType ResultTy = FnDecl->getResultType();
8886 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8887 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008888
8889 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008890 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
8891 if (FnExpr.isInvalid())
8892 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008893
John McCallb268a282010-08-23 23:25:46 +00008894 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008895 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008896 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008897
8898 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008899 FnDecl))
8900 return ExprError();
8901
John McCallb268a282010-08-23 23:25:46 +00008902 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008903 } else {
8904 // We matched a built-in operator. Convert the arguments, then
8905 // break out so that we will build the appropriate built-in
8906 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008907 ExprResult ArgsRes0 =
8908 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8909 Best->Conversions[0], AA_Passing);
8910 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008911 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008912 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008913
John Wiegley01296292011-04-08 18:41:53 +00008914 ExprResult ArgsRes1 =
8915 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8916 Best->Conversions[1], AA_Passing);
8917 if (ArgsRes1.isInvalid())
8918 return ExprError();
8919 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008920 break;
8921 }
8922 }
8923
Douglas Gregor66950a32009-09-30 21:46:01 +00008924 case OR_No_Viable_Function: {
8925 // C++ [over.match.oper]p9:
8926 // If the operator is the operator , [...] and there are no
8927 // viable functions, then the operator is assumed to be the
8928 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00008929 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00008930 break;
8931
Chandler Carruth8e543b32010-12-12 08:17:55 +00008932 // For class as left operand for assignment or compound assigment
8933 // operator do not fall through to handling in built-in, but report that
8934 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00008935 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008936 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00008937 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00008938 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8939 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00008940 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00008941 } else {
Richard Smith998a5912011-06-05 22:42:48 +00008942 // This is an erroneous use of an operator which can be overloaded by
8943 // a non-member function. Check for non-member operators which were
8944 // defined too late to be candidates.
8945 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
8946 // FIXME: Recover by calling the found function.
8947 return ExprError();
8948
Douglas Gregor66950a32009-09-30 21:46:01 +00008949 // No viable function; try to create a built-in operation, which will
8950 // produce an error. Then, show the non-viable candidates.
8951 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00008952 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008953 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00008954 "C++ binary operator overloading is missing candidates!");
8955 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00008956 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8957 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00008958 return move(Result);
8959 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008960
8961 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008962 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008963 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00008964 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00008965 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008966 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8967 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008968 return ExprError();
8969
8970 case OR_Deleted:
8971 Diag(OpLoc, diag::err_ovl_deleted_oper)
8972 << Best->Function->isDeleted()
8973 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008974 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00008975 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008976 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8977 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008978 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00008979 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008980
Douglas Gregor66950a32009-09-30 21:46:01 +00008981 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00008982 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008983}
8984
John McCalldadc5752010-08-24 06:29:42 +00008985ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00008986Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8987 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00008988 Expr *Base, Expr *Idx) {
8989 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00008990 DeclarationName OpName =
8991 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8992
8993 // If either side is type-dependent, create an appropriate dependent
8994 // expression.
8995 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8996
John McCall58cc69d2010-01-27 01:50:18 +00008997 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008998 // CHECKME: no 'operator' keyword?
8999 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9000 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00009001 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009002 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009003 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009004 /*ADL*/ true, /*Overloaded*/ false,
9005 UnresolvedSetIterator(),
9006 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00009007 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00009008
Sebastian Redladba46e2009-10-29 20:17:01 +00009009 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9010 Args, 2,
9011 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009012 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00009013 RLoc));
9014 }
9015
John Wiegley01296292011-04-08 18:41:53 +00009016 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
9017 ExprResult Result = ConvertPropertyForRValue(Args[0]);
9018 if (Result.isInvalid())
9019 return ExprError();
9020 Args[0] = Result.take();
9021 }
9022 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
9023 ExprResult Result = ConvertPropertyForRValue(Args[1]);
9024 if (Result.isInvalid())
9025 return ExprError();
9026 Args[1] = Result.take();
9027 }
John McCalle26a8722010-12-04 08:14:53 +00009028
Sebastian Redladba46e2009-10-29 20:17:01 +00009029 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009030 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009031
9032 // Subscript can only be overloaded as a member function.
9033
9034 // Add operator candidates that are member functions.
9035 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9036
9037 // Add builtin operator candidates.
9038 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9039
9040 // Perform overload resolution.
9041 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009042 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00009043 case OR_Success: {
9044 // We found a built-in operator or an overloaded operator.
9045 FunctionDecl *FnDecl = Best->Function;
9046
9047 if (FnDecl) {
9048 // We matched an overloaded operator. Build a call to that
9049 // operator.
9050
Chandler Carruth30141632011-02-25 19:41:05 +00009051 MarkDeclarationReferenced(LLoc, FnDecl);
9052
John McCalla0296f72010-03-19 07:35:19 +00009053 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009054 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00009055
Sebastian Redladba46e2009-10-29 20:17:01 +00009056 // Convert the arguments.
9057 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00009058 ExprResult Arg0 =
9059 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9060 Best->FoundDecl, Method);
9061 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009062 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009063 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009064
Anders Carlssona68e51e2010-01-29 18:37:50 +00009065 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009066 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00009067 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009068 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00009069 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009070 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00009071 Owned(Args[1]));
9072 if (InputInit.isInvalid())
9073 return ExprError();
9074
9075 Args[1] = InputInit.takeAs<Expr>();
9076
Sebastian Redladba46e2009-10-29 20:17:01 +00009077 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00009078 QualType ResultTy = FnDecl->getResultType();
9079 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9080 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00009081
9082 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00009083 DeclarationNameLoc LocInfo;
9084 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9085 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
9086 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00009087 if (FnExpr.isInvalid())
9088 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009089
John McCallb268a282010-08-23 23:25:46 +00009090 CXXOperatorCallExpr *TheCall =
9091 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00009092 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00009093 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009094
John McCallb268a282010-08-23 23:25:46 +00009095 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00009096 FnDecl))
9097 return ExprError();
9098
John McCallb268a282010-08-23 23:25:46 +00009099 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00009100 } else {
9101 // We matched a built-in operator. Convert the arguments, then
9102 // break out so that we will build the appropriate built-in
9103 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009104 ExprResult ArgsRes0 =
9105 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9106 Best->Conversions[0], AA_Passing);
9107 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009108 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009109 Args[0] = ArgsRes0.take();
9110
9111 ExprResult ArgsRes1 =
9112 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9113 Best->Conversions[1], AA_Passing);
9114 if (ArgsRes1.isInvalid())
9115 return ExprError();
9116 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009117
9118 break;
9119 }
9120 }
9121
9122 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00009123 if (CandidateSet.empty())
9124 Diag(LLoc, diag::err_ovl_no_oper)
9125 << Args[0]->getType() << /*subscript*/ 0
9126 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9127 else
9128 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9129 << Args[0]->getType()
9130 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009131 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9132 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00009133 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009134 }
9135
9136 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009137 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009138 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00009139 << Args[0]->getType() << Args[1]->getType()
9140 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009141 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9142 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009143 return ExprError();
9144
9145 case OR_Deleted:
9146 Diag(LLoc, diag::err_ovl_deleted_oper)
9147 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009148 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00009149 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009150 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9151 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009152 return ExprError();
9153 }
9154
9155 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00009156 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009157}
9158
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009159/// BuildCallToMemberFunction - Build a call to a member
9160/// function. MemExpr is the expression that refers to the member
9161/// function (and includes the object parameter), Args/NumArgs are the
9162/// arguments to the function call (not including the object
9163/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00009164/// expression refers to a non-static member function or an overloaded
9165/// member function.
John McCalldadc5752010-08-24 06:29:42 +00009166ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00009167Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9168 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009169 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00009170 assert(MemExprE->getType() == Context.BoundMemberTy ||
9171 MemExprE->getType() == Context.OverloadTy);
9172
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009173 // Dig out the member expression. This holds both the object
9174 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00009175 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009176
John McCall0009fcc2011-04-26 20:42:42 +00009177 // Determine whether this is a call to a pointer-to-member function.
9178 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9179 assert(op->getType() == Context.BoundMemberTy);
9180 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9181
9182 QualType fnType =
9183 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9184
9185 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9186 QualType resultType = proto->getCallResultType(Context);
9187 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9188
9189 // Check that the object type isn't more qualified than the
9190 // member function we're calling.
9191 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9192
9193 QualType objectType = op->getLHS()->getType();
9194 if (op->getOpcode() == BO_PtrMemI)
9195 objectType = objectType->castAs<PointerType>()->getPointeeType();
9196 Qualifiers objectQuals = objectType.getQualifiers();
9197
9198 Qualifiers difference = objectQuals - funcQuals;
9199 difference.removeObjCGCAttr();
9200 difference.removeAddressSpace();
9201 if (difference) {
9202 std::string qualsString = difference.getAsString();
9203 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9204 << fnType.getUnqualifiedType()
9205 << qualsString
9206 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9207 }
9208
9209 CXXMemberCallExpr *call
9210 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9211 resultType, valueKind, RParenLoc);
9212
9213 if (CheckCallReturnType(proto->getResultType(),
9214 op->getRHS()->getSourceRange().getBegin(),
9215 call, 0))
9216 return ExprError();
9217
9218 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9219 return ExprError();
9220
9221 return MaybeBindToTemporary(call);
9222 }
9223
John McCall10eae182009-11-30 22:42:35 +00009224 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009225 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009226 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009227 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009228 if (isa<MemberExpr>(NakedMemExpr)) {
9229 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009230 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009231 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009232 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00009233 } else {
9234 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009235 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009236
John McCall6e9f8f62009-12-03 04:06:58 +00009237 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009238 Expr::Classification ObjectClassification
9239 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9240 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009241
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009242 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009243 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009244
John McCall2d74de92009-12-01 22:10:20 +00009245 // FIXME: avoid copy.
9246 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9247 if (UnresExpr->hasExplicitTemplateArgs()) {
9248 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9249 TemplateArgs = &TemplateArgsBuffer;
9250 }
9251
John McCall10eae182009-11-30 22:42:35 +00009252 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9253 E = UnresExpr->decls_end(); I != E; ++I) {
9254
John McCall6e9f8f62009-12-03 04:06:58 +00009255 NamedDecl *Func = *I;
9256 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9257 if (isa<UsingShadowDecl>(Func))
9258 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9259
Douglas Gregor02824322011-01-26 19:30:28 +00009260
Francois Pichet64225792011-01-18 05:04:39 +00009261 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +00009262 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +00009263 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9264 CandidateSet);
9265 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009266 // If explicit template arguments were provided, we can't call a
9267 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009268 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009269 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009270
John McCalla0296f72010-03-19 07:35:19 +00009271 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009272 ObjectClassification,
9273 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009274 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009275 } else {
John McCall10eae182009-11-30 22:42:35 +00009276 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009277 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009278 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009279 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009280 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009281 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009282 }
Mike Stump11289f42009-09-09 15:08:12 +00009283
John McCall10eae182009-11-30 22:42:35 +00009284 DeclarationName DeclName = UnresExpr->getMemberName();
9285
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009286 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009287 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009288 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009289 case OR_Success:
9290 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009291 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009292 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009293 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009294 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009295 break;
9296
9297 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009298 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009299 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009300 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009301 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009302 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009303 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009304
9305 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009306 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009307 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009308 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009309 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009310 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009311
9312 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009313 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009314 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009315 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009316 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009317 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009318 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009319 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009320 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009321 }
9322
John McCall16df1e52010-03-30 21:47:33 +00009323 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009324
John McCall2d74de92009-12-01 22:10:20 +00009325 // If overload resolution picked a static member, build a
9326 // non-member call based on that function.
9327 if (Method->isStatic()) {
9328 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9329 Args, NumArgs, RParenLoc);
9330 }
9331
John McCall10eae182009-11-30 22:42:35 +00009332 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009333 }
9334
John McCall7decc9e2010-11-18 06:31:45 +00009335 QualType ResultType = Method->getResultType();
9336 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9337 ResultType = ResultType.getNonLValueExprType(Context);
9338
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009339 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009340 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009341 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009342 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009343
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009344 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009345 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009346 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009347 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009348
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009349 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009350 // We only need to do this if there was actually an overload; otherwise
9351 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009352 if (!Method->isStatic()) {
9353 ExprResult ObjectArg =
9354 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9355 FoundDecl, Method);
9356 if (ObjectArg.isInvalid())
9357 return ExprError();
9358 MemExpr->setBase(ObjectArg.take());
9359 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009360
9361 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009362 const FunctionProtoType *Proto =
9363 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009364 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009365 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009366 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009367
John McCallb268a282010-08-23 23:25:46 +00009368 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009369 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009370
Anders Carlsson47061ee2011-05-06 14:25:31 +00009371 if ((isa<CXXConstructorDecl>(CurContext) ||
9372 isa<CXXDestructorDecl>(CurContext)) &&
9373 TheCall->getMethodDecl()->isPure()) {
9374 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9375
Chandler Carruth59259262011-06-27 08:31:58 +00009376 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009377 Diag(MemExpr->getLocStart(),
9378 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9379 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9380 << MD->getParent()->getDeclName();
9381
9382 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009383 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009384 }
John McCallb268a282010-08-23 23:25:46 +00009385 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009386}
9387
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009388/// BuildCallToObjectOfClassType - Build a call to an object of class
9389/// type (C++ [over.call.object]), which can end up invoking an
9390/// overloaded function call operator (@c operator()) or performing a
9391/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009392ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009393Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009394 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009395 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009396 SourceLocation RParenLoc) {
John Wiegley01296292011-04-08 18:41:53 +00009397 ExprResult Object = Owned(Obj);
9398 if (Object.get()->getObjectKind() == OK_ObjCProperty) {
9399 Object = ConvertPropertyForRValue(Object.take());
9400 if (Object.isInvalid())
9401 return ExprError();
9402 }
John McCalle26a8722010-12-04 08:14:53 +00009403
John Wiegley01296292011-04-08 18:41:53 +00009404 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9405 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009406
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009407 // C++ [over.call.object]p1:
9408 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009409 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009410 // candidate functions includes at least the function call
9411 // operators of T. The function call operators of T are obtained by
9412 // ordinary lookup of the name operator() in the context of
9413 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009414 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009415 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009416
John Wiegley01296292011-04-08 18:41:53 +00009417 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009418 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009419 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009420 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009421
John McCall27b18f82009-11-17 02:14:36 +00009422 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9423 LookupQualifiedName(R, Record->getDecl());
9424 R.suppressDiagnostics();
9425
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009426 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009427 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009428 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9429 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009430 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009431 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009432
Douglas Gregorab7897a2008-11-19 22:57:39 +00009433 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009434 // In addition, for each (non-explicit in C++0x) conversion function
9435 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +00009436 //
9437 // operator conversion-type-id () cv-qualifier;
9438 //
9439 // where cv-qualifier is the same cv-qualification as, or a
9440 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009441 // denotes the type "pointer to function of (P1,...,Pn) returning
9442 // R", or the type "reference to pointer to function of
9443 // (P1,...,Pn) returning R", or the type "reference to function
9444 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009445 // is also considered as a candidate function. Similarly,
9446 // surrogate call functions are added to the set of candidate
9447 // functions for each conversion function declared in an
9448 // accessible base class provided the function is not hidden
9449 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009450 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009451 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009452 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009453 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009454 NamedDecl *D = *I;
9455 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9456 if (isa<UsingShadowDecl>(D))
9457 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009458
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009459 // Skip over templated conversion functions; they aren't
9460 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009461 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009462 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009463
John McCall6e9f8f62009-12-03 04:06:58 +00009464 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009465 if (!Conv->isExplicit()) {
9466 // Strip the reference type (if any) and then the pointer type (if
9467 // any) to get down to what might be a function type.
9468 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9469 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9470 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +00009471
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009472 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9473 {
9474 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9475 Object.get(), Args, NumArgs, CandidateSet);
9476 }
9477 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00009478 }
Mike Stump11289f42009-09-09 15:08:12 +00009479
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009480 // Perform overload resolution.
9481 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009482 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009483 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009484 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009485 // Overload resolution succeeded; we'll build the appropriate call
9486 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009487 break;
9488
9489 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009490 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009491 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9492 << Object.get()->getType() << /*call*/ 1
9493 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009494 else
John Wiegley01296292011-04-08 18:41:53 +00009495 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009496 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009497 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009498 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009499 break;
9500
9501 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009502 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009503 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009504 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009505 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009506 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009507
9508 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00009509 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00009510 diag::err_ovl_deleted_object_call)
9511 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +00009512 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009513 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +00009514 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009515 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009516 break;
Mike Stump11289f42009-09-09 15:08:12 +00009517 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009518
Douglas Gregorb412e172010-07-25 18:17:45 +00009519 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009520 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009521
Douglas Gregorab7897a2008-11-19 22:57:39 +00009522 if (Best->Function == 0) {
9523 // Since there is no function declaration, this is one of the
9524 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00009525 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00009526 = cast<CXXConversionDecl>(
9527 Best->Conversions[0].UserDefined.ConversionFunction);
9528
John Wiegley01296292011-04-08 18:41:53 +00009529 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009530 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009531
Douglas Gregorab7897a2008-11-19 22:57:39 +00009532 // We selected one of the surrogate functions that converts the
9533 // object parameter to a function pointer. Perform the conversion
9534 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009535
Fariborz Jahanian774cf792009-09-28 18:35:46 +00009536 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00009537 // and then call it.
John Wiegley01296292011-04-08 18:41:53 +00009538 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv);
Douglas Gregor668443e2011-01-20 00:18:04 +00009539 if (Call.isInvalid())
9540 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009541
Douglas Gregor668443e2011-01-20 00:18:04 +00009542 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00009543 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00009544 }
9545
Chandler Carruth30141632011-02-25 19:41:05 +00009546 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009547 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009548 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009549
Douglas Gregorab7897a2008-11-19 22:57:39 +00009550 // We found an overloaded operator(). Build a CXXOperatorCallExpr
9551 // that calls this method, using Object for the implicit object
9552 // parameter and passing along the remaining arguments.
9553 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00009554 const FunctionProtoType *Proto =
9555 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009556
9557 unsigned NumArgsInProto = Proto->getNumArgs();
9558 unsigned NumArgsToCheck = NumArgs;
9559
9560 // Build the full argument list for the method call (the
9561 // implicit object parameter is placed at the beginning of the
9562 // list).
9563 Expr **MethodArgs;
9564 if (NumArgs < NumArgsInProto) {
9565 NumArgsToCheck = NumArgsInProto;
9566 MethodArgs = new Expr*[NumArgsInProto + 1];
9567 } else {
9568 MethodArgs = new Expr*[NumArgs + 1];
9569 }
John Wiegley01296292011-04-08 18:41:53 +00009570 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009571 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9572 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00009573
John Wiegley01296292011-04-08 18:41:53 +00009574 ExprResult NewFn = CreateFunctionRefExpr(*this, Method);
9575 if (NewFn.isInvalid())
9576 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009577
9578 // Once we've built TheCall, all of the expressions are properly
9579 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00009580 QualType ResultTy = Method->getResultType();
9581 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9582 ResultTy = ResultTy.getNonLValueExprType(Context);
9583
John McCallb268a282010-08-23 23:25:46 +00009584 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009585 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +00009586 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00009587 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009588 delete [] MethodArgs;
9589
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009590 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00009591 Method))
9592 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009593
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009594 // We may have default arguments. If so, we need to allocate more
9595 // slots in the call for them.
9596 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00009597 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009598 else if (NumArgs > NumArgsInProto)
9599 NumArgsToCheck = NumArgsInProto;
9600
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009601 bool IsError = false;
9602
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009603 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +00009604 ExprResult ObjRes =
9605 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9606 Best->FoundDecl, Method);
9607 if (ObjRes.isInvalid())
9608 IsError = true;
9609 else
9610 Object = move(ObjRes);
9611 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009612
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009613 // Check the argument types.
9614 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009615 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009616 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009617 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00009618
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009619 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009620
John McCalldadc5752010-08-24 06:29:42 +00009621 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009622 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009623 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009624 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00009625 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009626
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009627 IsError |= InputInit.isInvalid();
9628 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009629 } else {
John McCalldadc5752010-08-24 06:29:42 +00009630 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009631 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9632 if (DefArg.isInvalid()) {
9633 IsError = true;
9634 break;
9635 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009636
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009637 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009638 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009639
9640 TheCall->setArg(i + 1, Arg);
9641 }
9642
9643 // If this is a variadic call, handle args passed through "...".
9644 if (Proto->isVariadic()) {
9645 // Promote the arguments (C99 6.5.2.2p7).
9646 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +00009647 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9648 IsError |= Arg.isInvalid();
9649 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009650 }
9651 }
9652
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009653 if (IsError) return true;
9654
John McCallb268a282010-08-23 23:25:46 +00009655 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00009656 return true;
9657
John McCalle172be52010-08-24 06:09:16 +00009658 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009659}
9660
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009661/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00009662/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009663/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00009664ExprResult
John McCallb268a282010-08-23 23:25:46 +00009665Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009666 assert(Base->getType()->isRecordType() &&
9667 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00009668
John Wiegley01296292011-04-08 18:41:53 +00009669 if (Base->getObjectKind() == OK_ObjCProperty) {
9670 ExprResult Result = ConvertPropertyForRValue(Base);
9671 if (Result.isInvalid())
9672 return ExprError();
9673 Base = Result.take();
9674 }
John McCalle26a8722010-12-04 08:14:53 +00009675
John McCallbc077cf2010-02-08 23:07:23 +00009676 SourceLocation Loc = Base->getExprLoc();
9677
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009678 // C++ [over.ref]p1:
9679 //
9680 // [...] An expression x->m is interpreted as (x.operator->())->m
9681 // for a class object x of type T if T::operator->() exists and if
9682 // the operator is selected as the best match function by the
9683 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00009684 DeclarationName OpName =
9685 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00009686 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009687 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00009688
John McCallbc077cf2010-02-08 23:07:23 +00009689 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00009690 PDiag(diag::err_typecheck_incomplete_tag)
9691 << Base->getSourceRange()))
9692 return ExprError();
9693
John McCall27b18f82009-11-17 02:14:36 +00009694 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9695 LookupQualifiedName(R, BaseRecord->getDecl());
9696 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00009697
9698 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00009699 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00009700 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9701 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00009702 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009703
9704 // Perform overload resolution.
9705 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009706 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009707 case OR_Success:
9708 // Overload resolution succeeded; we'll build the call below.
9709 break;
9710
9711 case OR_No_Viable_Function:
9712 if (CandidateSet.empty())
9713 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00009714 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009715 else
9716 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00009717 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009718 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009719 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009720
9721 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009722 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9723 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009724 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009725 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009726
9727 case OR_Deleted:
9728 Diag(OpLoc, diag::err_ovl_deleted_oper)
9729 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009730 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009731 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009732 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009733 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009734 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009735 }
9736
Chandler Carruth30141632011-02-25 19:41:05 +00009737 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00009738 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009739 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00009740
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009741 // Convert the object parameter.
9742 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009743 ExprResult BaseResult =
9744 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9745 Best->FoundDecl, Method);
9746 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +00009747 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009748 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +00009749
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009750 // Build the operator call.
John Wiegley01296292011-04-08 18:41:53 +00009751 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method);
9752 if (FnExpr.isInvalid())
9753 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009754
John McCall7decc9e2010-11-18 06:31:45 +00009755 QualType ResultTy = Method->getResultType();
9756 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9757 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00009758 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009759 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009760 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009761
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009762 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009763 Method))
9764 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +00009765
9766 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009767}
9768
Douglas Gregorcd695e52008-11-10 20:40:00 +00009769/// FixOverloadedFunctionReference - E is an expression that refers to
9770/// a C++ overloaded function (possibly with some parentheses and
9771/// perhaps a '&' around it). We have resolved the overloaded function
9772/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00009773/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00009774Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00009775 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00009776 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009777 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9778 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009779 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009780 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009781
Douglas Gregor51c538b2009-11-20 19:42:02 +00009782 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009783 }
9784
Douglas Gregor51c538b2009-11-20 19:42:02 +00009785 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009786 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9787 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009788 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00009789 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00009790 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00009791 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00009792 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009793 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009794
9795 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +00009796 ICE->getCastKind(),
9797 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00009798 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009799 }
9800
Douglas Gregor51c538b2009-11-20 19:42:02 +00009801 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00009802 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00009803 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009804 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9805 if (Method->isStatic()) {
9806 // Do nothing: static member functions aren't any different
9807 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00009808 } else {
John McCalle66edc12009-11-24 19:00:30 +00009809 // Fix the sub expression, which really has to be an
9810 // UnresolvedLookupExpr holding an overloaded member function
9811 // or template.
John McCall16df1e52010-03-30 21:47:33 +00009812 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9813 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00009814 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009815 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00009816
John McCalld14a8642009-11-21 08:51:07 +00009817 assert(isa<DeclRefExpr>(SubExpr)
9818 && "fixed to something other than a decl ref");
9819 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9820 && "fixed to a member ref with no nested name qualifier");
9821
9822 // We have taken the address of a pointer to member
9823 // function. Perform the computation here so that we get the
9824 // appropriate pointer to member type.
9825 QualType ClassType
9826 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9827 QualType MemPtrType
9828 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9829
John McCall7decc9e2010-11-18 06:31:45 +00009830 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9831 VK_RValue, OK_Ordinary,
9832 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009833 }
9834 }
John McCall16df1e52010-03-30 21:47:33 +00009835 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9836 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009837 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009838 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009839
John McCalle3027922010-08-25 11:45:40 +00009840 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009841 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00009842 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009843 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009844 }
John McCalld14a8642009-11-21 08:51:07 +00009845
9846 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00009847 // FIXME: avoid copy.
9848 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00009849 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00009850 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9851 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00009852 }
9853
John McCalld14a8642009-11-21 08:51:07 +00009854 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009855 ULE->getQualifierLoc(),
John McCalld14a8642009-11-21 08:51:07 +00009856 Fn,
9857 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009858 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009859 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009860 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009861 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00009862 }
9863
John McCall10eae182009-11-30 22:42:35 +00009864 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00009865 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00009866 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9867 if (MemExpr->hasExplicitTemplateArgs()) {
9868 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9869 TemplateArgs = &TemplateArgsBuffer;
9870 }
John McCall6b51f282009-11-23 01:53:49 +00009871
John McCall2d74de92009-12-01 22:10:20 +00009872 Expr *Base;
9873
John McCall7decc9e2010-11-18 06:31:45 +00009874 // If we're filling in a static method where we used to have an
9875 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00009876 if (MemExpr->isImplicitAccess()) {
9877 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9878 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009879 MemExpr->getQualifierLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009880 Fn,
9881 MemExpr->getMemberLoc(),
9882 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009883 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009884 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009885 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00009886 } else {
9887 SourceLocation Loc = MemExpr->getMemberLoc();
9888 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +00009889 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +00009890 Base = new (Context) CXXThisExpr(Loc,
9891 MemExpr->getBaseType(),
9892 /*isImplicit=*/true);
9893 }
John McCall2d74de92009-12-01 22:10:20 +00009894 } else
John McCallc3007a22010-10-26 07:05:15 +00009895 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00009896
John McCall4adb38c2011-04-27 00:36:17 +00009897 ExprValueKind valueKind;
9898 QualType type;
9899 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9900 valueKind = VK_LValue;
9901 type = Fn->getType();
9902 } else {
9903 valueKind = VK_RValue;
9904 type = Context.BoundMemberTy;
9905 }
9906
John McCall2d74de92009-12-01 22:10:20 +00009907 return MemberExpr::Create(Context, Base,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009908 MemExpr->isArrow(),
Douglas Gregorea972d32011-02-28 21:54:11 +00009909 MemExpr->getQualifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009910 Fn,
John McCall16df1e52010-03-30 21:47:33 +00009911 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009912 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00009913 TemplateArgs,
John McCall4adb38c2011-04-27 00:36:17 +00009914 type, valueKind, OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009915 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009916
John McCallc3007a22010-10-26 07:05:15 +00009917 llvm_unreachable("Invalid reference to overloaded function");
9918 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009919}
9920
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009921ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +00009922 DeclAccessPair Found,
9923 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00009924 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00009925}
9926
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009927} // end namespace clang