blob: c2bf9d3848fb8719975a25e57f76fbd57ac08476 [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 }
2077 ConvertedType = ToType;
2078 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002079}
2080
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002081/// FunctionArgTypesAreEqual - This routine checks two function proto types
2082/// for equlity of their argument types. Caller has already checked that
2083/// they have same number of arguments. This routine assumes that Objective-C
2084/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002085bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00002086 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002087 if (!getLangOptions().ObjC1)
2088 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2089 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002090
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002091 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2092 N = NewType->arg_type_begin(),
2093 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2094 QualType ToType = (*O);
2095 QualType FromType = (*N);
2096 if (ToType != FromType) {
2097 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2098 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002099 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2100 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2101 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2102 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002103 continue;
2104 }
John McCall8b07ec22010-05-15 11:32:37 +00002105 else if (const ObjCObjectPointerType *PTTo =
2106 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002107 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002108 FromType->getAs<ObjCObjectPointerType>())
2109 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2110 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002112 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002113 }
2114 }
2115 return true;
2116}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002117
Douglas Gregor39c16d42008-10-24 04:54:22 +00002118/// CheckPointerConversion - Check the pointer conversion from the
2119/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002120/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002121/// conversions for which IsPointerConversion has already returned
2122/// true. It returns true and produces a diagnostic if there was an
2123/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002124bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002125 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002126 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002127 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002128 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002129 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002130
John McCall8cb679e2010-11-15 09:13:47 +00002131 Kind = CK_BitCast;
2132
Chandler Carruthffab8732011-04-09 07:32:05 +00002133 if (!IsCStyleOrFunctionalCast &&
2134 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2135 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2136 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002137 PDiag(diag::warn_impcast_bool_to_null_pointer)
2138 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002139
John McCall9320b872011-09-09 05:25:32 +00002140 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2141 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002142 QualType FromPointeeType = FromPtrType->getPointeeType(),
2143 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002144
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002145 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2146 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002147 // We must have a derived-to-base conversion. Check an
2148 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002149 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2150 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002151 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002152 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002153 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002154
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002155 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002156 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002157 }
2158 }
John McCall9320b872011-09-09 05:25:32 +00002159 } else if (const ObjCObjectPointerType *ToPtrType =
2160 ToType->getAs<ObjCObjectPointerType>()) {
2161 if (const ObjCObjectPointerType *FromPtrType =
2162 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002163 // Objective-C++ conversions are always okay.
2164 // FIXME: We should have a different class of conversions for the
2165 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002166 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002167 return false;
John McCall9320b872011-09-09 05:25:32 +00002168 } else if (FromType->isBlockPointerType()) {
2169 Kind = CK_BlockPointerToObjCPointerCast;
2170 } else {
2171 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002172 }
John McCall9320b872011-09-09 05:25:32 +00002173 } else if (ToType->isBlockPointerType()) {
2174 if (!FromType->isBlockPointerType())
2175 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002176 }
John McCall8cb679e2010-11-15 09:13:47 +00002177
2178 // We shouldn't fall into this case unless it's valid for other
2179 // reasons.
2180 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2181 Kind = CK_NullToPointer;
2182
Douglas Gregor39c16d42008-10-24 04:54:22 +00002183 return false;
2184}
2185
Sebastian Redl72b597d2009-01-25 19:43:20 +00002186/// IsMemberPointerConversion - Determines whether the conversion of the
2187/// expression From, which has the (possibly adjusted) type FromType, can be
2188/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2189/// If so, returns true and places the converted type (that might differ from
2190/// ToType in its cv-qualifiers at some level) into ConvertedType.
2191bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002192 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002193 bool InOverloadResolution,
2194 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002195 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002196 if (!ToTypePtr)
2197 return false;
2198
2199 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002200 if (From->isNullPointerConstant(Context,
2201 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2202 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002203 ConvertedType = ToType;
2204 return true;
2205 }
2206
2207 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002208 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002209 if (!FromTypePtr)
2210 return false;
2211
2212 // A pointer to member of B can be converted to a pointer to member of D,
2213 // where D is derived from B (C++ 4.11p2).
2214 QualType FromClass(FromTypePtr->getClass(), 0);
2215 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002216
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002217 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2218 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2219 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002220 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2221 ToClass.getTypePtr());
2222 return true;
2223 }
2224
2225 return false;
2226}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002227
Sebastian Redl72b597d2009-01-25 19:43:20 +00002228/// CheckMemberPointerConversion - Check the member pointer conversion from the
2229/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002230/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002231/// for which IsMemberPointerConversion has already returned true. It returns
2232/// true and produces a diagnostic if there was an error, or returns false
2233/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002234bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002235 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002236 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002237 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002238 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002239 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002240 if (!FromPtrType) {
2241 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002242 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002243 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002244 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002245 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002246 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002247 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002248
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002249 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002250 assert(ToPtrType && "No member pointer cast has a target type "
2251 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002252
Sebastian Redled8f2002009-01-28 18:33:18 +00002253 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2254 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002255
Sebastian Redled8f2002009-01-28 18:33:18 +00002256 // FIXME: What about dependent types?
2257 assert(FromClass->isRecordType() && "Pointer into non-class.");
2258 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002259
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002260 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002261 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002262 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2263 assert(DerivationOkay &&
2264 "Should not have been called if derivation isn't OK.");
2265 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002266
Sebastian Redled8f2002009-01-28 18:33:18 +00002267 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2268 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002269 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2270 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2271 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2272 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002273 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002274
Douglas Gregor89ee6822009-02-28 01:32:25 +00002275 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002276 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2277 << FromClass << ToClass << QualType(VBase, 0)
2278 << From->getSourceRange();
2279 return true;
2280 }
2281
John McCall5b0829a2010-02-10 09:31:12 +00002282 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002283 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2284 Paths.front(),
2285 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002286
Anders Carlssond7923c62009-08-22 23:33:40 +00002287 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002288 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002289 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002290 return false;
2291}
2292
Douglas Gregor9a657932008-10-21 23:43:52 +00002293/// IsQualificationConversion - Determines whether the conversion from
2294/// an rvalue of type FromType to ToType is a qualification conversion
2295/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002296///
2297/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2298/// when the qualification conversion involves a change in the Objective-C
2299/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002300bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002301Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002302 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002303 FromType = Context.getCanonicalType(FromType);
2304 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002305 ObjCLifetimeConversion = false;
2306
Douglas Gregor9a657932008-10-21 23:43:52 +00002307 // If FromType and ToType are the same type, this is not a
2308 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002309 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002310 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002311
Douglas Gregor9a657932008-10-21 23:43:52 +00002312 // (C++ 4.4p4):
2313 // A conversion can add cv-qualifiers at levels other than the first
2314 // in multi-level pointers, subject to the following rules: [...]
2315 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002316 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002317 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002318 // Within each iteration of the loop, we check the qualifiers to
2319 // determine if this still looks like a qualification
2320 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002321 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002322 // until there are no more pointers or pointers-to-members left to
2323 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002324 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002325
Douglas Gregor90609aa2011-04-25 18:40:17 +00002326 Qualifiers FromQuals = FromType.getQualifiers();
2327 Qualifiers ToQuals = ToType.getQualifiers();
2328
John McCall31168b02011-06-15 23:02:42 +00002329 // Objective-C ARC:
2330 // Check Objective-C lifetime conversions.
2331 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2332 UnwrappedAnyPointer) {
2333 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2334 ObjCLifetimeConversion = true;
2335 FromQuals.removeObjCLifetime();
2336 ToQuals.removeObjCLifetime();
2337 } else {
2338 // Qualification conversions cannot cast between different
2339 // Objective-C lifetime qualifiers.
2340 return false;
2341 }
2342 }
2343
Douglas Gregorf30053d2011-05-08 06:09:53 +00002344 // Allow addition/removal of GC attributes but not changing GC attributes.
2345 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2346 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2347 FromQuals.removeObjCGCAttr();
2348 ToQuals.removeObjCGCAttr();
2349 }
2350
Douglas Gregor9a657932008-10-21 23:43:52 +00002351 // -- for every j > 0, if const is in cv 1,j then const is in cv
2352 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002353 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002354 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002355
Douglas Gregor9a657932008-10-21 23:43:52 +00002356 // -- if the cv 1,j and cv 2,j are different, then const is in
2357 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002358 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002359 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002360 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002361
Douglas Gregor9a657932008-10-21 23:43:52 +00002362 // Keep track of whether all prior cv-qualifiers in the "to" type
2363 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002364 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002365 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002366 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002367
2368 // We are left with FromType and ToType being the pointee types
2369 // after unwrapping the original FromType and ToType the same number
2370 // of types. If we unwrapped any pointers, and if FromType and
2371 // ToType have the same unqualified type (since we checked
2372 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002373 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002374}
2375
Douglas Gregor576e98c2009-01-30 23:27:23 +00002376/// Determines whether there is a user-defined conversion sequence
2377/// (C++ [over.ics.user]) that converts expression From to the type
2378/// ToType. If such a conversion exists, User will contain the
2379/// user-defined conversion sequence that performs such a conversion
2380/// and this routine will return true. Otherwise, this routine returns
2381/// false and User is unspecified.
2382///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002383/// \param AllowExplicit true if the conversion should consider C++0x
2384/// "explicit" conversion functions as well as non-explicit conversion
2385/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002386static OverloadingResult
2387IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2388 UserDefinedConversionSequence& User,
2389 OverloadCandidateSet& CandidateSet,
2390 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002391 // Whether we will only visit constructors.
2392 bool ConstructorsOnly = false;
2393
2394 // If the type we are conversion to is a class type, enumerate its
2395 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002396 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002397 // C++ [over.match.ctor]p1:
2398 // When objects of class type are direct-initialized (8.5), or
2399 // copy-initialized from an expression of the same or a
2400 // derived class type (8.5), overload resolution selects the
2401 // constructor. [...] For copy-initialization, the candidate
2402 // functions are all the converting constructors (12.3.1) of
2403 // that class. The argument list is the expression-list within
2404 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002405 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002406 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002407 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002408 ConstructorsOnly = true;
2409
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002410 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2411 // RequireCompleteType may have returned true due to some invalid decl
2412 // during template instantiation, but ToType may be complete enough now
2413 // to try to recover.
2414 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002415 // We're not going to find any constructors.
2416 } else if (CXXRecordDecl *ToRecordDecl
2417 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002418 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002419 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002420 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002421 NamedDecl *D = *Con;
2422 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2423
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002424 // Find the constructor (which may be a template).
2425 CXXConstructorDecl *Constructor = 0;
2426 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002427 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002428 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002429 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002430 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2431 else
John McCalla0296f72010-03-19 07:35:19 +00002432 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002433
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002434 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002435 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002436 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002437 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2438 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002439 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002440 /*SuppressUserConversions=*/
2441 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002442 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002443 // Allow one user-defined conversion when user specifies a
2444 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002445 S.AddOverloadCandidate(Constructor, FoundDecl,
2446 &From, 1, CandidateSet,
2447 /*SuppressUserConversions=*/
2448 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002449 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002450 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002451 }
2452 }
2453
Douglas Gregor5ab11652010-04-17 22:01:05 +00002454 // Enumerate conversion functions, if we're allowed to.
2455 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002456 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2457 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002458 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002459 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002460 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002461 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002462 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2463 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002464 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002465 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002466 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002467 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002468 DeclAccessPair FoundDecl = I.getPair();
2469 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002470 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2471 if (isa<UsingShadowDecl>(D))
2472 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2473
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002474 CXXConversionDecl *Conv;
2475 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002476 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2477 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002478 else
John McCallda4458e2010-03-31 01:36:47 +00002479 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002480
2481 if (AllowExplicit || !Conv->isExplicit()) {
2482 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002483 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2484 ActingContext, From, ToType,
2485 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002486 else
John McCall5c32be02010-08-24 20:38:10 +00002487 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2488 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002489 }
2490 }
2491 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002492 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002493
2494 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002495 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002496 case OR_Success:
2497 // Record the standard conversion we used and the conversion function.
2498 if (CXXConstructorDecl *Constructor
2499 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002500 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2501
John McCall5c32be02010-08-24 20:38:10 +00002502 // C++ [over.ics.user]p1:
2503 // If the user-defined conversion is specified by a
2504 // constructor (12.3.1), the initial standard conversion
2505 // sequence converts the source type to the type required by
2506 // the argument of the constructor.
2507 //
2508 QualType ThisType = Constructor->getThisType(S.Context);
2509 if (Best->Conversions[0].isEllipsis())
2510 User.EllipsisConversion = true;
2511 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002512 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002513 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002514 }
John McCall5c32be02010-08-24 20:38:10 +00002515 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00002516 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002517 User.After.setAsIdentityConversion();
2518 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2519 User.After.setAllToTypes(ToType);
2520 return OR_Success;
2521 } else if (CXXConversionDecl *Conversion
2522 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002523 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2524
John McCall5c32be02010-08-24 20:38:10 +00002525 // C++ [over.ics.user]p1:
2526 //
2527 // [...] If the user-defined conversion is specified by a
2528 // conversion function (12.3.2), the initial standard
2529 // conversion sequence converts the source type to the
2530 // implicit object parameter of the conversion function.
2531 User.Before = Best->Conversions[0].Standard;
2532 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00002533 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002534 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002535
John McCall5c32be02010-08-24 20:38:10 +00002536 // C++ [over.ics.user]p2:
2537 // The second standard conversion sequence converts the
2538 // result of the user-defined conversion to the target type
2539 // for the sequence. Since an implicit conversion sequence
2540 // is an initialization, the special rules for
2541 // initialization by user-defined conversion apply when
2542 // selecting the best user-defined conversion for a
2543 // user-defined conversion sequence (see 13.3.3 and
2544 // 13.3.3.1).
2545 User.After = Best->FinalConversion;
2546 return OR_Success;
2547 } else {
2548 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002549 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002550 }
2551
John McCall5c32be02010-08-24 20:38:10 +00002552 case OR_No_Viable_Function:
2553 return OR_No_Viable_Function;
2554 case OR_Deleted:
2555 // No conversion here! We're done.
2556 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002557
John McCall5c32be02010-08-24 20:38:10 +00002558 case OR_Ambiguous:
2559 return OR_Ambiguous;
2560 }
2561
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002562 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002563}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002564
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002565bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002566Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002567 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002568 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002569 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002570 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002571 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002572 if (OvResult == OR_Ambiguous)
2573 Diag(From->getSourceRange().getBegin(),
2574 diag::err_typecheck_ambiguous_condition)
2575 << From->getType() << ToType << From->getSourceRange();
2576 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2577 Diag(From->getSourceRange().getBegin(),
2578 diag::err_typecheck_nonviable_condition)
2579 << From->getType() << ToType << From->getSourceRange();
2580 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002581 return false;
John McCall5c32be02010-08-24 20:38:10 +00002582 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002583 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002584}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002585
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002586/// CompareImplicitConversionSequences - Compare two implicit
2587/// conversion sequences to determine whether one is better than the
2588/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002589static ImplicitConversionSequence::CompareKind
2590CompareImplicitConversionSequences(Sema &S,
2591 const ImplicitConversionSequence& ICS1,
2592 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002593{
2594 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2595 // conversion sequences (as defined in 13.3.3.1)
2596 // -- a standard conversion sequence (13.3.3.1.1) is a better
2597 // conversion sequence than a user-defined conversion sequence or
2598 // an ellipsis conversion sequence, and
2599 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2600 // conversion sequence than an ellipsis conversion sequence
2601 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002602 //
John McCall0d1da222010-01-12 00:44:57 +00002603 // C++0x [over.best.ics]p10:
2604 // For the purpose of ranking implicit conversion sequences as
2605 // described in 13.3.3.2, the ambiguous conversion sequence is
2606 // treated as a user-defined sequence that is indistinguishable
2607 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002608 if (ICS1.getKindRank() < ICS2.getKindRank())
2609 return ImplicitConversionSequence::Better;
2610 else if (ICS2.getKindRank() < ICS1.getKindRank())
2611 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002612
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002613 // The following checks require both conversion sequences to be of
2614 // the same kind.
2615 if (ICS1.getKind() != ICS2.getKind())
2616 return ImplicitConversionSequence::Indistinguishable;
2617
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002618 // Two implicit conversion sequences of the same form are
2619 // indistinguishable conversion sequences unless one of the
2620 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002621 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002622 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002623 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002624 // User-defined conversion sequence U1 is a better conversion
2625 // sequence than another user-defined conversion sequence U2 if
2626 // they contain the same user-defined conversion function or
2627 // constructor and if the second standard conversion sequence of
2628 // U1 is better than the second standard conversion sequence of
2629 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002630 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002631 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002632 return CompareStandardConversionSequences(S,
2633 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002634 ICS2.UserDefined.After);
2635 }
2636
2637 return ImplicitConversionSequence::Indistinguishable;
2638}
2639
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002640static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2641 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2642 Qualifiers Quals;
2643 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002644 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002645 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002646
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002647 return Context.hasSameUnqualifiedType(T1, T2);
2648}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002649
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002650// Per 13.3.3.2p3, compare the given standard conversion sequences to
2651// determine if one is a proper subset of the other.
2652static ImplicitConversionSequence::CompareKind
2653compareStandardConversionSubsets(ASTContext &Context,
2654 const StandardConversionSequence& SCS1,
2655 const StandardConversionSequence& SCS2) {
2656 ImplicitConversionSequence::CompareKind Result
2657 = ImplicitConversionSequence::Indistinguishable;
2658
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002659 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002660 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00002661 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2662 return ImplicitConversionSequence::Better;
2663 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2664 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002665
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002666 if (SCS1.Second != SCS2.Second) {
2667 if (SCS1.Second == ICK_Identity)
2668 Result = ImplicitConversionSequence::Better;
2669 else if (SCS2.Second == ICK_Identity)
2670 Result = ImplicitConversionSequence::Worse;
2671 else
2672 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002673 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002674 return ImplicitConversionSequence::Indistinguishable;
2675
2676 if (SCS1.Third == SCS2.Third) {
2677 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2678 : ImplicitConversionSequence::Indistinguishable;
2679 }
2680
2681 if (SCS1.Third == ICK_Identity)
2682 return Result == ImplicitConversionSequence::Worse
2683 ? ImplicitConversionSequence::Indistinguishable
2684 : ImplicitConversionSequence::Better;
2685
2686 if (SCS2.Third == ICK_Identity)
2687 return Result == ImplicitConversionSequence::Better
2688 ? ImplicitConversionSequence::Indistinguishable
2689 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002690
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002691 return ImplicitConversionSequence::Indistinguishable;
2692}
2693
Douglas Gregore696ebb2011-01-26 14:52:12 +00002694/// \brief Determine whether one of the given reference bindings is better
2695/// than the other based on what kind of bindings they are.
2696static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2697 const StandardConversionSequence &SCS2) {
2698 // C++0x [over.ics.rank]p3b4:
2699 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2700 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002701 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002702 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002703 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002704 // reference*.
2705 //
2706 // FIXME: Rvalue references. We're going rogue with the above edits,
2707 // because the semantics in the current C++0x working paper (N3225 at the
2708 // time of this writing) break the standard definition of std::forward
2709 // and std::reference_wrapper when dealing with references to functions.
2710 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002711 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2712 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2713 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002714
Douglas Gregore696ebb2011-01-26 14:52:12 +00002715 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2716 SCS2.IsLvalueReference) ||
2717 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2718 !SCS2.IsLvalueReference);
2719}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002720
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002721/// CompareStandardConversionSequences - Compare two standard
2722/// conversion sequences to determine whether one is better than the
2723/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002724static ImplicitConversionSequence::CompareKind
2725CompareStandardConversionSequences(Sema &S,
2726 const StandardConversionSequence& SCS1,
2727 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002728{
2729 // Standard conversion sequence S1 is a better conversion sequence
2730 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2731
2732 // -- S1 is a proper subsequence of S2 (comparing the conversion
2733 // sequences in the canonical form defined by 13.3.3.1.1,
2734 // excluding any Lvalue Transformation; the identity conversion
2735 // sequence is considered to be a subsequence of any
2736 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002737 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002738 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002739 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002740
2741 // -- the rank of S1 is better than the rank of S2 (by the rules
2742 // defined below), or, if not that,
2743 ImplicitConversionRank Rank1 = SCS1.getRank();
2744 ImplicitConversionRank Rank2 = SCS2.getRank();
2745 if (Rank1 < Rank2)
2746 return ImplicitConversionSequence::Better;
2747 else if (Rank2 < Rank1)
2748 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002749
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002750 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2751 // are indistinguishable unless one of the following rules
2752 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002753
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002754 // A conversion that is not a conversion of a pointer, or
2755 // pointer to member, to bool is better than another conversion
2756 // that is such a conversion.
2757 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2758 return SCS2.isPointerConversionToBool()
2759 ? ImplicitConversionSequence::Better
2760 : ImplicitConversionSequence::Worse;
2761
Douglas Gregor5c407d92008-10-23 00:40:37 +00002762 // C++ [over.ics.rank]p4b2:
2763 //
2764 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002765 // conversion of B* to A* is better than conversion of B* to
2766 // void*, and conversion of A* to void* is better than conversion
2767 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002768 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002769 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002770 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002771 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002772 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2773 // Exactly one of the conversion sequences is a conversion to
2774 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002775 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2776 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002777 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2778 // Neither conversion sequence converts to a void pointer; compare
2779 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002780 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002781 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002782 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002783 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2784 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002785 // Both conversion sequences are conversions to void
2786 // pointers. Compare the source types to determine if there's an
2787 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002788 QualType FromType1 = SCS1.getFromType();
2789 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002790
2791 // Adjust the types we're converting from via the array-to-pointer
2792 // conversion, if we need to.
2793 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002794 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002795 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002796 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002797
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002798 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2799 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002800
John McCall5c32be02010-08-24 20:38:10 +00002801 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002802 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002803 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002804 return ImplicitConversionSequence::Worse;
2805
2806 // Objective-C++: If one interface is more specific than the
2807 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002808 const ObjCObjectPointerType* FromObjCPtr1
2809 = FromType1->getAs<ObjCObjectPointerType>();
2810 const ObjCObjectPointerType* FromObjCPtr2
2811 = FromType2->getAs<ObjCObjectPointerType>();
2812 if (FromObjCPtr1 && FromObjCPtr2) {
2813 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2814 FromObjCPtr2);
2815 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2816 FromObjCPtr1);
2817 if (AssignLeft != AssignRight) {
2818 return AssignLeft? ImplicitConversionSequence::Better
2819 : ImplicitConversionSequence::Worse;
2820 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002821 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002822 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002823
2824 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2825 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002826 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002827 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002828 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002829
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002830 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002831 // Check for a better reference binding based on the kind of bindings.
2832 if (isBetterReferenceBindingKind(SCS1, SCS2))
2833 return ImplicitConversionSequence::Better;
2834 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2835 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002836
Sebastian Redlb28b4072009-03-22 23:49:27 +00002837 // C++ [over.ics.rank]p3b4:
2838 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2839 // which the references refer are the same type except for
2840 // top-level cv-qualifiers, and the type to which the reference
2841 // initialized by S2 refers is more cv-qualified than the type
2842 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002843 QualType T1 = SCS1.getToType(2);
2844 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002845 T1 = S.Context.getCanonicalType(T1);
2846 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002847 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002848 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2849 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002850 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00002851 // Objective-C++ ARC: If the references refer to objects with different
2852 // lifetimes, prefer bindings that don't change lifetime.
2853 if (SCS1.ObjCLifetimeConversionBinding !=
2854 SCS2.ObjCLifetimeConversionBinding) {
2855 return SCS1.ObjCLifetimeConversionBinding
2856 ? ImplicitConversionSequence::Worse
2857 : ImplicitConversionSequence::Better;
2858 }
2859
Chandler Carruth8e543b32010-12-12 08:17:55 +00002860 // If the type is an array type, promote the element qualifiers to the
2861 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002862 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002863 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002864 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002865 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002866 if (T2.isMoreQualifiedThan(T1))
2867 return ImplicitConversionSequence::Better;
2868 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00002869 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002870 }
2871 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002872
Francois Pichet08d2fa02011-09-18 21:37:37 +00002873 // In Microsoft mode, prefer an integral conversion to a
2874 // floating-to-integral conversion if the integral conversion
2875 // is between types of the same size.
2876 // For example:
2877 // void f(float);
2878 // void f(int);
2879 // int main {
2880 // long a;
2881 // f(a);
2882 // }
2883 // Here, MSVC will call f(int) instead of generating a compile error
2884 // as clang will do in standard mode.
2885 if (S.getLangOptions().MicrosoftMode &&
2886 SCS1.Second == ICK_Integral_Conversion &&
2887 SCS2.Second == ICK_Floating_Integral &&
2888 S.Context.getTypeSize(SCS1.getFromType()) ==
2889 S.Context.getTypeSize(SCS1.getToType(2)))
2890 return ImplicitConversionSequence::Better;
2891
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002892 return ImplicitConversionSequence::Indistinguishable;
2893}
2894
2895/// CompareQualificationConversions - Compares two standard conversion
2896/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002897/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2898ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002899CompareQualificationConversions(Sema &S,
2900 const StandardConversionSequence& SCS1,
2901 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002902 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002903 // -- S1 and S2 differ only in their qualification conversion and
2904 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2905 // cv-qualification signature of type T1 is a proper subset of
2906 // the cv-qualification signature of type T2, and S1 is not the
2907 // deprecated string literal array-to-pointer conversion (4.2).
2908 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2909 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2910 return ImplicitConversionSequence::Indistinguishable;
2911
2912 // FIXME: the example in the standard doesn't use a qualification
2913 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002914 QualType T1 = SCS1.getToType(2);
2915 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002916 T1 = S.Context.getCanonicalType(T1);
2917 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002918 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002919 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2920 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002921
2922 // If the types are the same, we won't learn anything by unwrapped
2923 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002924 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002925 return ImplicitConversionSequence::Indistinguishable;
2926
Chandler Carruth607f38e2009-12-29 07:16:59 +00002927 // If the type is an array type, promote the element qualifiers to the type
2928 // for comparison.
2929 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002930 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002931 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002932 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002933
Mike Stump11289f42009-09-09 15:08:12 +00002934 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002935 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00002936
2937 // Objective-C++ ARC:
2938 // Prefer qualification conversions not involving a change in lifetime
2939 // to qualification conversions that do not change lifetime.
2940 if (SCS1.QualificationIncludesObjCLifetime !=
2941 SCS2.QualificationIncludesObjCLifetime) {
2942 Result = SCS1.QualificationIncludesObjCLifetime
2943 ? ImplicitConversionSequence::Worse
2944 : ImplicitConversionSequence::Better;
2945 }
2946
John McCall5c32be02010-08-24 20:38:10 +00002947 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002948 // Within each iteration of the loop, we check the qualifiers to
2949 // determine if this still looks like a qualification
2950 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002951 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002952 // until there are no more pointers or pointers-to-members left
2953 // to unwrap. This essentially mimics what
2954 // IsQualificationConversion does, but here we're checking for a
2955 // strict subset of qualifiers.
2956 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2957 // The qualifiers are the same, so this doesn't tell us anything
2958 // about how the sequences rank.
2959 ;
2960 else if (T2.isMoreQualifiedThan(T1)) {
2961 // T1 has fewer qualifiers, so it could be the better sequence.
2962 if (Result == ImplicitConversionSequence::Worse)
2963 // Neither has qualifiers that are a subset of the other's
2964 // qualifiers.
2965 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002966
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002967 Result = ImplicitConversionSequence::Better;
2968 } else if (T1.isMoreQualifiedThan(T2)) {
2969 // T2 has fewer qualifiers, so it could be the better sequence.
2970 if (Result == ImplicitConversionSequence::Better)
2971 // Neither has qualifiers that are a subset of the other's
2972 // qualifiers.
2973 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002974
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002975 Result = ImplicitConversionSequence::Worse;
2976 } else {
2977 // Qualifiers are disjoint.
2978 return ImplicitConversionSequence::Indistinguishable;
2979 }
2980
2981 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002982 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002983 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002984 }
2985
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002986 // Check that the winning standard conversion sequence isn't using
2987 // the deprecated string literal array to pointer conversion.
2988 switch (Result) {
2989 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002990 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002991 Result = ImplicitConversionSequence::Indistinguishable;
2992 break;
2993
2994 case ImplicitConversionSequence::Indistinguishable:
2995 break;
2996
2997 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002998 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002999 Result = ImplicitConversionSequence::Indistinguishable;
3000 break;
3001 }
3002
3003 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003004}
3005
Douglas Gregor5c407d92008-10-23 00:40:37 +00003006/// CompareDerivedToBaseConversions - Compares two standard conversion
3007/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003008/// various kinds of derived-to-base conversions (C++
3009/// [over.ics.rank]p4b3). As part of these checks, we also look at
3010/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003011ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003012CompareDerivedToBaseConversions(Sema &S,
3013 const StandardConversionSequence& SCS1,
3014 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003015 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003016 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003017 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003018 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003019
3020 // Adjust the types we're converting from via the array-to-pointer
3021 // conversion, if we need to.
3022 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003023 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003024 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003025 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003026
3027 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003028 FromType1 = S.Context.getCanonicalType(FromType1);
3029 ToType1 = S.Context.getCanonicalType(ToType1);
3030 FromType2 = S.Context.getCanonicalType(FromType2);
3031 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003032
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003033 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003034 //
3035 // If class B is derived directly or indirectly from class A and
3036 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003037 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003038 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003039 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003040 SCS2.Second == ICK_Pointer_Conversion &&
3041 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3042 FromType1->isPointerType() && FromType2->isPointerType() &&
3043 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003044 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003045 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003046 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003047 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003048 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003049 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003050 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003051 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003052
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003053 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003054 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003055 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003056 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003057 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003058 return ImplicitConversionSequence::Worse;
3059 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003060
3061 // -- conversion of B* to A* is better than conversion of C* to A*,
3062 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003063 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003064 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003065 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003066 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003067 }
3068 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3069 SCS2.Second == ICK_Pointer_Conversion) {
3070 const ObjCObjectPointerType *FromPtr1
3071 = FromType1->getAs<ObjCObjectPointerType>();
3072 const ObjCObjectPointerType *FromPtr2
3073 = FromType2->getAs<ObjCObjectPointerType>();
3074 const ObjCObjectPointerType *ToPtr1
3075 = ToType1->getAs<ObjCObjectPointerType>();
3076 const ObjCObjectPointerType *ToPtr2
3077 = ToType2->getAs<ObjCObjectPointerType>();
3078
3079 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3080 // Apply the same conversion ranking rules for Objective-C pointer types
3081 // that we do for C++ pointers to class types. However, we employ the
3082 // Objective-C pseudo-subtyping relationship used for assignment of
3083 // Objective-C pointer types.
3084 bool FromAssignLeft
3085 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3086 bool FromAssignRight
3087 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3088 bool ToAssignLeft
3089 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3090 bool ToAssignRight
3091 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3092
3093 // A conversion to an a non-id object pointer type or qualified 'id'
3094 // type is better than a conversion to 'id'.
3095 if (ToPtr1->isObjCIdType() &&
3096 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3097 return ImplicitConversionSequence::Worse;
3098 if (ToPtr2->isObjCIdType() &&
3099 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3100 return ImplicitConversionSequence::Better;
3101
3102 // A conversion to a non-id object pointer type is better than a
3103 // conversion to a qualified 'id' type
3104 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3105 return ImplicitConversionSequence::Worse;
3106 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3107 return ImplicitConversionSequence::Better;
3108
3109 // A conversion to an a non-Class object pointer type or qualified 'Class'
3110 // type is better than a conversion to 'Class'.
3111 if (ToPtr1->isObjCClassType() &&
3112 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3113 return ImplicitConversionSequence::Worse;
3114 if (ToPtr2->isObjCClassType() &&
3115 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3116 return ImplicitConversionSequence::Better;
3117
3118 // A conversion to a non-Class object pointer type is better than a
3119 // conversion to a qualified 'Class' type.
3120 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3121 return ImplicitConversionSequence::Worse;
3122 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3123 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003124
Douglas Gregor058d3de2011-01-31 18:51:41 +00003125 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3126 if (S.Context.hasSameType(FromType1, FromType2) &&
3127 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3128 (ToAssignLeft != ToAssignRight))
3129 return ToAssignLeft? ImplicitConversionSequence::Worse
3130 : ImplicitConversionSequence::Better;
3131
3132 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3133 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3134 (FromAssignLeft != FromAssignRight))
3135 return FromAssignLeft? ImplicitConversionSequence::Better
3136 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003137 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003138 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003139
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003140 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003141 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3142 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3143 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003144 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003145 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003146 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003147 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003148 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003149 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003150 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003151 ToType2->getAs<MemberPointerType>();
3152 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3153 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3154 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3155 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3156 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3157 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3158 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3159 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003160 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003161 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003162 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003163 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003164 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003165 return ImplicitConversionSequence::Better;
3166 }
3167 // conversion of B::* to C::* is better than conversion of A::* to C::*
3168 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003169 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003170 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003171 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003172 return ImplicitConversionSequence::Worse;
3173 }
3174 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003175
Douglas Gregor5ab11652010-04-17 22:01:05 +00003176 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003177 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003178 // -- binding of an expression of type C to a reference of type
3179 // B& is better than binding an expression of type C to a
3180 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003181 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3182 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3183 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003184 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003185 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003186 return ImplicitConversionSequence::Worse;
3187 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003188
Douglas Gregor2fe98832008-11-03 19:09:14 +00003189 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003190 // -- binding of an expression of type B to a reference of type
3191 // A& is better than binding an expression of type C to a
3192 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003193 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3194 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3195 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003196 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003197 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003198 return ImplicitConversionSequence::Worse;
3199 }
3200 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003201
Douglas Gregor5c407d92008-10-23 00:40:37 +00003202 return ImplicitConversionSequence::Indistinguishable;
3203}
3204
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003205/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3206/// determine whether they are reference-related,
3207/// reference-compatible, reference-compatible with added
3208/// qualification, or incompatible, for use in C++ initialization by
3209/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3210/// type, and the first type (T1) is the pointee type of the reference
3211/// type being initialized.
3212Sema::ReferenceCompareResult
3213Sema::CompareReferenceRelationship(SourceLocation Loc,
3214 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003215 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003216 bool &ObjCConversion,
3217 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003218 assert(!OrigT1->isReferenceType() &&
3219 "T1 must be the pointee type of the reference type");
3220 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3221
3222 QualType T1 = Context.getCanonicalType(OrigT1);
3223 QualType T2 = Context.getCanonicalType(OrigT2);
3224 Qualifiers T1Quals, T2Quals;
3225 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3226 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3227
3228 // C++ [dcl.init.ref]p4:
3229 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3230 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3231 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003232 DerivedToBase = false;
3233 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003234 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003235 if (UnqualT1 == UnqualT2) {
3236 // Nothing to do.
3237 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003238 IsDerivedFrom(UnqualT2, UnqualT1))
3239 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003240 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3241 UnqualT2->isObjCObjectOrInterfaceType() &&
3242 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3243 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003244 else
3245 return Ref_Incompatible;
3246
3247 // At this point, we know that T1 and T2 are reference-related (at
3248 // least).
3249
3250 // If the type is an array type, promote the element qualifiers to the type
3251 // for comparison.
3252 if (isa<ArrayType>(T1) && T1Quals)
3253 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3254 if (isa<ArrayType>(T2) && T2Quals)
3255 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3256
3257 // C++ [dcl.init.ref]p4:
3258 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3259 // reference-related to T2 and cv1 is the same cv-qualification
3260 // as, or greater cv-qualification than, cv2. For purposes of
3261 // overload resolution, cases for which cv1 is greater
3262 // cv-qualification than cv2 are identified as
3263 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003264 //
3265 // Note that we also require equivalence of Objective-C GC and address-space
3266 // qualifiers when performing these computations, so that e.g., an int in
3267 // address space 1 is not reference-compatible with an int in address
3268 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003269 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3270 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3271 T1Quals.removeObjCLifetime();
3272 T2Quals.removeObjCLifetime();
3273 ObjCLifetimeConversion = true;
3274 }
3275
Douglas Gregord517d552011-04-28 17:56:11 +00003276 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003277 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003278 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003279 return Ref_Compatible_With_Added_Qualification;
3280 else
3281 return Ref_Related;
3282}
3283
Douglas Gregor836a7e82010-08-11 02:15:33 +00003284/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003285/// with DeclType. Return true if something definite is found.
3286static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003287FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3288 QualType DeclType, SourceLocation DeclLoc,
3289 Expr *Init, QualType T2, bool AllowRvalues,
3290 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003291 assert(T2->isRecordType() && "Can only find conversions of record types.");
3292 CXXRecordDecl *T2RecordDecl
3293 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3294
3295 OverloadCandidateSet CandidateSet(DeclLoc);
3296 const UnresolvedSetImpl *Conversions
3297 = T2RecordDecl->getVisibleConversionFunctions();
3298 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3299 E = Conversions->end(); I != E; ++I) {
3300 NamedDecl *D = *I;
3301 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3302 if (isa<UsingShadowDecl>(D))
3303 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3304
3305 FunctionTemplateDecl *ConvTemplate
3306 = dyn_cast<FunctionTemplateDecl>(D);
3307 CXXConversionDecl *Conv;
3308 if (ConvTemplate)
3309 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3310 else
3311 Conv = cast<CXXConversionDecl>(D);
3312
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003313 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003314 // explicit conversions, skip it.
3315 if (!AllowExplicit && Conv->isExplicit())
3316 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003317
Douglas Gregor836a7e82010-08-11 02:15:33 +00003318 if (AllowRvalues) {
3319 bool DerivedToBase = false;
3320 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003321 bool ObjCLifetimeConversion = false;
Douglas Gregor836a7e82010-08-11 02:15:33 +00003322 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003323 S.CompareReferenceRelationship(
3324 DeclLoc,
3325 Conv->getConversionType().getNonReferenceType()
3326 .getUnqualifiedType(),
3327 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003328 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003329 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003330 continue;
3331 } else {
3332 // If the conversion function doesn't return a reference type,
3333 // it can't be considered for this conversion. An rvalue reference
3334 // is only acceptable if its referencee is a function type.
3335
3336 const ReferenceType *RefType =
3337 Conv->getConversionType()->getAs<ReferenceType>();
3338 if (!RefType ||
3339 (!RefType->isLValueReferenceType() &&
3340 !RefType->getPointeeType()->isFunctionType()))
3341 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003342 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003343
Douglas Gregor836a7e82010-08-11 02:15:33 +00003344 if (ConvTemplate)
3345 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003346 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003347 else
3348 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003349 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003350 }
3351
3352 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003353 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003354 case OR_Success:
3355 // C++ [over.ics.ref]p1:
3356 //
3357 // [...] If the parameter binds directly to the result of
3358 // applying a conversion function to the argument
3359 // expression, the implicit conversion sequence is a
3360 // user-defined conversion sequence (13.3.3.1.2), with the
3361 // second standard conversion sequence either an identity
3362 // conversion or, if the conversion function returns an
3363 // entity of a type that is a derived class of the parameter
3364 // type, a derived-to-base Conversion.
3365 if (!Best->FinalConversion.DirectBinding)
3366 return false;
3367
Chandler Carruth30141632011-02-25 19:41:05 +00003368 if (Best->Function)
3369 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003370 ICS.setUserDefined();
3371 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3372 ICS.UserDefined.After = Best->FinalConversion;
3373 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003374 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003375 ICS.UserDefined.EllipsisConversion = false;
3376 assert(ICS.UserDefined.After.ReferenceBinding &&
3377 ICS.UserDefined.After.DirectBinding &&
3378 "Expected a direct reference binding!");
3379 return true;
3380
3381 case OR_Ambiguous:
3382 ICS.setAmbiguous();
3383 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3384 Cand != CandidateSet.end(); ++Cand)
3385 if (Cand->Viable)
3386 ICS.Ambiguous.addConversion(Cand->Function);
3387 return true;
3388
3389 case OR_No_Viable_Function:
3390 case OR_Deleted:
3391 // There was no suitable conversion, or we found a deleted
3392 // conversion; continue with other checks.
3393 return false;
3394 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003395
Eric Christopheraba9fb22010-06-30 18:36:32 +00003396 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003397}
3398
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003399/// \brief Compute an implicit conversion sequence for reference
3400/// initialization.
3401static ImplicitConversionSequence
3402TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3403 SourceLocation DeclLoc,
3404 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003405 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003406 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3407
3408 // Most paths end in a failed conversion.
3409 ImplicitConversionSequence ICS;
3410 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3411
3412 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3413 QualType T2 = Init->getType();
3414
3415 // If the initializer is the address of an overloaded function, try
3416 // to resolve the overloaded function. If all goes well, T2 is the
3417 // type of the resulting function.
3418 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3419 DeclAccessPair Found;
3420 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3421 false, Found))
3422 T2 = Fn->getType();
3423 }
3424
3425 // Compute some basic properties of the types and the initializer.
3426 bool isRValRef = DeclType->isRValueReferenceType();
3427 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003428 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003429 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003430 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003431 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003432 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003433 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003434
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003435
Sebastian Redld92badf2010-06-30 18:13:39 +00003436 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003437 // A reference to type "cv1 T1" is initialized by an expression
3438 // of type "cv2 T2" as follows:
3439
Sebastian Redld92badf2010-06-30 18:13:39 +00003440 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003441 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003442 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3443 // reference-compatible with "cv2 T2," or
3444 //
3445 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3446 if (InitCategory.isLValue() &&
3447 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003448 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003449 // When a parameter of reference type binds directly (8.5.3)
3450 // to an argument expression, the implicit conversion sequence
3451 // is the identity conversion, unless the argument expression
3452 // has a type that is a derived class of the parameter type,
3453 // in which case the implicit conversion sequence is a
3454 // derived-to-base Conversion (13.3.3.1).
3455 ICS.setStandard();
3456 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003457 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3458 : ObjCConversion? ICK_Compatible_Conversion
3459 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003460 ICS.Standard.Third = ICK_Identity;
3461 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3462 ICS.Standard.setToType(0, T2);
3463 ICS.Standard.setToType(1, T1);
3464 ICS.Standard.setToType(2, T1);
3465 ICS.Standard.ReferenceBinding = true;
3466 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003467 ICS.Standard.IsLvalueReference = !isRValRef;
3468 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3469 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003470 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003471 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003472 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003473
Sebastian Redld92badf2010-06-30 18:13:39 +00003474 // Nothing more to do: the inaccessibility/ambiguity check for
3475 // derived-to-base conversions is suppressed when we're
3476 // computing the implicit conversion sequence (C++
3477 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003478 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003479 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003480
Sebastian Redld92badf2010-06-30 18:13:39 +00003481 // -- has a class type (i.e., T2 is a class type), where T1 is
3482 // not reference-related to T2, and can be implicitly
3483 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3484 // is reference-compatible with "cv3 T3" 92) (this
3485 // conversion is selected by enumerating the applicable
3486 // conversion functions (13.3.1.6) and choosing the best
3487 // one through overload resolution (13.3)),
3488 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003489 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003490 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003491 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3492 Init, T2, /*AllowRvalues=*/false,
3493 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003494 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003495 }
3496 }
3497
Sebastian Redld92badf2010-06-30 18:13:39 +00003498 // -- Otherwise, the reference shall be an lvalue reference to a
3499 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003500 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003502 // We actually handle one oddity of C++ [over.ics.ref] at this
3503 // point, which is that, due to p2 (which short-circuits reference
3504 // binding by only attempting a simple conversion for non-direct
3505 // bindings) and p3's strange wording, we allow a const volatile
3506 // reference to bind to an rvalue. Hence the check for the presence
3507 // of "const" rather than checking for "const" being the only
3508 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003509 // This is also the point where rvalue references and lvalue inits no longer
3510 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003511 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003512 return ICS;
3513
Douglas Gregorf143cd52011-01-24 16:14:37 +00003514 // -- If the initializer expression
3515 //
3516 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003517 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003518 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3519 (InitCategory.isXValue() ||
3520 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3521 (InitCategory.isLValue() && T2->isFunctionType()))) {
3522 ICS.setStandard();
3523 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003524 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003525 : ObjCConversion? ICK_Compatible_Conversion
3526 : ICK_Identity;
3527 ICS.Standard.Third = ICK_Identity;
3528 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3529 ICS.Standard.setToType(0, T2);
3530 ICS.Standard.setToType(1, T1);
3531 ICS.Standard.setToType(2, T1);
3532 ICS.Standard.ReferenceBinding = true;
3533 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3534 // binding unless we're binding to a class prvalue.
3535 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3536 // allow the use of rvalue references in C++98/03 for the benefit of
3537 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003538 ICS.Standard.DirectBinding =
3539 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003540 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003541 ICS.Standard.IsLvalueReference = !isRValRef;
3542 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003543 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003544 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003545 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003546 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003547 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003548 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003549
Douglas Gregorf143cd52011-01-24 16:14:37 +00003550 // -- has a class type (i.e., T2 is a class type), where T1 is not
3551 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003552 // an xvalue, class prvalue, or function lvalue of type
3553 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003554 // "cv3 T3",
3555 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003556 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003557 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003558 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003559 // class subobject).
3560 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003561 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003562 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3563 Init, T2, /*AllowRvalues=*/true,
3564 AllowExplicit)) {
3565 // In the second case, if the reference is an rvalue reference
3566 // and the second standard conversion sequence of the
3567 // user-defined conversion sequence includes an lvalue-to-rvalue
3568 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003569 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003570 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3571 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3572
Douglas Gregor95273c32011-01-21 16:36:05 +00003573 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003574 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003575
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003576 // -- Otherwise, a temporary of type "cv1 T1" is created and
3577 // initialized from the initializer expression using the
3578 // rules for a non-reference copy initialization (8.5). The
3579 // reference is then bound to the temporary. If T1 is
3580 // reference-related to T2, cv1 must be the same
3581 // cv-qualification as, or greater cv-qualification than,
3582 // cv2; otherwise, the program is ill-formed.
3583 if (RefRelationship == Sema::Ref_Related) {
3584 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3585 // we would be reference-compatible or reference-compatible with
3586 // added qualification. But that wasn't the case, so the reference
3587 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00003588 //
3589 // Note that we only want to check address spaces and cvr-qualifiers here.
3590 // ObjC GC and lifetime qualifiers aren't important.
3591 Qualifiers T1Quals = T1.getQualifiers();
3592 Qualifiers T2Quals = T2.getQualifiers();
3593 T1Quals.removeObjCGCAttr();
3594 T1Quals.removeObjCLifetime();
3595 T2Quals.removeObjCGCAttr();
3596 T2Quals.removeObjCLifetime();
3597 if (!T1Quals.compatiblyIncludes(T2Quals))
3598 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003599 }
3600
3601 // If at least one of the types is a class type, the types are not
3602 // related, and we aren't allowed any user conversions, the
3603 // reference binding fails. This case is important for breaking
3604 // recursion, since TryImplicitConversion below will attempt to
3605 // create a temporary through the use of a copy constructor.
3606 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3607 (T1->isRecordType() || T2->isRecordType()))
3608 return ICS;
3609
Douglas Gregorcba72b12011-01-21 05:18:22 +00003610 // If T1 is reference-related to T2 and the reference is an rvalue
3611 // reference, the initializer expression shall not be an lvalue.
3612 if (RefRelationship >= Sema::Ref_Related &&
3613 isRValRef && Init->Classify(S.Context).isLValue())
3614 return ICS;
3615
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003616 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003617 // When a parameter of reference type is not bound directly to
3618 // an argument expression, the conversion sequence is the one
3619 // required to convert the argument expression to the
3620 // underlying type of the reference according to
3621 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3622 // to copy-initializing a temporary of the underlying type with
3623 // the argument expression. Any difference in top-level
3624 // cv-qualification is subsumed by the initialization itself
3625 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003626 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3627 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003628 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003629 /*CStyle=*/false,
3630 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003631
3632 // Of course, that's still a reference binding.
3633 if (ICS.isStandard()) {
3634 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003635 ICS.Standard.IsLvalueReference = !isRValRef;
3636 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3637 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003638 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003639 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003640 } else if (ICS.isUserDefined()) {
3641 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00003642 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3643 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3644 ICS.UserDefined.After.BindsToRvalue = true;
3645 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3646 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003647 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003648
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003649 return ICS;
3650}
3651
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003652/// TryCopyInitialization - Try to copy-initialize a value of type
3653/// ToType from the expression From. Return the implicit conversion
3654/// sequence required to pass this argument, which may be a bad
3655/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003656/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003657/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003658static ImplicitConversionSequence
3659TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003660 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00003661 bool InOverloadResolution,
3662 bool AllowObjCWritebackConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003663 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003664 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003665 /*FIXME:*/From->getLocStart(),
3666 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003667 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003668
John McCall5c32be02010-08-24 20:38:10 +00003669 return TryImplicitConversion(S, From, ToType,
3670 SuppressUserConversions,
3671 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003672 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00003673 /*CStyle=*/false,
3674 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003675}
3676
Anna Zaks1b068122011-07-28 19:46:48 +00003677static bool TryCopyInitialization(const CanQualType FromQTy,
3678 const CanQualType ToQTy,
3679 Sema &S,
3680 SourceLocation Loc,
3681 ExprValueKind FromVK) {
3682 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
3683 ImplicitConversionSequence ICS =
3684 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
3685
3686 return !ICS.isBad();
3687}
3688
Douglas Gregor436424c2008-11-18 23:14:02 +00003689/// TryObjectArgumentInitialization - Try to initialize the object
3690/// parameter of the given member function (@c Method) from the
3691/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003692static ImplicitConversionSequence
3693TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003694 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003695 CXXMethodDecl *Method,
3696 CXXRecordDecl *ActingContext) {
3697 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003698 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3699 // const volatile object.
3700 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3701 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003702 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003703
3704 // Set up the conversion sequence as a "bad" conversion, to allow us
3705 // to exit early.
3706 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003707
3708 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003709 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003710 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003711 FromType = PT->getPointeeType();
3712
Douglas Gregor02824322011-01-26 19:30:28 +00003713 // When we had a pointer, it's implicitly dereferenced, so we
3714 // better have an lvalue.
3715 assert(FromClassification.isLValue());
3716 }
3717
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003718 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003719
Douglas Gregor02824322011-01-26 19:30:28 +00003720 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003721 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003722 // parameter is
3723 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003724 // - "lvalue reference to cv X" for functions declared without a
3725 // ref-qualifier or with the & ref-qualifier
3726 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003727 // ref-qualifier
3728 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003729 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003730 // cv-qualification on the member function declaration.
3731 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003732 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003733 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003734 // (C++ [over.match.funcs]p5). We perform a simplified version of
3735 // reference binding here, that allows class rvalues to bind to
3736 // non-constant references.
3737
Douglas Gregor02824322011-01-26 19:30:28 +00003738 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003739 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003740 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003741 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003742 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003743 ICS.setBad(BadConversionSequence::bad_qualifiers,
3744 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003745 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003746 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003747
3748 // Check that we have either the same type or a derived type. It
3749 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003750 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003751 ImplicitConversionKind SecondKind;
3752 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3753 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003754 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003755 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003756 else {
John McCall65eb8792010-02-25 01:37:24 +00003757 ICS.setBad(BadConversionSequence::unrelated_class,
3758 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003759 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003760 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003761
Douglas Gregor02824322011-01-26 19:30:28 +00003762 // Check the ref-qualifier.
3763 switch (Method->getRefQualifier()) {
3764 case RQ_None:
3765 // Do nothing; we don't care about lvalueness or rvalueness.
3766 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003767
Douglas Gregor02824322011-01-26 19:30:28 +00003768 case RQ_LValue:
3769 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3770 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003771 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003772 ImplicitParamType);
3773 return ICS;
3774 }
3775 break;
3776
3777 case RQ_RValue:
3778 if (!FromClassification.isRValue()) {
3779 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003780 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003781 ImplicitParamType);
3782 return ICS;
3783 }
3784 break;
3785 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003786
Douglas Gregor436424c2008-11-18 23:14:02 +00003787 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003788 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003789 ICS.Standard.setAsIdentityConversion();
3790 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003791 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003792 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003793 ICS.Standard.ReferenceBinding = true;
3794 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003795 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003796 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003797 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3798 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3799 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003800 return ICS;
3801}
3802
3803/// PerformObjectArgumentInitialization - Perform initialization of
3804/// the implicit object parameter for the given Method with the given
3805/// expression.
John Wiegley01296292011-04-08 18:41:53 +00003806ExprResult
3807Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003808 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003809 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003810 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003811 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003812 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003813 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003814
Douglas Gregor02824322011-01-26 19:30:28 +00003815 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003816 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003817 FromRecordType = PT->getPointeeType();
3818 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003819 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003820 } else {
3821 FromRecordType = From->getType();
3822 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003823 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003824 }
3825
John McCall6e9f8f62009-12-03 04:06:58 +00003826 // Note that we always use the true parent context when performing
3827 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003828 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003829 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3830 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003831 if (ICS.isBad()) {
3832 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3833 Qualifiers FromQs = FromRecordType.getQualifiers();
3834 Qualifiers ToQs = DestType.getQualifiers();
3835 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3836 if (CVR) {
3837 Diag(From->getSourceRange().getBegin(),
3838 diag::err_member_function_call_bad_cvr)
3839 << Method->getDeclName() << FromRecordType << (CVR - 1)
3840 << From->getSourceRange();
3841 Diag(Method->getLocation(), diag::note_previous_decl)
3842 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00003843 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003844 }
3845 }
3846
Douglas Gregor436424c2008-11-18 23:14:02 +00003847 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003848 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003849 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003850 }
Mike Stump11289f42009-09-09 15:08:12 +00003851
John Wiegley01296292011-04-08 18:41:53 +00003852 if (ICS.Standard.Second == ICK_Derived_To_Base) {
3853 ExprResult FromRes =
3854 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3855 if (FromRes.isInvalid())
3856 return ExprError();
3857 From = FromRes.take();
3858 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003859
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003860 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00003861 From = ImpCastExprToType(From, DestType, CK_NoOp,
3862 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3863 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00003864}
3865
Douglas Gregor5fb53972009-01-14 15:45:31 +00003866/// TryContextuallyConvertToBool - Attempt to contextually convert the
3867/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003868static ImplicitConversionSequence
3869TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003870 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003871 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003872 // FIXME: Are these flags correct?
3873 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003874 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003875 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003876 /*CStyle=*/false,
3877 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003878}
3879
3880/// PerformContextuallyConvertToBool - Perform a contextual conversion
3881/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00003882ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00003883 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003884 if (!ICS.isBad())
3885 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003886
Fariborz Jahanian76197412009-11-18 18:26:29 +00003887 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00003888 return Diag(From->getSourceRange().getBegin(),
3889 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003890 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003891 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00003892}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003893
John McCallfec112d2011-09-09 06:11:02 +00003894/// dropPointerConversions - If the given standard conversion sequence
3895/// involves any pointer conversions, remove them. This may change
3896/// the result type of the conversion sequence.
3897static void dropPointerConversion(StandardConversionSequence &SCS) {
3898 if (SCS.Second == ICK_Pointer_Conversion) {
3899 SCS.Second = ICK_Identity;
3900 SCS.Third = ICK_Identity;
3901 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
3902 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003903}
John McCall5c32be02010-08-24 20:38:10 +00003904
John McCallfec112d2011-09-09 06:11:02 +00003905/// TryContextuallyConvertToObjCPointer - Attempt to contextually
3906/// convert the expression From to an Objective-C pointer type.
3907static ImplicitConversionSequence
3908TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
3909 // Do an implicit conversion to 'id'.
3910 QualType Ty = S.Context.getObjCIdType();
3911 ImplicitConversionSequence ICS
3912 = TryImplicitConversion(S, From, Ty,
3913 // FIXME: Are these flags correct?
3914 /*SuppressUserConversions=*/false,
3915 /*AllowExplicit=*/true,
3916 /*InOverloadResolution=*/false,
3917 /*CStyle=*/false,
3918 /*AllowObjCWritebackConversion=*/false);
3919
3920 // Strip off any final conversions to 'id'.
3921 switch (ICS.getKind()) {
3922 case ImplicitConversionSequence::BadConversion:
3923 case ImplicitConversionSequence::AmbiguousConversion:
3924 case ImplicitConversionSequence::EllipsisConversion:
3925 break;
3926
3927 case ImplicitConversionSequence::UserDefinedConversion:
3928 dropPointerConversion(ICS.UserDefined.After);
3929 break;
3930
3931 case ImplicitConversionSequence::StandardConversion:
3932 dropPointerConversion(ICS.Standard);
3933 break;
3934 }
3935
3936 return ICS;
3937}
3938
3939/// PerformContextuallyConvertToObjCPointer - Perform a contextual
3940/// conversion of the expression From to an Objective-C pointer type.
3941ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003942 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00003943 ImplicitConversionSequence ICS =
3944 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003945 if (!ICS.isBad())
3946 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00003947 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003948}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003949
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003950/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003951/// enumeration type.
3952///
3953/// This routine will attempt to convert an expression of class type to an
3954/// integral or enumeration type, if that class type only has a single
3955/// conversion to an integral or enumeration type.
3956///
Douglas Gregor4799d032010-06-30 00:20:43 +00003957/// \param Loc The source location of the construct that requires the
3958/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003959///
Douglas Gregor4799d032010-06-30 00:20:43 +00003960/// \param FromE The expression we're converting from.
3961///
3962/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3963/// have integral or enumeration type.
3964///
3965/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3966/// incomplete class type.
3967///
3968/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3969/// explicit conversion function (because no implicit conversion functions
3970/// were available). This is a recovery mode.
3971///
3972/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3973/// showing which conversion was picked.
3974///
3975/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3976/// conversion function that could convert to integral or enumeration type.
3977///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003978/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00003979/// usable conversion function.
3980///
3981/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3982/// function, which may be an extension in this case.
3983///
3984/// \returns The expression, converted to an integral or enumeration type if
3985/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003986ExprResult
John McCallb268a282010-08-23 23:25:46 +00003987Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003988 const PartialDiagnostic &NotIntDiag,
3989 const PartialDiagnostic &IncompleteDiag,
3990 const PartialDiagnostic &ExplicitConvDiag,
3991 const PartialDiagnostic &ExplicitConvNote,
3992 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003993 const PartialDiagnostic &AmbigNote,
3994 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003995 // We can't perform any more checking for type-dependent expressions.
3996 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003997 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003998
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003999 // If the expression already has integral or enumeration type, we're golden.
4000 QualType T = From->getType();
4001 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00004002 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004003
4004 // FIXME: Check for missing '()' if T is a function type?
4005
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004006 // 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 +00004007 // expression of integral or enumeration type.
4008 const RecordType *RecordTy = T->getAs<RecordType>();
4009 if (!RecordTy || !getLangOptions().CPlusPlus) {
4010 Diag(Loc, NotIntDiag)
4011 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004012 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004013 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004014
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004015 // We must have a complete class type.
4016 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004017 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004018
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004019 // Look for a conversion to an integral or enumeration type.
4020 UnresolvedSet<4> ViableConversions;
4021 UnresolvedSet<4> ExplicitConversions;
4022 const UnresolvedSetImpl *Conversions
4023 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004024
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004025 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004026 E = Conversions->end();
4027 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004028 ++I) {
4029 if (CXXConversionDecl *Conversion
4030 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4031 if (Conversion->getConversionType().getNonReferenceType()
4032 ->isIntegralOrEnumerationType()) {
4033 if (Conversion->isExplicit())
4034 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4035 else
4036 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4037 }
4038 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004040 switch (ViableConversions.size()) {
4041 case 0:
4042 if (ExplicitConversions.size() == 1) {
4043 DeclAccessPair Found = ExplicitConversions[0];
4044 CXXConversionDecl *Conversion
4045 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004046
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004047 // The user probably meant to invoke the given explicit
4048 // conversion; use it.
4049 QualType ConvTy
4050 = Conversion->getConversionType().getNonReferenceType();
4051 std::string TypeStr;
4052 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004053
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004054 Diag(Loc, ExplicitConvDiag)
4055 << T << ConvTy
4056 << FixItHint::CreateInsertion(From->getLocStart(),
4057 "static_cast<" + TypeStr + ">(")
4058 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4059 ")");
4060 Diag(Conversion->getLocation(), ExplicitConvNote)
4061 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004062
4063 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004064 // explicit conversion function.
4065 if (isSFINAEContext())
4066 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004067
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004068 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00004069 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
4070 if (Result.isInvalid())
4071 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004072
Douglas Gregor668443e2011-01-20 00:18:04 +00004073 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004074 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004075
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004076 // We'll complain below about a non-integral condition type.
4077 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004078
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004079 case 1: {
4080 // Apply this conversion.
4081 DeclAccessPair Found = ViableConversions[0];
4082 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004083
Douglas Gregor4799d032010-06-30 00:20:43 +00004084 CXXConversionDecl *Conversion
4085 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4086 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004087 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004088 if (ConvDiag.getDiagID()) {
4089 if (isSFINAEContext())
4090 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004091
Douglas Gregor4799d032010-06-30 00:20:43 +00004092 Diag(Loc, ConvDiag)
4093 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4094 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004095
Douglas Gregor668443e2011-01-20 00:18:04 +00004096 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004097 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00004098 if (Result.isInvalid())
4099 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004100
Douglas Gregor668443e2011-01-20 00:18:04 +00004101 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004102 break;
4103 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004104
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004105 default:
4106 Diag(Loc, AmbigDiag)
4107 << T << From->getSourceRange();
4108 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4109 CXXConversionDecl *Conv
4110 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4111 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4112 Diag(Conv->getLocation(), AmbigNote)
4113 << ConvTy->isEnumeralType() << ConvTy;
4114 }
John McCallb268a282010-08-23 23:25:46 +00004115 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004116 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004117
Douglas Gregor5823da32010-06-29 23:25:20 +00004118 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004119 Diag(Loc, NotIntDiag)
4120 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004121
John McCallb268a282010-08-23 23:25:46 +00004122 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004123}
4124
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004125/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004126/// candidate functions, using the given function call arguments. If
4127/// @p SuppressUserConversions, then don't allow user-defined
4128/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004129///
4130/// \para PartialOverloading true if we are performing "partial" overloading
4131/// based on an incomplete set of function arguments. This feature is used by
4132/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004133void
4134Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004135 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004136 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004137 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004138 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004139 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004140 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004141 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004142 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004143 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004144 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004145
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004146 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004147 if (!isa<CXXConstructorDecl>(Method)) {
4148 // If we get here, it's because we're calling a member function
4149 // that is named without a member access expression (e.g.,
4150 // "this->f") that was either written explicitly or created
4151 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004152 // function, e.g., X::f(). We use an empty type for the implied
4153 // object argument (C++ [over.call.func]p3), and the acting context
4154 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004155 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004156 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004157 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004158 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004159 return;
4160 }
4161 // We treat a constructor like a non-member function, since its object
4162 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004163 }
4164
Douglas Gregorff7028a2009-11-13 23:59:09 +00004165 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004166 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004167
Douglas Gregor27381f32009-11-23 12:27:39 +00004168 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004169 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004170
Douglas Gregorffe14e32009-11-14 01:20:54 +00004171 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4172 // C++ [class.copy]p3:
4173 // A member function template is never instantiated to perform the copy
4174 // of a class object to an object of its class type.
4175 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004176 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004177 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004178 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4179 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004180 return;
4181 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004182
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004183 // Add this candidate
4184 CandidateSet.push_back(OverloadCandidate());
4185 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004186 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004187 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004188 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004189 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004190 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004191 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004192
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004193 unsigned NumArgsInProto = Proto->getNumArgs();
4194
4195 // (C++ 13.3.2p2): A candidate function having fewer than m
4196 // parameters is viable only if it has an ellipsis in its parameter
4197 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004198 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004199 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004200 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004201 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004202 return;
4203 }
4204
4205 // (C++ 13.3.2p2): A candidate function having more than m parameters
4206 // is viable only if the (m+1)st parameter has a default argument
4207 // (8.3.6). For the purposes of overload resolution, the
4208 // parameter list is truncated on the right, so that there are
4209 // exactly m parameters.
4210 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004211 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004212 // Not enough arguments.
4213 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004214 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004215 return;
4216 }
4217
4218 // Determine the implicit conversion sequences for each of the
4219 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004220 Candidate.Conversions.resize(NumArgs);
4221 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4222 if (ArgIdx < NumArgsInProto) {
4223 // (C++ 13.3.2p3): for F to be a viable function, there shall
4224 // exist for each argument an implicit conversion sequence
4225 // (13.3.3.1) that converts that argument to the corresponding
4226 // parameter of F.
4227 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004228 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004229 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004230 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004231 /*InOverloadResolution=*/true,
4232 /*AllowObjCWritebackConversion=*/
4233 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004234 if (Candidate.Conversions[ArgIdx].isBad()) {
4235 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004236 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004237 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004238 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004239 } else {
4240 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4241 // argument for which there is no corresponding parameter is
4242 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004243 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004244 }
4245 }
4246}
4247
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004248/// \brief Add all of the function declarations in the given function set to
4249/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004250void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004251 Expr **Args, unsigned NumArgs,
4252 OverloadCandidateSet& CandidateSet,
4253 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004254 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004255 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4256 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004257 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004258 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004259 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004260 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004261 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004262 CandidateSet, SuppressUserConversions);
4263 else
John McCalla0296f72010-03-19 07:35:19 +00004264 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004265 SuppressUserConversions);
4266 } else {
John McCalla0296f72010-03-19 07:35:19 +00004267 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004268 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4269 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004270 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004271 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004272 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004273 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004274 Args[0]->Classify(Context),
4275 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004276 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004277 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004278 else
John McCalla0296f72010-03-19 07:35:19 +00004279 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004280 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004281 Args, NumArgs, CandidateSet,
4282 SuppressUserConversions);
4283 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004284 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004285}
4286
John McCallf0f1cf02009-11-17 07:50:12 +00004287/// AddMethodCandidate - Adds a named decl (which is some kind of
4288/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004289void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004290 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004291 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004292 Expr **Args, unsigned NumArgs,
4293 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004294 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004295 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004296 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004297
4298 if (isa<UsingShadowDecl>(Decl))
4299 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004300
John McCallf0f1cf02009-11-17 07:50:12 +00004301 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4302 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4303 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004304 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4305 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004306 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004307 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004308 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004309 } else {
John McCalla0296f72010-03-19 07:35:19 +00004310 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004311 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004312 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004313 }
4314}
4315
Douglas Gregor436424c2008-11-18 23:14:02 +00004316/// AddMethodCandidate - Adds the given C++ member function to the set
4317/// of candidate functions, using the given function call arguments
4318/// and the object argument (@c Object). For example, in a call
4319/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4320/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4321/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004322/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004323void
John McCalla0296f72010-03-19 07:35:19 +00004324Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004325 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004326 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004327 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004328 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004329 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004330 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004331 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004332 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004333 assert(!isa<CXXConstructorDecl>(Method) &&
4334 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004335
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004336 if (!CandidateSet.isNewCandidate(Method))
4337 return;
4338
Douglas Gregor27381f32009-11-23 12:27:39 +00004339 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004340 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004341
Douglas Gregor436424c2008-11-18 23:14:02 +00004342 // Add this candidate
4343 CandidateSet.push_back(OverloadCandidate());
4344 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004345 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004346 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004347 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004348 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004349 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004350
4351 unsigned NumArgsInProto = Proto->getNumArgs();
4352
4353 // (C++ 13.3.2p2): A candidate function having fewer than m
4354 // parameters is viable only if it has an ellipsis in its parameter
4355 // list (8.3.5).
4356 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4357 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004358 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004359 return;
4360 }
4361
4362 // (C++ 13.3.2p2): A candidate function having more than m parameters
4363 // is viable only if the (m+1)st parameter has a default argument
4364 // (8.3.6). For the purposes of overload resolution, the
4365 // parameter list is truncated on the right, so that there are
4366 // exactly m parameters.
4367 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4368 if (NumArgs < MinRequiredArgs) {
4369 // Not enough arguments.
4370 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004371 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004372 return;
4373 }
4374
4375 Candidate.Viable = true;
4376 Candidate.Conversions.resize(NumArgs + 1);
4377
John McCall6e9f8f62009-12-03 04:06:58 +00004378 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004379 // The implicit object argument is ignored.
4380 Candidate.IgnoreObjectArgument = true;
4381 else {
4382 // Determine the implicit conversion sequence for the object
4383 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004384 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004385 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4386 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004387 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004388 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004389 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004390 return;
4391 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004392 }
4393
4394 // Determine the implicit conversion sequences for each of the
4395 // arguments.
4396 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4397 if (ArgIdx < NumArgsInProto) {
4398 // (C++ 13.3.2p3): for F to be a viable function, there shall
4399 // exist for each argument an implicit conversion sequence
4400 // (13.3.3.1) that converts that argument to the corresponding
4401 // parameter of F.
4402 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004403 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004404 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004405 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004406 /*InOverloadResolution=*/true,
4407 /*AllowObjCWritebackConversion=*/
4408 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004409 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004410 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004411 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004412 break;
4413 }
4414 } else {
4415 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4416 // argument for which there is no corresponding parameter is
4417 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004418 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004419 }
4420 }
4421}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004422
Douglas Gregor97628d62009-08-21 00:16:32 +00004423/// \brief Add a C++ member function template as a candidate to the candidate
4424/// set, using template argument deduction to produce an appropriate member
4425/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004426void
Douglas Gregor97628d62009-08-21 00:16:32 +00004427Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004428 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004429 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004430 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004431 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004432 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004433 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004434 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004435 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004436 if (!CandidateSet.isNewCandidate(MethodTmpl))
4437 return;
4438
Douglas Gregor97628d62009-08-21 00:16:32 +00004439 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004440 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004441 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004442 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004443 // candidate functions in the usual way.113) A given name can refer to one
4444 // or more function templates and also to a set of overloaded non-template
4445 // functions. In such a case, the candidate functions generated from each
4446 // function template are combined with the set of non-template candidate
4447 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004448 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004449 FunctionDecl *Specialization = 0;
4450 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004451 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004452 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004453 CandidateSet.push_back(OverloadCandidate());
4454 OverloadCandidate &Candidate = CandidateSet.back();
4455 Candidate.FoundDecl = FoundDecl;
4456 Candidate.Function = MethodTmpl->getTemplatedDecl();
4457 Candidate.Viable = false;
4458 Candidate.FailureKind = ovl_fail_bad_deduction;
4459 Candidate.IsSurrogate = false;
4460 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004461 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004462 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004463 Info);
4464 return;
4465 }
Mike Stump11289f42009-09-09 15:08:12 +00004466
Douglas Gregor97628d62009-08-21 00:16:32 +00004467 // Add the function template specialization produced by template argument
4468 // deduction as a candidate.
4469 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004470 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004471 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004472 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004473 ActingContext, ObjectType, ObjectClassification,
4474 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004475}
4476
Douglas Gregor05155d82009-08-21 23:19:43 +00004477/// \brief Add a C++ function template specialization as a candidate
4478/// in the candidate set, using template argument deduction to produce
4479/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004480void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004481Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004482 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004483 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004484 Expr **Args, unsigned NumArgs,
4485 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004486 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004487 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4488 return;
4489
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004490 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004491 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004492 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004493 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004494 // candidate functions in the usual way.113) A given name can refer to one
4495 // or more function templates and also to a set of overloaded non-template
4496 // functions. In such a case, the candidate functions generated from each
4497 // function template are combined with the set of non-template candidate
4498 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004499 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004500 FunctionDecl *Specialization = 0;
4501 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004502 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004503 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004504 CandidateSet.push_back(OverloadCandidate());
4505 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004506 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004507 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4508 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004509 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004510 Candidate.IsSurrogate = false;
4511 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004512 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004513 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004514 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004515 return;
4516 }
Mike Stump11289f42009-09-09 15:08:12 +00004517
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004518 // Add the function template specialization produced by template argument
4519 // deduction as a candidate.
4520 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004521 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004522 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004523}
Mike Stump11289f42009-09-09 15:08:12 +00004524
Douglas Gregora1f013e2008-11-07 22:36:19 +00004525/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004526/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004527/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004528/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004529/// (which may or may not be the same type as the type that the
4530/// conversion function produces).
4531void
4532Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004533 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004534 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004535 Expr *From, QualType ToType,
4536 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004537 assert(!Conversion->getDescribedFunctionTemplate() &&
4538 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004539 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004540 if (!CandidateSet.isNewCandidate(Conversion))
4541 return;
4542
Douglas Gregor27381f32009-11-23 12:27:39 +00004543 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004544 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004545
Douglas Gregora1f013e2008-11-07 22:36:19 +00004546 // Add this candidate
4547 CandidateSet.push_back(OverloadCandidate());
4548 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004549 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004550 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004551 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004552 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004553 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004554 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004555 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004556 Candidate.Viable = true;
4557 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004558 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004559
Douglas Gregor6affc782010-08-19 15:37:02 +00004560 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004561 // For conversion functions, the function is considered to be a member of
4562 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004563 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004564 //
4565 // Determine the implicit conversion sequence for the implicit
4566 // object parameter.
4567 QualType ImplicitParamType = From->getType();
4568 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4569 ImplicitParamType = FromPtrType->getPointeeType();
4570 CXXRecordDecl *ConversionContext
4571 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004572
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004573 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004574 = TryObjectArgumentInitialization(*this, From->getType(),
4575 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004576 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004577
John McCall0d1da222010-01-12 00:44:57 +00004578 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004579 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004580 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004581 return;
4582 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004583
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004584 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004585 // derived to base as such conversions are given Conversion Rank. They only
4586 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4587 QualType FromCanon
4588 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4589 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4590 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4591 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004592 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004593 return;
4594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004595
Douglas Gregora1f013e2008-11-07 22:36:19 +00004596 // To determine what the conversion from the result of calling the
4597 // conversion function to the type we're eventually trying to
4598 // convert to (ToType), we need to synthesize a call to the
4599 // conversion function and attempt copy initialization from it. This
4600 // makes sure that we get the right semantics with respect to
4601 // lvalues/rvalues and the type. Fortunately, we can allocate this
4602 // call on the stack and we don't need its arguments to be
4603 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004604 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004605 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004606 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4607 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004608 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004609 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004610
Richard Smith48d24642011-07-13 22:53:21 +00004611 QualType ConversionType = Conversion->getConversionType();
4612 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004613 Candidate.Viable = false;
4614 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4615 return;
4616 }
4617
Richard Smith48d24642011-07-13 22:53:21 +00004618 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00004619
Mike Stump11289f42009-09-09 15:08:12 +00004620 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004621 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4622 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00004623 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004624 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004625 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004626 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004627 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004628 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00004629 /*InOverloadResolution=*/false,
4630 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004631
John McCall0d1da222010-01-12 00:44:57 +00004632 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004633 case ImplicitConversionSequence::StandardConversion:
4634 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004635
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004636 // C++ [over.ics.user]p3:
4637 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004638 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004639 // shall have exact match rank.
4640 if (Conversion->getPrimaryTemplate() &&
4641 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4642 Candidate.Viable = false;
4643 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4644 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004645
Douglas Gregorcba72b12011-01-21 05:18:22 +00004646 // C++0x [dcl.init.ref]p5:
4647 // In the second case, if the reference is an rvalue reference and
4648 // the second standard conversion sequence of the user-defined
4649 // conversion sequence includes an lvalue-to-rvalue conversion, the
4650 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004651 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004652 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4653 Candidate.Viable = false;
4654 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4655 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004656 break;
4657
4658 case ImplicitConversionSequence::BadConversion:
4659 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004660 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004661 break;
4662
4663 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004664 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00004665 "Can only end up with a standard conversion sequence or failure");
4666 }
4667}
4668
Douglas Gregor05155d82009-08-21 23:19:43 +00004669/// \brief Adds a conversion function template specialization
4670/// candidate to the overload set, using template argument deduction
4671/// to deduce the template arguments of the conversion function
4672/// template from the type that we are converting to (C++
4673/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004674void
Douglas Gregor05155d82009-08-21 23:19:43 +00004675Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004676 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004677 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004678 Expr *From, QualType ToType,
4679 OverloadCandidateSet &CandidateSet) {
4680 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4681 "Only conversion function templates permitted here");
4682
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004683 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4684 return;
4685
John McCallbc077cf2010-02-08 23:07:23 +00004686 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004687 CXXConversionDecl *Specialization = 0;
4688 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004689 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004690 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004691 CandidateSet.push_back(OverloadCandidate());
4692 OverloadCandidate &Candidate = CandidateSet.back();
4693 Candidate.FoundDecl = FoundDecl;
4694 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4695 Candidate.Viable = false;
4696 Candidate.FailureKind = ovl_fail_bad_deduction;
4697 Candidate.IsSurrogate = false;
4698 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004699 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004700 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004701 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004702 return;
4703 }
Mike Stump11289f42009-09-09 15:08:12 +00004704
Douglas Gregor05155d82009-08-21 23:19:43 +00004705 // Add the conversion function template specialization produced by
4706 // template argument deduction as a candidate.
4707 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004708 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004709 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004710}
4711
Douglas Gregorab7897a2008-11-19 22:57:39 +00004712/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4713/// converts the given @c Object to a function pointer via the
4714/// conversion function @c Conversion, and then attempts to call it
4715/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4716/// the type of function that we'll eventually be calling.
4717void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004718 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004719 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004720 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004721 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004722 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004723 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004724 if (!CandidateSet.isNewCandidate(Conversion))
4725 return;
4726
Douglas Gregor27381f32009-11-23 12:27:39 +00004727 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004728 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004729
Douglas Gregorab7897a2008-11-19 22:57:39 +00004730 CandidateSet.push_back(OverloadCandidate());
4731 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004732 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004733 Candidate.Function = 0;
4734 Candidate.Surrogate = Conversion;
4735 Candidate.Viable = true;
4736 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004737 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004738 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004739 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004740
4741 // Determine the implicit conversion sequence for the implicit
4742 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004743 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004744 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004745 Object->Classify(Context),
4746 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004747 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004748 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004749 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004750 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004751 return;
4752 }
4753
4754 // The first conversion is actually a user-defined conversion whose
4755 // first conversion is ObjectInit's standard conversion (which is
4756 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004757 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004758 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004759 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004760 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00004761 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00004762 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004763 = Candidate.Conversions[0].UserDefined.Before;
4764 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4765
Mike Stump11289f42009-09-09 15:08:12 +00004766 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004767 unsigned NumArgsInProto = Proto->getNumArgs();
4768
4769 // (C++ 13.3.2p2): A candidate function having fewer than m
4770 // parameters is viable only if it has an ellipsis in its parameter
4771 // list (8.3.5).
4772 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4773 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004774 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004775 return;
4776 }
4777
4778 // Function types don't have any default arguments, so just check if
4779 // we have enough arguments.
4780 if (NumArgs < NumArgsInProto) {
4781 // Not enough arguments.
4782 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004783 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004784 return;
4785 }
4786
4787 // Determine the implicit conversion sequences for each of the
4788 // arguments.
4789 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4790 if (ArgIdx < NumArgsInProto) {
4791 // (C++ 13.3.2p3): for F to be a viable function, there shall
4792 // exist for each argument an implicit conversion sequence
4793 // (13.3.3.1) that converts that argument to the corresponding
4794 // parameter of F.
4795 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004796 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004797 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004798 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00004799 /*InOverloadResolution=*/false,
4800 /*AllowObjCWritebackConversion=*/
4801 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004802 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004803 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004804 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004805 break;
4806 }
4807 } else {
4808 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4809 // argument for which there is no corresponding parameter is
4810 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004811 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004812 }
4813 }
4814}
4815
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004816/// \brief Add overload candidates for overloaded operators that are
4817/// member functions.
4818///
4819/// Add the overloaded operator candidates that are member functions
4820/// for the operator Op that was used in an operator expression such
4821/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4822/// CandidateSet will store the added overload candidates. (C++
4823/// [over.match.oper]).
4824void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4825 SourceLocation OpLoc,
4826 Expr **Args, unsigned NumArgs,
4827 OverloadCandidateSet& CandidateSet,
4828 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004829 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4830
4831 // C++ [over.match.oper]p3:
4832 // For a unary operator @ with an operand of a type whose
4833 // cv-unqualified version is T1, and for a binary operator @ with
4834 // a left operand of a type whose cv-unqualified version is T1 and
4835 // a right operand of a type whose cv-unqualified version is T2,
4836 // three sets of candidate functions, designated member
4837 // candidates, non-member candidates and built-in candidates, are
4838 // constructed as follows:
4839 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004840
4841 // -- If T1 is a class type, the set of member candidates is the
4842 // result of the qualified lookup of T1::operator@
4843 // (13.3.1.1.1); otherwise, the set of member candidates is
4844 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004845 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004846 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004847 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004848 return;
Mike Stump11289f42009-09-09 15:08:12 +00004849
John McCall27b18f82009-11-17 02:14:36 +00004850 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4851 LookupQualifiedName(Operators, T1Rec->getDecl());
4852 Operators.suppressDiagnostics();
4853
Mike Stump11289f42009-09-09 15:08:12 +00004854 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004855 OperEnd = Operators.end();
4856 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004857 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004858 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004859 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00004860 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004861 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004862 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004863}
4864
Douglas Gregora11693b2008-11-12 17:17:38 +00004865/// AddBuiltinCandidate - Add a candidate for a built-in
4866/// operator. ResultTy and ParamTys are the result and parameter types
4867/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004868/// arguments being passed to the candidate. IsAssignmentOperator
4869/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004870/// operator. NumContextualBoolArguments is the number of arguments
4871/// (at the beginning of the argument list) that will be contextually
4872/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004873void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004874 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004875 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004876 bool IsAssignmentOperator,
4877 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004878 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004879 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004880
Douglas Gregora11693b2008-11-12 17:17:38 +00004881 // Add this candidate
4882 CandidateSet.push_back(OverloadCandidate());
4883 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004884 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004885 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004886 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004887 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004888 Candidate.BuiltinTypes.ResultTy = ResultTy;
4889 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4890 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4891
4892 // Determine the implicit conversion sequences for each of the
4893 // arguments.
4894 Candidate.Viable = true;
4895 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004896 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004897 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004898 // C++ [over.match.oper]p4:
4899 // For the built-in assignment operators, conversions of the
4900 // left operand are restricted as follows:
4901 // -- no temporaries are introduced to hold the left operand, and
4902 // -- no user-defined conversions are applied to the left
4903 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004904 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004905 //
4906 // We block these conversions by turning off user-defined
4907 // conversions, since that is the only way that initialization of
4908 // a reference to a non-class type can occur from something that
4909 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004910 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004911 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004912 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004913 Candidate.Conversions[ArgIdx]
4914 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004915 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004916 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004917 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004918 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00004919 /*InOverloadResolution=*/false,
4920 /*AllowObjCWritebackConversion=*/
4921 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004922 }
John McCall0d1da222010-01-12 00:44:57 +00004923 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004924 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004925 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004926 break;
4927 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004928 }
4929}
4930
4931/// BuiltinCandidateTypeSet - A set of types that will be used for the
4932/// candidate operator functions for built-in operators (C++
4933/// [over.built]). The types are separated into pointer types and
4934/// enumeration types.
4935class BuiltinCandidateTypeSet {
4936 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004937 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004938
4939 /// PointerTypes - The set of pointer types that will be used in the
4940 /// built-in candidates.
4941 TypeSet PointerTypes;
4942
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004943 /// MemberPointerTypes - The set of member pointer types that will be
4944 /// used in the built-in candidates.
4945 TypeSet MemberPointerTypes;
4946
Douglas Gregora11693b2008-11-12 17:17:38 +00004947 /// EnumerationTypes - The set of enumeration types that will be
4948 /// used in the built-in candidates.
4949 TypeSet EnumerationTypes;
4950
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004951 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004952 /// candidates.
4953 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004954
4955 /// \brief A flag indicating non-record types are viable candidates
4956 bool HasNonRecordTypes;
4957
4958 /// \brief A flag indicating whether either arithmetic or enumeration types
4959 /// were present in the candidate set.
4960 bool HasArithmeticOrEnumeralTypes;
4961
Douglas Gregor80af3132011-05-21 23:15:46 +00004962 /// \brief A flag indicating whether the nullptr type was present in the
4963 /// candidate set.
4964 bool HasNullPtrType;
4965
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004966 /// Sema - The semantic analysis instance where we are building the
4967 /// candidate type set.
4968 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004969
Douglas Gregora11693b2008-11-12 17:17:38 +00004970 /// Context - The AST context in which we will build the type sets.
4971 ASTContext &Context;
4972
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004973 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4974 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004975 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004976
4977public:
4978 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004979 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004980
Mike Stump11289f42009-09-09 15:08:12 +00004981 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004982 : HasNonRecordTypes(false),
4983 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00004984 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00004985 SemaRef(SemaRef),
4986 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004987
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004988 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004989 SourceLocation Loc,
4990 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004991 bool AllowExplicitConversions,
4992 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004993
4994 /// pointer_begin - First pointer type found;
4995 iterator pointer_begin() { return PointerTypes.begin(); }
4996
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004997 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004998 iterator pointer_end() { return PointerTypes.end(); }
4999
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005000 /// member_pointer_begin - First member pointer type found;
5001 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5002
5003 /// member_pointer_end - Past the last member pointer type found;
5004 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5005
Douglas Gregora11693b2008-11-12 17:17:38 +00005006 /// enumeration_begin - First enumeration type found;
5007 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5008
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005009 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005010 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005011
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005012 iterator vector_begin() { return VectorTypes.begin(); }
5013 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005014
5015 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5016 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005017 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005018};
5019
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005020/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005021/// the set of pointer types along with any more-qualified variants of
5022/// that type. For example, if @p Ty is "int const *", this routine
5023/// will add "int const *", "int const volatile *", "int const
5024/// restrict *", and "int const volatile restrict *" to the set of
5025/// pointer types. Returns true if the add of @p Ty itself succeeded,
5026/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005027///
5028/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005029bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005030BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5031 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00005032
Douglas Gregora11693b2008-11-12 17:17:38 +00005033 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005034 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00005035 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005036
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005037 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00005038 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005039 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005040 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005041 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005042 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005043 buildObjCPtr = true;
5044 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005045 else
David Blaikie83d382b2011-09-23 05:06:16 +00005046 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005047 }
5048 else
5049 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005050
Sebastian Redl4990a632009-11-18 20:39:26 +00005051 // Don't add qualified variants of arrays. For one, they're not allowed
5052 // (the qualifier would sink to the element type), and for another, the
5053 // only overload situation where it matters is subscript or pointer +- int,
5054 // and those shouldn't have qualifier variants anyway.
5055 if (PointeeTy->isArrayType())
5056 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005057 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005058 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005059 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005060 bool hasVolatile = VisibleQuals.hasVolatile();
5061 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005062
John McCall8ccfcb52009-09-24 19:53:00 +00005063 // Iterate through all strict supersets of BaseCVR.
5064 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5065 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005066 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5067 // in the types.
5068 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5069 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005070 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005071 if (!buildObjCPtr)
5072 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5073 else
5074 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005075 }
5076
5077 return true;
5078}
5079
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005080/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5081/// to the set of pointer types along with any more-qualified variants of
5082/// that type. For example, if @p Ty is "int const *", this routine
5083/// will add "int const *", "int const volatile *", "int const
5084/// restrict *", and "int const volatile restrict *" to the set of
5085/// pointer types. Returns true if the add of @p Ty itself succeeded,
5086/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005087///
5088/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005089bool
5090BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5091 QualType Ty) {
5092 // Insert this type.
5093 if (!MemberPointerTypes.insert(Ty))
5094 return false;
5095
John McCall8ccfcb52009-09-24 19:53:00 +00005096 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5097 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005098
John McCall8ccfcb52009-09-24 19:53:00 +00005099 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005100 // Don't add qualified variants of arrays. For one, they're not allowed
5101 // (the qualifier would sink to the element type), and for another, the
5102 // only overload situation where it matters is subscript or pointer +- int,
5103 // and those shouldn't have qualifier variants anyway.
5104 if (PointeeTy->isArrayType())
5105 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005106 const Type *ClassTy = PointerTy->getClass();
5107
5108 // Iterate through all strict supersets of the pointee type's CVR
5109 // qualifiers.
5110 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5111 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5112 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005113
John McCall8ccfcb52009-09-24 19:53:00 +00005114 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005115 MemberPointerTypes.insert(
5116 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005117 }
5118
5119 return true;
5120}
5121
Douglas Gregora11693b2008-11-12 17:17:38 +00005122/// AddTypesConvertedFrom - Add each of the types to which the type @p
5123/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005124/// primarily interested in pointer types and enumeration types. We also
5125/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005126/// AllowUserConversions is true if we should look at the conversion
5127/// functions of a class type, and AllowExplicitConversions if we
5128/// should also include the explicit conversion functions of a class
5129/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005130void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005131BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005132 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005133 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005134 bool AllowExplicitConversions,
5135 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005136 // Only deal with canonical types.
5137 Ty = Context.getCanonicalType(Ty);
5138
5139 // Look through reference types; they aren't part of the type of an
5140 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005141 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005142 Ty = RefTy->getPointeeType();
5143
John McCall33ddac02011-01-19 10:06:00 +00005144 // If we're dealing with an array type, decay to the pointer.
5145 if (Ty->isArrayType())
5146 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5147
5148 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005149 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005150
Chandler Carruth00a38332010-12-13 01:44:01 +00005151 // Flag if we ever add a non-record type.
5152 const RecordType *TyRec = Ty->getAs<RecordType>();
5153 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5154
Chandler Carruth00a38332010-12-13 01:44:01 +00005155 // Flag if we encounter an arithmetic type.
5156 HasArithmeticOrEnumeralTypes =
5157 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5158
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005159 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5160 PointerTypes.insert(Ty);
5161 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005162 // Insert our type, and its more-qualified variants, into the set
5163 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005164 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005165 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005166 } else if (Ty->isMemberPointerType()) {
5167 // Member pointers are far easier, since the pointee can't be converted.
5168 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5169 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005170 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005171 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005172 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005173 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005174 // We treat vector types as arithmetic types in many contexts as an
5175 // extension.
5176 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005177 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005178 } else if (Ty->isNullPtrType()) {
5179 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005180 } else if (AllowUserConversions && TyRec) {
5181 // No conversion functions in incomplete types.
5182 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5183 return;
Mike Stump11289f42009-09-09 15:08:12 +00005184
Chandler Carruth00a38332010-12-13 01:44:01 +00005185 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5186 const UnresolvedSetImpl *Conversions
5187 = ClassDecl->getVisibleConversionFunctions();
5188 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5189 E = Conversions->end(); I != E; ++I) {
5190 NamedDecl *D = I.getDecl();
5191 if (isa<UsingShadowDecl>(D))
5192 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005193
Chandler Carruth00a38332010-12-13 01:44:01 +00005194 // Skip conversion function templates; they don't tell us anything
5195 // about which builtin types we can convert to.
5196 if (isa<FunctionTemplateDecl>(D))
5197 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005198
Chandler Carruth00a38332010-12-13 01:44:01 +00005199 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5200 if (AllowExplicitConversions || !Conv->isExplicit()) {
5201 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5202 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005203 }
5204 }
5205 }
5206}
5207
Douglas Gregor84605ae2009-08-24 13:43:27 +00005208/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5209/// the volatile- and non-volatile-qualified assignment operators for the
5210/// given type to the candidate set.
5211static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5212 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005213 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005214 unsigned NumArgs,
5215 OverloadCandidateSet &CandidateSet) {
5216 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005217
Douglas Gregor84605ae2009-08-24 13:43:27 +00005218 // T& operator=(T&, T)
5219 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5220 ParamTypes[1] = T;
5221 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5222 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005223
Douglas Gregor84605ae2009-08-24 13:43:27 +00005224 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5225 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005226 ParamTypes[0]
5227 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005228 ParamTypes[1] = T;
5229 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005230 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005231 }
5232}
Mike Stump11289f42009-09-09 15:08:12 +00005233
Sebastian Redl1054fae2009-10-25 17:03:50 +00005234/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5235/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005236static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5237 Qualifiers VRQuals;
5238 const RecordType *TyRec;
5239 if (const MemberPointerType *RHSMPType =
5240 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005241 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005242 else
5243 TyRec = ArgExpr->getType()->getAs<RecordType>();
5244 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005245 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005246 VRQuals.addVolatile();
5247 VRQuals.addRestrict();
5248 return VRQuals;
5249 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005250
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005251 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005252 if (!ClassDecl->hasDefinition())
5253 return VRQuals;
5254
John McCallad371252010-01-20 00:46:10 +00005255 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005256 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005257
John McCallad371252010-01-20 00:46:10 +00005258 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005259 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005260 NamedDecl *D = I.getDecl();
5261 if (isa<UsingShadowDecl>(D))
5262 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5263 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005264 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5265 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5266 CanTy = ResTypeRef->getPointeeType();
5267 // Need to go down the pointer/mempointer chain and add qualifiers
5268 // as see them.
5269 bool done = false;
5270 while (!done) {
5271 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5272 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005273 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005274 CanTy->getAs<MemberPointerType>())
5275 CanTy = ResTypeMPtr->getPointeeType();
5276 else
5277 done = true;
5278 if (CanTy.isVolatileQualified())
5279 VRQuals.addVolatile();
5280 if (CanTy.isRestrictQualified())
5281 VRQuals.addRestrict();
5282 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5283 return VRQuals;
5284 }
5285 }
5286 }
5287 return VRQuals;
5288}
John McCall52872982010-11-13 05:51:15 +00005289
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005290namespace {
John McCall52872982010-11-13 05:51:15 +00005291
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005292/// \brief Helper class to manage the addition of builtin operator overload
5293/// candidates. It provides shared state and utility methods used throughout
5294/// the process, as well as a helper method to add each group of builtin
5295/// operator overloads from the standard to a candidate set.
5296class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005297 // Common instance state available to all overload candidate addition methods.
5298 Sema &S;
5299 Expr **Args;
5300 unsigned NumArgs;
5301 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005302 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005303 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005304 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005305
Chandler Carruthc6586e52010-12-12 10:35:00 +00005306 // Define some constants used to index and iterate over the arithemetic types
5307 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005308 // The "promoted arithmetic types" are the arithmetic
5309 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005310 static const unsigned FirstIntegralType = 3;
5311 static const unsigned LastIntegralType = 18;
5312 static const unsigned FirstPromotedIntegralType = 3,
5313 LastPromotedIntegralType = 9;
5314 static const unsigned FirstPromotedArithmeticType = 0,
5315 LastPromotedArithmeticType = 9;
5316 static const unsigned NumArithmeticTypes = 18;
5317
Chandler Carruthc6586e52010-12-12 10:35:00 +00005318 /// \brief Get the canonical type for a given arithmetic type index.
5319 CanQualType getArithmeticType(unsigned index) {
5320 assert(index < NumArithmeticTypes);
5321 static CanQualType ASTContext::* const
5322 ArithmeticTypes[NumArithmeticTypes] = {
5323 // Start of promoted types.
5324 &ASTContext::FloatTy,
5325 &ASTContext::DoubleTy,
5326 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005327
Chandler Carruthc6586e52010-12-12 10:35:00 +00005328 // Start of integral types.
5329 &ASTContext::IntTy,
5330 &ASTContext::LongTy,
5331 &ASTContext::LongLongTy,
5332 &ASTContext::UnsignedIntTy,
5333 &ASTContext::UnsignedLongTy,
5334 &ASTContext::UnsignedLongLongTy,
5335 // End of promoted types.
5336
5337 &ASTContext::BoolTy,
5338 &ASTContext::CharTy,
5339 &ASTContext::WCharTy,
5340 &ASTContext::Char16Ty,
5341 &ASTContext::Char32Ty,
5342 &ASTContext::SignedCharTy,
5343 &ASTContext::ShortTy,
5344 &ASTContext::UnsignedCharTy,
5345 &ASTContext::UnsignedShortTy,
5346 // End of integral types.
5347 // FIXME: What about complex?
5348 };
5349 return S.Context.*ArithmeticTypes[index];
5350 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005351
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005352 /// \brief Gets the canonical type resulting from the usual arithemetic
5353 /// converions for the given arithmetic types.
5354 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5355 // Accelerator table for performing the usual arithmetic conversions.
5356 // The rules are basically:
5357 // - if either is floating-point, use the wider floating-point
5358 // - if same signedness, use the higher rank
5359 // - if same size, use unsigned of the higher rank
5360 // - use the larger type
5361 // These rules, together with the axiom that higher ranks are
5362 // never smaller, are sufficient to precompute all of these results
5363 // *except* when dealing with signed types of higher rank.
5364 // (we could precompute SLL x UI for all known platforms, but it's
5365 // better not to make any assumptions).
5366 enum PromotedType {
5367 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5368 };
5369 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5370 [LastPromotedArithmeticType] = {
5371 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5372 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5373 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5374 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5375 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5376 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5377 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5378 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5379 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5380 };
5381
5382 assert(L < LastPromotedArithmeticType);
5383 assert(R < LastPromotedArithmeticType);
5384 int Idx = ConversionsTable[L][R];
5385
5386 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005387 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005388
5389 // Slow path: we need to compare widths.
5390 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005391 CanQualType LT = getArithmeticType(L),
5392 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005393 unsigned LW = S.Context.getIntWidth(LT),
5394 RW = S.Context.getIntWidth(RT);
5395
5396 // If they're different widths, use the signed type.
5397 if (LW > RW) return LT;
5398 else if (LW < RW) return RT;
5399
5400 // Otherwise, use the unsigned type of the signed type's rank.
5401 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5402 assert(L == SLL || R == SLL);
5403 return S.Context.UnsignedLongLongTy;
5404 }
5405
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005406 /// \brief Helper method to factor out the common pattern of adding overloads
5407 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005408 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5409 bool HasVolatile) {
5410 QualType ParamTypes[2] = {
5411 S.Context.getLValueReferenceType(CandidateTy),
5412 S.Context.IntTy
5413 };
5414
5415 // Non-volatile version.
5416 if (NumArgs == 1)
5417 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5418 else
5419 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5420
5421 // Use a heuristic to reduce number of builtin candidates in the set:
5422 // add volatile version only if there are conversions to a volatile type.
5423 if (HasVolatile) {
5424 ParamTypes[0] =
5425 S.Context.getLValueReferenceType(
5426 S.Context.getVolatileType(CandidateTy));
5427 if (NumArgs == 1)
5428 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5429 else
5430 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5431 }
5432 }
5433
5434public:
5435 BuiltinOperatorOverloadBuilder(
5436 Sema &S, Expr **Args, unsigned NumArgs,
5437 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005438 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005439 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005440 OverloadCandidateSet &CandidateSet)
5441 : S(S), Args(Args), NumArgs(NumArgs),
5442 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005443 HasArithmeticOrEnumeralCandidateType(
5444 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005445 CandidateTypes(CandidateTypes),
5446 CandidateSet(CandidateSet) {
5447 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005448 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005449 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005450 assert(getArithmeticType(LastPromotedIntegralType - 1)
5451 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005452 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005453 assert(getArithmeticType(FirstPromotedArithmeticType)
5454 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005455 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005456 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5457 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005458 "Invalid last promoted arithmetic type");
5459 }
5460
5461 // C++ [over.built]p3:
5462 //
5463 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5464 // is either volatile or empty, there exist candidate operator
5465 // functions of the form
5466 //
5467 // VQ T& operator++(VQ T&);
5468 // T operator++(VQ T&, int);
5469 //
5470 // C++ [over.built]p4:
5471 //
5472 // For every pair (T, VQ), where T is an arithmetic type other
5473 // than bool, and VQ is either volatile or empty, there exist
5474 // candidate operator functions of the form
5475 //
5476 // VQ T& operator--(VQ T&);
5477 // T operator--(VQ T&, int);
5478 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005479 if (!HasArithmeticOrEnumeralCandidateType)
5480 return;
5481
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005482 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5483 Arith < NumArithmeticTypes; ++Arith) {
5484 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005485 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005486 VisibleTypeConversionsQuals.hasVolatile());
5487 }
5488 }
5489
5490 // C++ [over.built]p5:
5491 //
5492 // For every pair (T, VQ), where T is a cv-qualified or
5493 // cv-unqualified object type, and VQ is either volatile or
5494 // empty, there exist candidate operator functions of the form
5495 //
5496 // T*VQ& operator++(T*VQ&);
5497 // T*VQ& operator--(T*VQ&);
5498 // T* operator++(T*VQ&, int);
5499 // T* operator--(T*VQ&, int);
5500 void addPlusPlusMinusMinusPointerOverloads() {
5501 for (BuiltinCandidateTypeSet::iterator
5502 Ptr = CandidateTypes[0].pointer_begin(),
5503 PtrEnd = CandidateTypes[0].pointer_end();
5504 Ptr != PtrEnd; ++Ptr) {
5505 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005506 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005507 continue;
5508
5509 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5510 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5511 VisibleTypeConversionsQuals.hasVolatile()));
5512 }
5513 }
5514
5515 // C++ [over.built]p6:
5516 // For every cv-qualified or cv-unqualified object type T, there
5517 // exist candidate operator functions of the form
5518 //
5519 // T& operator*(T*);
5520 //
5521 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005522 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005523 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005524 // T& operator*(T*);
5525 void addUnaryStarPointerOverloads() {
5526 for (BuiltinCandidateTypeSet::iterator
5527 Ptr = CandidateTypes[0].pointer_begin(),
5528 PtrEnd = CandidateTypes[0].pointer_end();
5529 Ptr != PtrEnd; ++Ptr) {
5530 QualType ParamTy = *Ptr;
5531 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005532 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5533 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005534
Douglas Gregor02824322011-01-26 19:30:28 +00005535 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5536 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5537 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005538
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005539 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5540 &ParamTy, Args, 1, CandidateSet);
5541 }
5542 }
5543
5544 // C++ [over.built]p9:
5545 // For every promoted arithmetic type T, there exist candidate
5546 // operator functions of the form
5547 //
5548 // T operator+(T);
5549 // T operator-(T);
5550 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005551 if (!HasArithmeticOrEnumeralCandidateType)
5552 return;
5553
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005554 for (unsigned Arith = FirstPromotedArithmeticType;
5555 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005556 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005557 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5558 }
5559
5560 // Extension: We also add these operators for vector types.
5561 for (BuiltinCandidateTypeSet::iterator
5562 Vec = CandidateTypes[0].vector_begin(),
5563 VecEnd = CandidateTypes[0].vector_end();
5564 Vec != VecEnd; ++Vec) {
5565 QualType VecTy = *Vec;
5566 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5567 }
5568 }
5569
5570 // C++ [over.built]p8:
5571 // For every type T, there exist candidate operator functions of
5572 // the form
5573 //
5574 // T* operator+(T*);
5575 void addUnaryPlusPointerOverloads() {
5576 for (BuiltinCandidateTypeSet::iterator
5577 Ptr = CandidateTypes[0].pointer_begin(),
5578 PtrEnd = CandidateTypes[0].pointer_end();
5579 Ptr != PtrEnd; ++Ptr) {
5580 QualType ParamTy = *Ptr;
5581 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5582 }
5583 }
5584
5585 // C++ [over.built]p10:
5586 // For every promoted integral type T, there exist candidate
5587 // operator functions of the form
5588 //
5589 // T operator~(T);
5590 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005591 if (!HasArithmeticOrEnumeralCandidateType)
5592 return;
5593
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005594 for (unsigned Int = FirstPromotedIntegralType;
5595 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005596 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005597 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5598 }
5599
5600 // Extension: We also add this operator for vector types.
5601 for (BuiltinCandidateTypeSet::iterator
5602 Vec = CandidateTypes[0].vector_begin(),
5603 VecEnd = CandidateTypes[0].vector_end();
5604 Vec != VecEnd; ++Vec) {
5605 QualType VecTy = *Vec;
5606 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5607 }
5608 }
5609
5610 // C++ [over.match.oper]p16:
5611 // For every pointer to member type T, there exist candidate operator
5612 // functions of the form
5613 //
5614 // bool operator==(T,T);
5615 // bool operator!=(T,T);
5616 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5617 /// Set of (canonical) types that we've already handled.
5618 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5619
5620 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5621 for (BuiltinCandidateTypeSet::iterator
5622 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5623 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5624 MemPtr != MemPtrEnd;
5625 ++MemPtr) {
5626 // Don't add the same builtin candidate twice.
5627 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5628 continue;
5629
5630 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5631 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5632 CandidateSet);
5633 }
5634 }
5635 }
5636
5637 // C++ [over.built]p15:
5638 //
Douglas Gregor80af3132011-05-21 23:15:46 +00005639 // For every T, where T is an enumeration type, a pointer type, or
5640 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005641 //
5642 // bool operator<(T, T);
5643 // bool operator>(T, T);
5644 // bool operator<=(T, T);
5645 // bool operator>=(T, T);
5646 // bool operator==(T, T);
5647 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005648 void addRelationalPointerOrEnumeralOverloads() {
5649 // C++ [over.built]p1:
5650 // If there is a user-written candidate with the same name and parameter
5651 // types as a built-in candidate operator function, the built-in operator
5652 // function is hidden and is not included in the set of candidate
5653 // functions.
5654 //
5655 // The text is actually in a note, but if we don't implement it then we end
5656 // up with ambiguities when the user provides an overloaded operator for
5657 // an enumeration type. Note that only enumeration types have this problem,
5658 // so we track which enumeration types we've seen operators for. Also, the
5659 // only other overloaded operator with enumeration argumenst, operator=,
5660 // cannot be overloaded for enumeration types, so this is the only place
5661 // where we must suppress candidates like this.
5662 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5663 UserDefinedBinaryOperators;
5664
5665 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5666 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5667 CandidateTypes[ArgIdx].enumeration_end()) {
5668 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5669 CEnd = CandidateSet.end();
5670 C != CEnd; ++C) {
5671 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5672 continue;
5673
5674 QualType FirstParamType =
5675 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5676 QualType SecondParamType =
5677 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5678
5679 // Skip if either parameter isn't of enumeral type.
5680 if (!FirstParamType->isEnumeralType() ||
5681 !SecondParamType->isEnumeralType())
5682 continue;
5683
5684 // Add this operator to the set of known user-defined operators.
5685 UserDefinedBinaryOperators.insert(
5686 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5687 S.Context.getCanonicalType(SecondParamType)));
5688 }
5689 }
5690 }
5691
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005692 /// Set of (canonical) types that we've already handled.
5693 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5694
5695 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5696 for (BuiltinCandidateTypeSet::iterator
5697 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5698 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5699 Ptr != PtrEnd; ++Ptr) {
5700 // Don't add the same builtin candidate twice.
5701 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5702 continue;
5703
5704 QualType ParamTypes[2] = { *Ptr, *Ptr };
5705 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5706 CandidateSet);
5707 }
5708 for (BuiltinCandidateTypeSet::iterator
5709 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5710 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5711 Enum != EnumEnd; ++Enum) {
5712 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5713
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005714 // Don't add the same builtin candidate twice, or if a user defined
5715 // candidate exists.
5716 if (!AddedTypes.insert(CanonType) ||
5717 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5718 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005719 continue;
5720
5721 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005722 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5723 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005724 }
Douglas Gregor80af3132011-05-21 23:15:46 +00005725
5726 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5727 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5728 if (AddedTypes.insert(NullPtrTy) &&
5729 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5730 NullPtrTy))) {
5731 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5732 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5733 CandidateSet);
5734 }
5735 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005736 }
5737 }
5738
5739 // C++ [over.built]p13:
5740 //
5741 // For every cv-qualified or cv-unqualified object type T
5742 // there exist candidate operator functions of the form
5743 //
5744 // T* operator+(T*, ptrdiff_t);
5745 // T& operator[](T*, ptrdiff_t); [BELOW]
5746 // T* operator-(T*, ptrdiff_t);
5747 // T* operator+(ptrdiff_t, T*);
5748 // T& operator[](ptrdiff_t, T*); [BELOW]
5749 //
5750 // C++ [over.built]p14:
5751 //
5752 // For every T, where T is a pointer to object type, there
5753 // exist candidate operator functions of the form
5754 //
5755 // ptrdiff_t operator-(T, T);
5756 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5757 /// Set of (canonical) types that we've already handled.
5758 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5759
5760 for (int Arg = 0; Arg < 2; ++Arg) {
5761 QualType AsymetricParamTypes[2] = {
5762 S.Context.getPointerDiffType(),
5763 S.Context.getPointerDiffType(),
5764 };
5765 for (BuiltinCandidateTypeSet::iterator
5766 Ptr = CandidateTypes[Arg].pointer_begin(),
5767 PtrEnd = CandidateTypes[Arg].pointer_end();
5768 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005769 QualType PointeeTy = (*Ptr)->getPointeeType();
5770 if (!PointeeTy->isObjectType())
5771 continue;
5772
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005773 AsymetricParamTypes[Arg] = *Ptr;
5774 if (Arg == 0 || Op == OO_Plus) {
5775 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5776 // T* operator+(ptrdiff_t, T*);
5777 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5778 CandidateSet);
5779 }
5780 if (Op == OO_Minus) {
5781 // ptrdiff_t operator-(T, T);
5782 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5783 continue;
5784
5785 QualType ParamTypes[2] = { *Ptr, *Ptr };
5786 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5787 Args, 2, CandidateSet);
5788 }
5789 }
5790 }
5791 }
5792
5793 // C++ [over.built]p12:
5794 //
5795 // For every pair of promoted arithmetic types L and R, there
5796 // exist candidate operator functions of the form
5797 //
5798 // LR operator*(L, R);
5799 // LR operator/(L, R);
5800 // LR operator+(L, R);
5801 // LR operator-(L, R);
5802 // bool operator<(L, R);
5803 // bool operator>(L, R);
5804 // bool operator<=(L, R);
5805 // bool operator>=(L, R);
5806 // bool operator==(L, R);
5807 // bool operator!=(L, R);
5808 //
5809 // where LR is the result of the usual arithmetic conversions
5810 // between types L and R.
5811 //
5812 // C++ [over.built]p24:
5813 //
5814 // For every pair of promoted arithmetic types L and R, there exist
5815 // candidate operator functions of the form
5816 //
5817 // LR operator?(bool, L, R);
5818 //
5819 // where LR is the result of the usual arithmetic conversions
5820 // between types L and R.
5821 // Our candidates ignore the first parameter.
5822 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005823 if (!HasArithmeticOrEnumeralCandidateType)
5824 return;
5825
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005826 for (unsigned Left = FirstPromotedArithmeticType;
5827 Left < LastPromotedArithmeticType; ++Left) {
5828 for (unsigned Right = FirstPromotedArithmeticType;
5829 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005830 QualType LandR[2] = { getArithmeticType(Left),
5831 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005832 QualType Result =
5833 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005834 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005835 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5836 }
5837 }
5838
5839 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5840 // conditional operator for vector types.
5841 for (BuiltinCandidateTypeSet::iterator
5842 Vec1 = CandidateTypes[0].vector_begin(),
5843 Vec1End = CandidateTypes[0].vector_end();
5844 Vec1 != Vec1End; ++Vec1) {
5845 for (BuiltinCandidateTypeSet::iterator
5846 Vec2 = CandidateTypes[1].vector_begin(),
5847 Vec2End = CandidateTypes[1].vector_end();
5848 Vec2 != Vec2End; ++Vec2) {
5849 QualType LandR[2] = { *Vec1, *Vec2 };
5850 QualType Result = S.Context.BoolTy;
5851 if (!isComparison) {
5852 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5853 Result = *Vec1;
5854 else
5855 Result = *Vec2;
5856 }
5857
5858 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5859 }
5860 }
5861 }
5862
5863 // C++ [over.built]p17:
5864 //
5865 // For every pair of promoted integral types L and R, there
5866 // exist candidate operator functions of the form
5867 //
5868 // LR operator%(L, R);
5869 // LR operator&(L, R);
5870 // LR operator^(L, R);
5871 // LR operator|(L, R);
5872 // L operator<<(L, R);
5873 // L operator>>(L, R);
5874 //
5875 // where LR is the result of the usual arithmetic conversions
5876 // between types L and R.
5877 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005878 if (!HasArithmeticOrEnumeralCandidateType)
5879 return;
5880
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005881 for (unsigned Left = FirstPromotedIntegralType;
5882 Left < LastPromotedIntegralType; ++Left) {
5883 for (unsigned Right = FirstPromotedIntegralType;
5884 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005885 QualType LandR[2] = { getArithmeticType(Left),
5886 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005887 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5888 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005889 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005890 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5891 }
5892 }
5893 }
5894
5895 // C++ [over.built]p20:
5896 //
5897 // For every pair (T, VQ), where T is an enumeration or
5898 // pointer to member type and VQ is either volatile or
5899 // empty, there exist candidate operator functions of the form
5900 //
5901 // VQ T& operator=(VQ T&, T);
5902 void addAssignmentMemberPointerOrEnumeralOverloads() {
5903 /// Set of (canonical) types that we've already handled.
5904 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5905
5906 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5907 for (BuiltinCandidateTypeSet::iterator
5908 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5909 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5910 Enum != EnumEnd; ++Enum) {
5911 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5912 continue;
5913
5914 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5915 CandidateSet);
5916 }
5917
5918 for (BuiltinCandidateTypeSet::iterator
5919 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5920 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5921 MemPtr != MemPtrEnd; ++MemPtr) {
5922 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5923 continue;
5924
5925 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5926 CandidateSet);
5927 }
5928 }
5929 }
5930
5931 // C++ [over.built]p19:
5932 //
5933 // For every pair (T, VQ), where T is any type and VQ is either
5934 // volatile or empty, there exist candidate operator functions
5935 // of the form
5936 //
5937 // T*VQ& operator=(T*VQ&, T*);
5938 //
5939 // C++ [over.built]p21:
5940 //
5941 // For every pair (T, VQ), where T is a cv-qualified or
5942 // cv-unqualified object type and VQ is either volatile or
5943 // empty, there exist candidate operator functions of the form
5944 //
5945 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5946 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5947 void addAssignmentPointerOverloads(bool isEqualOp) {
5948 /// Set of (canonical) types that we've already handled.
5949 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5950
5951 for (BuiltinCandidateTypeSet::iterator
5952 Ptr = CandidateTypes[0].pointer_begin(),
5953 PtrEnd = CandidateTypes[0].pointer_end();
5954 Ptr != PtrEnd; ++Ptr) {
5955 // If this is operator=, keep track of the builtin candidates we added.
5956 if (isEqualOp)
5957 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005958 else if (!(*Ptr)->getPointeeType()->isObjectType())
5959 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005960
5961 // non-volatile version
5962 QualType ParamTypes[2] = {
5963 S.Context.getLValueReferenceType(*Ptr),
5964 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5965 };
5966 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5967 /*IsAssigmentOperator=*/ isEqualOp);
5968
5969 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5970 VisibleTypeConversionsQuals.hasVolatile()) {
5971 // volatile version
5972 ParamTypes[0] =
5973 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5974 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5975 /*IsAssigmentOperator=*/isEqualOp);
5976 }
5977 }
5978
5979 if (isEqualOp) {
5980 for (BuiltinCandidateTypeSet::iterator
5981 Ptr = CandidateTypes[1].pointer_begin(),
5982 PtrEnd = CandidateTypes[1].pointer_end();
5983 Ptr != PtrEnd; ++Ptr) {
5984 // Make sure we don't add the same candidate twice.
5985 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5986 continue;
5987
Chandler Carruth8e543b32010-12-12 08:17:55 +00005988 QualType ParamTypes[2] = {
5989 S.Context.getLValueReferenceType(*Ptr),
5990 *Ptr,
5991 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005992
5993 // non-volatile version
5994 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5995 /*IsAssigmentOperator=*/true);
5996
5997 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5998 VisibleTypeConversionsQuals.hasVolatile()) {
5999 // volatile version
6000 ParamTypes[0] =
6001 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006002 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6003 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006004 }
6005 }
6006 }
6007 }
6008
6009 // C++ [over.built]p18:
6010 //
6011 // For every triple (L, VQ, R), where L is an arithmetic type,
6012 // VQ is either volatile or empty, and R is a promoted
6013 // arithmetic type, there exist candidate operator functions of
6014 // the form
6015 //
6016 // VQ L& operator=(VQ L&, R);
6017 // VQ L& operator*=(VQ L&, R);
6018 // VQ L& operator/=(VQ L&, R);
6019 // VQ L& operator+=(VQ L&, R);
6020 // VQ L& operator-=(VQ L&, R);
6021 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006022 if (!HasArithmeticOrEnumeralCandidateType)
6023 return;
6024
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006025 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6026 for (unsigned Right = FirstPromotedArithmeticType;
6027 Right < LastPromotedArithmeticType; ++Right) {
6028 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006029 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006030
6031 // Add this built-in operator as a candidate (VQ is empty).
6032 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006033 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006034 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6035 /*IsAssigmentOperator=*/isEqualOp);
6036
6037 // Add this built-in operator as a candidate (VQ is 'volatile').
6038 if (VisibleTypeConversionsQuals.hasVolatile()) {
6039 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006040 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006041 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006042 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6043 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006044 /*IsAssigmentOperator=*/isEqualOp);
6045 }
6046 }
6047 }
6048
6049 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6050 for (BuiltinCandidateTypeSet::iterator
6051 Vec1 = CandidateTypes[0].vector_begin(),
6052 Vec1End = CandidateTypes[0].vector_end();
6053 Vec1 != Vec1End; ++Vec1) {
6054 for (BuiltinCandidateTypeSet::iterator
6055 Vec2 = CandidateTypes[1].vector_begin(),
6056 Vec2End = CandidateTypes[1].vector_end();
6057 Vec2 != Vec2End; ++Vec2) {
6058 QualType ParamTypes[2];
6059 ParamTypes[1] = *Vec2;
6060 // Add this built-in operator as a candidate (VQ is empty).
6061 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6062 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6063 /*IsAssigmentOperator=*/isEqualOp);
6064
6065 // Add this built-in operator as a candidate (VQ is 'volatile').
6066 if (VisibleTypeConversionsQuals.hasVolatile()) {
6067 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6068 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006069 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6070 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006071 /*IsAssigmentOperator=*/isEqualOp);
6072 }
6073 }
6074 }
6075 }
6076
6077 // C++ [over.built]p22:
6078 //
6079 // For every triple (L, VQ, R), where L is an integral type, VQ
6080 // is either volatile or empty, and R is a promoted integral
6081 // type, there exist candidate operator functions of the form
6082 //
6083 // VQ L& operator%=(VQ L&, R);
6084 // VQ L& operator<<=(VQ L&, R);
6085 // VQ L& operator>>=(VQ L&, R);
6086 // VQ L& operator&=(VQ L&, R);
6087 // VQ L& operator^=(VQ L&, R);
6088 // VQ L& operator|=(VQ L&, R);
6089 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006090 if (!HasArithmeticOrEnumeralCandidateType)
6091 return;
6092
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006093 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6094 for (unsigned Right = FirstPromotedIntegralType;
6095 Right < LastPromotedIntegralType; ++Right) {
6096 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006097 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006098
6099 // Add this built-in operator as a candidate (VQ is empty).
6100 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006101 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006102 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6103 if (VisibleTypeConversionsQuals.hasVolatile()) {
6104 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006105 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006106 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6107 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6108 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6109 CandidateSet);
6110 }
6111 }
6112 }
6113 }
6114
6115 // C++ [over.operator]p23:
6116 //
6117 // There also exist candidate operator functions of the form
6118 //
6119 // bool operator!(bool);
6120 // bool operator&&(bool, bool);
6121 // bool operator||(bool, bool);
6122 void addExclaimOverload() {
6123 QualType ParamTy = S.Context.BoolTy;
6124 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6125 /*IsAssignmentOperator=*/false,
6126 /*NumContextualBoolArguments=*/1);
6127 }
6128 void addAmpAmpOrPipePipeOverload() {
6129 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6130 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6131 /*IsAssignmentOperator=*/false,
6132 /*NumContextualBoolArguments=*/2);
6133 }
6134
6135 // C++ [over.built]p13:
6136 //
6137 // For every cv-qualified or cv-unqualified object type T there
6138 // exist candidate operator functions of the form
6139 //
6140 // T* operator+(T*, ptrdiff_t); [ABOVE]
6141 // T& operator[](T*, ptrdiff_t);
6142 // T* operator-(T*, ptrdiff_t); [ABOVE]
6143 // T* operator+(ptrdiff_t, T*); [ABOVE]
6144 // T& operator[](ptrdiff_t, T*);
6145 void addSubscriptOverloads() {
6146 for (BuiltinCandidateTypeSet::iterator
6147 Ptr = CandidateTypes[0].pointer_begin(),
6148 PtrEnd = CandidateTypes[0].pointer_end();
6149 Ptr != PtrEnd; ++Ptr) {
6150 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6151 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006152 if (!PointeeType->isObjectType())
6153 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006154
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006155 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6156
6157 // T& operator[](T*, ptrdiff_t)
6158 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6159 }
6160
6161 for (BuiltinCandidateTypeSet::iterator
6162 Ptr = CandidateTypes[1].pointer_begin(),
6163 PtrEnd = CandidateTypes[1].pointer_end();
6164 Ptr != PtrEnd; ++Ptr) {
6165 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6166 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006167 if (!PointeeType->isObjectType())
6168 continue;
6169
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006170 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6171
6172 // T& operator[](ptrdiff_t, T*)
6173 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6174 }
6175 }
6176
6177 // C++ [over.built]p11:
6178 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6179 // C1 is the same type as C2 or is a derived class of C2, T is an object
6180 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6181 // there exist candidate operator functions of the form
6182 //
6183 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6184 //
6185 // where CV12 is the union of CV1 and CV2.
6186 void addArrowStarOverloads() {
6187 for (BuiltinCandidateTypeSet::iterator
6188 Ptr = CandidateTypes[0].pointer_begin(),
6189 PtrEnd = CandidateTypes[0].pointer_end();
6190 Ptr != PtrEnd; ++Ptr) {
6191 QualType C1Ty = (*Ptr);
6192 QualType C1;
6193 QualifierCollector Q1;
6194 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6195 if (!isa<RecordType>(C1))
6196 continue;
6197 // heuristic to reduce number of builtin candidates in the set.
6198 // Add volatile/restrict version only if there are conversions to a
6199 // volatile/restrict type.
6200 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6201 continue;
6202 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6203 continue;
6204 for (BuiltinCandidateTypeSet::iterator
6205 MemPtr = CandidateTypes[1].member_pointer_begin(),
6206 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6207 MemPtr != MemPtrEnd; ++MemPtr) {
6208 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6209 QualType C2 = QualType(mptr->getClass(), 0);
6210 C2 = C2.getUnqualifiedType();
6211 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6212 break;
6213 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6214 // build CV12 T&
6215 QualType T = mptr->getPointeeType();
6216 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6217 T.isVolatileQualified())
6218 continue;
6219 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6220 T.isRestrictQualified())
6221 continue;
6222 T = Q1.apply(S.Context, T);
6223 QualType ResultTy = S.Context.getLValueReferenceType(T);
6224 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6225 }
6226 }
6227 }
6228
6229 // Note that we don't consider the first argument, since it has been
6230 // contextually converted to bool long ago. The candidates below are
6231 // therefore added as binary.
6232 //
6233 // C++ [over.built]p25:
6234 // For every type T, where T is a pointer, pointer-to-member, or scoped
6235 // enumeration type, there exist candidate operator functions of the form
6236 //
6237 // T operator?(bool, T, T);
6238 //
6239 void addConditionalOperatorOverloads() {
6240 /// Set of (canonical) types that we've already handled.
6241 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6242
6243 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6244 for (BuiltinCandidateTypeSet::iterator
6245 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6246 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6247 Ptr != PtrEnd; ++Ptr) {
6248 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6249 continue;
6250
6251 QualType ParamTypes[2] = { *Ptr, *Ptr };
6252 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6253 }
6254
6255 for (BuiltinCandidateTypeSet::iterator
6256 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6257 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6258 MemPtr != MemPtrEnd; ++MemPtr) {
6259 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6260 continue;
6261
6262 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6263 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6264 }
6265
6266 if (S.getLangOptions().CPlusPlus0x) {
6267 for (BuiltinCandidateTypeSet::iterator
6268 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6269 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6270 Enum != EnumEnd; ++Enum) {
6271 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6272 continue;
6273
6274 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6275 continue;
6276
6277 QualType ParamTypes[2] = { *Enum, *Enum };
6278 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6279 }
6280 }
6281 }
6282 }
6283};
6284
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006285} // end anonymous namespace
6286
6287/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6288/// operator overloads to the candidate set (C++ [over.built]), based
6289/// on the operator @p Op and the arguments given. For example, if the
6290/// operator is a binary '+', this routine might add "int
6291/// operator+(int, int)" to cover integer addition.
6292void
6293Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6294 SourceLocation OpLoc,
6295 Expr **Args, unsigned NumArgs,
6296 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006297 // Find all of the types that the arguments can convert to, but only
6298 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006299 // that make use of these types. Also record whether we encounter non-record
6300 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006301 Qualifiers VisibleTypeConversionsQuals;
6302 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006303 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6304 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006305
6306 bool HasNonRecordCandidateType = false;
6307 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006308 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006309 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6310 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6311 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6312 OpLoc,
6313 true,
6314 (Op == OO_Exclaim ||
6315 Op == OO_AmpAmp ||
6316 Op == OO_PipePipe),
6317 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006318 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6319 CandidateTypes[ArgIdx].hasNonRecordTypes();
6320 HasArithmeticOrEnumeralCandidateType =
6321 HasArithmeticOrEnumeralCandidateType ||
6322 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006323 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006324
Chandler Carruth00a38332010-12-13 01:44:01 +00006325 // Exit early when no non-record types have been added to the candidate set
6326 // for any of the arguments to the operator.
6327 if (!HasNonRecordCandidateType)
6328 return;
6329
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006330 // Setup an object to manage the common state for building overloads.
6331 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6332 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006333 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006334 CandidateTypes, CandidateSet);
6335
6336 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006337 switch (Op) {
6338 case OO_None:
6339 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00006340 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00006341
Chandler Carruth5184de02010-12-12 08:51:33 +00006342 case OO_New:
6343 case OO_Delete:
6344 case OO_Array_New:
6345 case OO_Array_Delete:
6346 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00006347 llvm_unreachable(
6348 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00006349
6350 case OO_Comma:
6351 case OO_Arrow:
6352 // C++ [over.match.oper]p3:
6353 // -- For the operator ',', the unary operator '&', or the
6354 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006355 break;
6356
6357 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006358 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006359 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006360 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006361
6362 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006363 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006364 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006365 } else {
6366 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6367 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6368 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006369 break;
6370
Chandler Carruth5184de02010-12-12 08:51:33 +00006371 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006372 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006373 OpBuilder.addUnaryStarPointerOverloads();
6374 else
6375 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6376 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006377
Chandler Carruth5184de02010-12-12 08:51:33 +00006378 case OO_Slash:
6379 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006380 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006381
6382 case OO_PlusPlus:
6383 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006384 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6385 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006386 break;
6387
Douglas Gregor84605ae2009-08-24 13:43:27 +00006388 case OO_EqualEqual:
6389 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006390 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006391 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006392
Douglas Gregora11693b2008-11-12 17:17:38 +00006393 case OO_Less:
6394 case OO_Greater:
6395 case OO_LessEqual:
6396 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006397 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006398 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6399 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006400
Douglas Gregora11693b2008-11-12 17:17:38 +00006401 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006402 case OO_Caret:
6403 case OO_Pipe:
6404 case OO_LessLess:
6405 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006406 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006407 break;
6408
Chandler Carruth5184de02010-12-12 08:51:33 +00006409 case OO_Amp: // '&' is either unary or binary
6410 if (NumArgs == 1)
6411 // C++ [over.match.oper]p3:
6412 // -- For the operator ',', the unary operator '&', or the
6413 // operator '->', the built-in candidates set is empty.
6414 break;
6415
6416 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6417 break;
6418
6419 case OO_Tilde:
6420 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6421 break;
6422
Douglas Gregora11693b2008-11-12 17:17:38 +00006423 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006424 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006425 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006426
6427 case OO_PlusEqual:
6428 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006429 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006430 // Fall through.
6431
6432 case OO_StarEqual:
6433 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006434 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006435 break;
6436
6437 case OO_PercentEqual:
6438 case OO_LessLessEqual:
6439 case OO_GreaterGreaterEqual:
6440 case OO_AmpEqual:
6441 case OO_CaretEqual:
6442 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006443 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006444 break;
6445
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006446 case OO_Exclaim:
6447 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006448 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006449
Douglas Gregora11693b2008-11-12 17:17:38 +00006450 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006451 case OO_PipePipe:
6452 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006453 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006454
6455 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006456 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006457 break;
6458
6459 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006460 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006461 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006462
6463 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006464 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006465 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6466 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006467 }
6468}
6469
Douglas Gregore254f902009-02-04 00:32:51 +00006470/// \brief Add function candidates found via argument-dependent lookup
6471/// to the set of overloading candidates.
6472///
6473/// This routine performs argument-dependent name lookup based on the
6474/// given function name (which may also be an operator name) and adds
6475/// all of the overload candidates found by ADL to the overload
6476/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006477void
Douglas Gregore254f902009-02-04 00:32:51 +00006478Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006479 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006480 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006481 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006482 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006483 bool PartialOverloading,
6484 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006485 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006486
John McCall91f61fc2010-01-26 06:04:06 +00006487 // FIXME: This approach for uniquing ADL results (and removing
6488 // redundant candidates from the set) relies on pointer-equality,
6489 // which means we need to key off the canonical decl. However,
6490 // always going back to the canonical decl might not get us the
6491 // right set of default arguments. What default arguments are
6492 // we supposed to consider on ADL candidates, anyway?
6493
Douglas Gregorcabea402009-09-22 15:41:20 +00006494 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006495 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6496 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006497
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006498 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006499 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6500 CandEnd = CandidateSet.end();
6501 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006502 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006503 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006504 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006505 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006506 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006507
6508 // For each of the ADL candidates we found, add it to the overload
6509 // set.
John McCall8fe68082010-01-26 07:16:45 +00006510 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006511 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006512 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006513 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006514 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006515
John McCalla0296f72010-03-19 07:35:19 +00006516 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006517 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006518 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006519 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006520 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006521 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006522 }
Douglas Gregore254f902009-02-04 00:32:51 +00006523}
6524
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006525/// isBetterOverloadCandidate - Determines whether the first overload
6526/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006527bool
John McCall5c32be02010-08-24 20:38:10 +00006528isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006529 const OverloadCandidate &Cand1,
6530 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006531 SourceLocation Loc,
6532 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006533 // Define viable functions to be better candidates than non-viable
6534 // functions.
6535 if (!Cand2.Viable)
6536 return Cand1.Viable;
6537 else if (!Cand1.Viable)
6538 return false;
6539
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006540 // C++ [over.match.best]p1:
6541 //
6542 // -- if F is a static member function, ICS1(F) is defined such
6543 // that ICS1(F) is neither better nor worse than ICS1(G) for
6544 // any function G, and, symmetrically, ICS1(G) is neither
6545 // better nor worse than ICS1(F).
6546 unsigned StartArg = 0;
6547 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6548 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006549
Douglas Gregord3cb3562009-07-07 23:38:56 +00006550 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006551 // A viable function F1 is defined to be a better function than another
6552 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006553 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006554 unsigned NumArgs = Cand1.Conversions.size();
6555 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6556 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006557 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006558 switch (CompareImplicitConversionSequences(S,
6559 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006560 Cand2.Conversions[ArgIdx])) {
6561 case ImplicitConversionSequence::Better:
6562 // Cand1 has a better conversion sequence.
6563 HasBetterConversion = true;
6564 break;
6565
6566 case ImplicitConversionSequence::Worse:
6567 // Cand1 can't be better than Cand2.
6568 return false;
6569
6570 case ImplicitConversionSequence::Indistinguishable:
6571 // Do nothing.
6572 break;
6573 }
6574 }
6575
Mike Stump11289f42009-09-09 15:08:12 +00006576 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006577 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006578 if (HasBetterConversion)
6579 return true;
6580
Mike Stump11289f42009-09-09 15:08:12 +00006581 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006582 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006583 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006584 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6585 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006586
6587 // -- F1 and F2 are function template specializations, and the function
6588 // template for F1 is more specialized than the template for F2
6589 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006590 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006591 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006592 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006593 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006594 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6595 Cand2.Function->getPrimaryTemplate(),
6596 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006597 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006598 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006599 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006600 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006601 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006602
Douglas Gregora1f013e2008-11-07 22:36:19 +00006603 // -- the context is an initialization by user-defined conversion
6604 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6605 // from the return type of F1 to the destination type (i.e.,
6606 // the type of the entity being initialized) is a better
6607 // conversion sequence than the standard conversion sequence
6608 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006609 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006610 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006611 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006612 switch (CompareStandardConversionSequences(S,
6613 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006614 Cand2.FinalConversion)) {
6615 case ImplicitConversionSequence::Better:
6616 // Cand1 has a better conversion sequence.
6617 return true;
6618
6619 case ImplicitConversionSequence::Worse:
6620 // Cand1 can't be better than Cand2.
6621 return false;
6622
6623 case ImplicitConversionSequence::Indistinguishable:
6624 // Do nothing
6625 break;
6626 }
6627 }
6628
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006629 return false;
6630}
6631
Mike Stump11289f42009-09-09 15:08:12 +00006632/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006633/// within an overload candidate set.
6634///
6635/// \param CandidateSet the set of candidate functions.
6636///
6637/// \param Loc the location of the function name (or operator symbol) for
6638/// which overload resolution occurs.
6639///
Mike Stump11289f42009-09-09 15:08:12 +00006640/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006641/// function, Best points to the candidate function found.
6642///
6643/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006644OverloadingResult
6645OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006646 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00006647 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006648 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006649 Best = end();
6650 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6651 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006652 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006653 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006654 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006655 }
6656
6657 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006658 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006659 return OR_No_Viable_Function;
6660
6661 // Make sure that this function is better than every other viable
6662 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006663 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006664 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006665 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006666 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006667 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006668 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006669 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006670 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006671 }
Mike Stump11289f42009-09-09 15:08:12 +00006672
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006673 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006674 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00006675 (Best->Function->isDeleted() ||
6676 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006677 return OR_Deleted;
6678
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006679 return OR_Success;
6680}
6681
John McCall53262c92010-01-12 02:15:36 +00006682namespace {
6683
6684enum OverloadCandidateKind {
6685 oc_function,
6686 oc_method,
6687 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006688 oc_function_template,
6689 oc_method_template,
6690 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006691 oc_implicit_default_constructor,
6692 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006693 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006694 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006695 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00006696 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006697};
6698
John McCalle1ac8d12010-01-13 00:25:19 +00006699OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6700 FunctionDecl *Fn,
6701 std::string &Description) {
6702 bool isTemplate = false;
6703
6704 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6705 isTemplate = true;
6706 Description = S.getTemplateArgumentBindingsText(
6707 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6708 }
John McCallfd0b2f82010-01-06 09:43:14 +00006709
6710 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006711 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006712 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006713
Sebastian Redl08905022011-02-05 19:23:19 +00006714 if (Ctor->getInheritedConstructor())
6715 return oc_implicit_inherited_constructor;
6716
Alexis Hunt119c10e2011-05-25 23:16:36 +00006717 if (Ctor->isDefaultConstructor())
6718 return oc_implicit_default_constructor;
6719
6720 if (Ctor->isMoveConstructor())
6721 return oc_implicit_move_constructor;
6722
6723 assert(Ctor->isCopyConstructor() &&
6724 "unexpected sort of implicit constructor");
6725 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006726 }
6727
6728 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6729 // This actually gets spelled 'candidate function' for now, but
6730 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006731 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006732 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006733
Alexis Hunt119c10e2011-05-25 23:16:36 +00006734 if (Meth->isMoveAssignmentOperator())
6735 return oc_implicit_move_assignment;
6736
Douglas Gregorec3bec02010-09-27 22:37:28 +00006737 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006738 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006739 return oc_implicit_copy_assignment;
6740 }
6741
John McCalle1ac8d12010-01-13 00:25:19 +00006742 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006743}
6744
Sebastian Redl08905022011-02-05 19:23:19 +00006745void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6746 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6747 if (!Ctor) return;
6748
6749 Ctor = Ctor->getInheritedConstructor();
6750 if (!Ctor) return;
6751
6752 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6753}
6754
John McCall53262c92010-01-12 02:15:36 +00006755} // end anonymous namespace
6756
6757// Notes the location of an overload candidate.
6758void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006759 std::string FnDesc;
6760 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6761 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6762 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00006763 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00006764}
6765
Douglas Gregorb491ed32011-02-19 21:32:49 +00006766//Notes the location of all overload candidates designated through
6767// OverloadedExpr
6768void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6769 assert(OverloadedExpr->getType() == Context.OverloadTy);
6770
6771 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6772 OverloadExpr *OvlExpr = Ovl.Expression;
6773
6774 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6775 IEnd = OvlExpr->decls_end();
6776 I != IEnd; ++I) {
6777 if (FunctionTemplateDecl *FunTmpl =
6778 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6779 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6780 } else if (FunctionDecl *Fun
6781 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6782 NoteOverloadCandidate(Fun);
6783 }
6784 }
6785}
6786
John McCall0d1da222010-01-12 00:44:57 +00006787/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6788/// "lead" diagnostic; it will be given two arguments, the source and
6789/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006790void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6791 Sema &S,
6792 SourceLocation CaretLoc,
6793 const PartialDiagnostic &PDiag) const {
6794 S.Diag(CaretLoc, PDiag)
6795 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006796 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006797 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6798 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006799 }
John McCall12f97bc2010-01-08 04:41:39 +00006800}
6801
John McCall0d1da222010-01-12 00:44:57 +00006802namespace {
6803
John McCall6a61b522010-01-13 09:16:55 +00006804void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6805 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6806 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006807 assert(Cand->Function && "for now, candidate must be a function");
6808 FunctionDecl *Fn = Cand->Function;
6809
6810 // There's a conversion slot for the object argument if this is a
6811 // non-constructor method. Note that 'I' corresponds the
6812 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006813 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006814 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006815 if (I == 0)
6816 isObjectArgument = true;
6817 else
6818 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006819 }
6820
John McCalle1ac8d12010-01-13 00:25:19 +00006821 std::string FnDesc;
6822 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6823
John McCall6a61b522010-01-13 09:16:55 +00006824 Expr *FromExpr = Conv.Bad.FromExpr;
6825 QualType FromTy = Conv.Bad.getFromType();
6826 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006827
John McCallfb7ad0f2010-02-02 02:42:52 +00006828 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006829 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006830 Expr *E = FromExpr->IgnoreParens();
6831 if (isa<UnaryOperator>(E))
6832 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006833 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006834
6835 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6836 << (unsigned) FnKind << FnDesc
6837 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6838 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006839 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00006840 return;
6841 }
6842
John McCall6d174642010-01-23 08:10:49 +00006843 // Do some hand-waving analysis to see if the non-viability is due
6844 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006845 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6846 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6847 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6848 CToTy = RT->getPointeeType();
6849 else {
6850 // TODO: detect and diagnose the full richness of const mismatches.
6851 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6852 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6853 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6854 }
6855
6856 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6857 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6858 // It is dumb that we have to do this here.
6859 while (isa<ArrayType>(CFromTy))
6860 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6861 while (isa<ArrayType>(CToTy))
6862 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6863
6864 Qualifiers FromQs = CFromTy.getQualifiers();
6865 Qualifiers ToQs = CToTy.getQualifiers();
6866
6867 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6868 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6869 << (unsigned) FnKind << FnDesc
6870 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6871 << FromTy
6872 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6873 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006874 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006875 return;
6876 }
6877
John McCall31168b02011-06-15 23:02:42 +00006878 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00006879 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00006880 << (unsigned) FnKind << FnDesc
6881 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6882 << FromTy
6883 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
6884 << (unsigned) isObjectArgument << I+1;
6885 MaybeEmitInheritedConstructorNote(S, Fn);
6886 return;
6887 }
6888
Douglas Gregoraec25842011-04-26 23:16:46 +00006889 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
6890 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
6891 << (unsigned) FnKind << FnDesc
6892 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6893 << FromTy
6894 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
6895 << (unsigned) isObjectArgument << I+1;
6896 MaybeEmitInheritedConstructorNote(S, Fn);
6897 return;
6898 }
6899
John McCall47000992010-01-14 03:28:57 +00006900 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6901 assert(CVR && "unexpected qualifiers mismatch");
6902
6903 if (isObjectArgument) {
6904 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6905 << (unsigned) FnKind << FnDesc
6906 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6907 << FromTy << (CVR - 1);
6908 } else {
6909 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6910 << (unsigned) FnKind << FnDesc
6911 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6912 << FromTy << (CVR - 1) << I+1;
6913 }
Sebastian Redl08905022011-02-05 19:23:19 +00006914 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006915 return;
6916 }
6917
Sebastian Redla72462c2011-09-24 17:48:32 +00006918 // Special diagnostic for failure to convert an initializer list, since
6919 // telling the user that it has type void is not useful.
6920 if (FromExpr && isa<InitListExpr>(FromExpr)) {
6921 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
6922 << (unsigned) FnKind << FnDesc
6923 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6924 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6925 MaybeEmitInheritedConstructorNote(S, Fn);
6926 return;
6927 }
6928
John McCall6d174642010-01-23 08:10:49 +00006929 // Diagnose references or pointers to incomplete types differently,
6930 // since it's far from impossible that the incompleteness triggered
6931 // the failure.
6932 QualType TempFromTy = FromTy.getNonReferenceType();
6933 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6934 TempFromTy = PTy->getPointeeType();
6935 if (TempFromTy->isIncompleteType()) {
6936 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6937 << (unsigned) FnKind << FnDesc
6938 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6939 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006940 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00006941 return;
6942 }
6943
Douglas Gregor56f2e342010-06-30 23:01:39 +00006944 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006945 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006946 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6947 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6948 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6949 FromPtrTy->getPointeeType()) &&
6950 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6951 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006952 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00006953 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006954 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006955 }
6956 } else if (const ObjCObjectPointerType *FromPtrTy
6957 = FromTy->getAs<ObjCObjectPointerType>()) {
6958 if (const ObjCObjectPointerType *ToPtrTy
6959 = ToTy->getAs<ObjCObjectPointerType>())
6960 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6961 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6962 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6963 FromPtrTy->getPointeeType()) &&
6964 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006965 BaseToDerivedConversion = 2;
6966 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6967 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6968 !FromTy->isIncompleteType() &&
6969 !ToRefTy->getPointeeType()->isIncompleteType() &&
6970 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6971 BaseToDerivedConversion = 3;
6972 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006973
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006974 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006975 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006976 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006977 << (unsigned) FnKind << FnDesc
6978 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006979 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006980 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006981 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00006982 return;
6983 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006984
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00006985 if (isa<ObjCObjectPointerType>(CFromTy) &&
6986 isa<PointerType>(CToTy)) {
6987 Qualifiers FromQs = CFromTy.getQualifiers();
6988 Qualifiers ToQs = CToTy.getQualifiers();
6989 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
6990 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
6991 << (unsigned) FnKind << FnDesc
6992 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6993 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6994 MaybeEmitInheritedConstructorNote(S, Fn);
6995 return;
6996 }
6997 }
6998
Anna Zaksdf92ddf2011-07-19 19:49:12 +00006999 // Emit the generic diagnostic and, optionally, add the hints to it.
7000 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7001 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007002 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007003 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7004 << (unsigned) (Cand->Fix.Kind);
7005
7006 // If we can fix the conversion, suggest the FixIts.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007007 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007008 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7009 HI != HE; ++HI)
7010 FDiag << *HI;
7011 S.Diag(Fn->getLocation(), FDiag);
7012
Sebastian Redl08905022011-02-05 19:23:19 +00007013 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007014}
7015
7016void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7017 unsigned NumFormalArgs) {
7018 // TODO: treat calls to a missing default constructor as a special case
7019
7020 FunctionDecl *Fn = Cand->Function;
7021 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7022
7023 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007024
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00007025 // With invalid overloaded operators, it's possible that we think we
7026 // have an arity mismatch when it fact it looks like we have the
7027 // right number of arguments, because only overloaded operators have
7028 // the weird behavior of overloading member and non-member functions.
7029 // Just don't report anything.
7030 if (Fn->isInvalidDecl() &&
7031 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7032 return;
7033
John McCall6a61b522010-01-13 09:16:55 +00007034 // at least / at most / exactly
7035 unsigned mode, modeCount;
7036 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007037 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7038 (Cand->FailureKind == ovl_fail_bad_deduction &&
7039 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007040 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00007041 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00007042 mode = 0; // "at least"
7043 else
7044 mode = 2; // "exactly"
7045 modeCount = MinParams;
7046 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007047 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7048 (Cand->FailureKind == ovl_fail_bad_deduction &&
7049 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00007050 if (MinParams != FnTy->getNumArgs())
7051 mode = 1; // "at most"
7052 else
7053 mode = 2; // "exactly"
7054 modeCount = FnTy->getNumArgs();
7055 }
7056
7057 std::string Description;
7058 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7059
7060 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007061 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00007062 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00007063 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007064}
7065
John McCall8b9ed552010-02-01 18:53:26 +00007066/// Diagnose a failed template-argument deduction.
7067void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7068 Expr **Args, unsigned NumArgs) {
7069 FunctionDecl *Fn = Cand->Function; // pattern
7070
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007071 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007072 NamedDecl *ParamD;
7073 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7074 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7075 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007076 switch (Cand->DeductionFailure.Result) {
7077 case Sema::TDK_Success:
7078 llvm_unreachable("TDK_success while diagnosing bad deduction");
7079
7080 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007081 assert(ParamD && "no parameter found for incomplete deduction result");
7082 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7083 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007084 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007085 return;
7086 }
7087
John McCall42d7d192010-08-05 09:05:08 +00007088 case Sema::TDK_Underqualified: {
7089 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7090 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7091
7092 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7093
7094 // Param will have been canonicalized, but it should just be a
7095 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007096 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007097 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007098 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007099 assert(S.Context.hasSameType(Param, NonCanonParam));
7100
7101 // Arg has also been canonicalized, but there's nothing we can do
7102 // about that. It also doesn't matter as much, because it won't
7103 // have any template parameters in it (because deduction isn't
7104 // done on dependent types).
7105 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7106
7107 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7108 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007109 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007110 return;
7111 }
7112
7113 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007114 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007115 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007116 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007117 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007118 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007119 which = 1;
7120 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007121 which = 2;
7122 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007123
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007124 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007125 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007126 << *Cand->DeductionFailure.getFirstArg()
7127 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007128 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007129 return;
7130 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007131
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007132 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007133 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007134 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007135 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007136 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7137 << ParamD->getDeclName();
7138 else {
7139 int index = 0;
7140 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7141 index = TTP->getIndex();
7142 else if (NonTypeTemplateParmDecl *NTTP
7143 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7144 index = NTTP->getIndex();
7145 else
7146 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007147 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007148 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7149 << (index + 1);
7150 }
Sebastian Redl08905022011-02-05 19:23:19 +00007151 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007152 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007153
Douglas Gregor02eb4832010-05-08 18:13:28 +00007154 case Sema::TDK_TooManyArguments:
7155 case Sema::TDK_TooFewArguments:
7156 DiagnoseArityMismatch(S, Cand, NumArgs);
7157 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007158
7159 case Sema::TDK_InstantiationDepth:
7160 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007161 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007162 return;
7163
7164 case Sema::TDK_SubstitutionFailure: {
7165 std::string ArgString;
7166 if (TemplateArgumentList *Args
7167 = Cand->DeductionFailure.getTemplateArgumentList())
7168 ArgString = S.getTemplateArgumentBindingsText(
7169 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7170 *Args);
7171 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7172 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007173 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007174 return;
7175 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007176
John McCall8b9ed552010-02-01 18:53:26 +00007177 // TODO: diagnose these individually, then kill off
7178 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007179 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007180 case Sema::TDK_FailedOverloadResolution:
7181 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007182 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007183 return;
7184 }
7185}
7186
7187/// Generates a 'note' diagnostic for an overload candidate. We've
7188/// already generated a primary error at the call site.
7189///
7190/// It really does need to be a single diagnostic with its caret
7191/// pointed at the candidate declaration. Yes, this creates some
7192/// major challenges of technical writing. Yes, this makes pointing
7193/// out problems with specific arguments quite awkward. It's still
7194/// better than generating twenty screens of text for every failed
7195/// overload.
7196///
7197/// It would be great to be able to express per-candidate problems
7198/// more richly for those diagnostic clients that cared, but we'd
7199/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007200void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7201 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007202 FunctionDecl *Fn = Cand->Function;
7203
John McCall12f97bc2010-01-08 04:41:39 +00007204 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007205 if (Cand->Viable && (Fn->isDeleted() ||
7206 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007207 std::string FnDesc;
7208 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007209
7210 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007211 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007212 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007213 return;
John McCall12f97bc2010-01-08 04:41:39 +00007214 }
7215
John McCalle1ac8d12010-01-13 00:25:19 +00007216 // We don't really have anything else to say about viable candidates.
7217 if (Cand->Viable) {
7218 S.NoteOverloadCandidate(Fn);
7219 return;
7220 }
John McCall0d1da222010-01-12 00:44:57 +00007221
John McCall6a61b522010-01-13 09:16:55 +00007222 switch (Cand->FailureKind) {
7223 case ovl_fail_too_many_arguments:
7224 case ovl_fail_too_few_arguments:
7225 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007226
John McCall6a61b522010-01-13 09:16:55 +00007227 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007228 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7229
John McCallfe796dd2010-01-23 05:17:32 +00007230 case ovl_fail_trivial_conversion:
7231 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007232 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007233 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007234
John McCall65eb8792010-02-25 01:37:24 +00007235 case ovl_fail_bad_conversion: {
7236 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7237 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007238 if (Cand->Conversions[I].isBad())
7239 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007240
John McCall6a61b522010-01-13 09:16:55 +00007241 // FIXME: this currently happens when we're called from SemaInit
7242 // when user-conversion overload fails. Figure out how to handle
7243 // those conditions and diagnose them well.
7244 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007245 }
John McCall65eb8792010-02-25 01:37:24 +00007246 }
John McCalld3224162010-01-08 00:58:21 +00007247}
7248
7249void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7250 // Desugar the type of the surrogate down to a function type,
7251 // retaining as many typedefs as possible while still showing
7252 // the function type (and, therefore, its parameter types).
7253 QualType FnType = Cand->Surrogate->getConversionType();
7254 bool isLValueReference = false;
7255 bool isRValueReference = false;
7256 bool isPointer = false;
7257 if (const LValueReferenceType *FnTypeRef =
7258 FnType->getAs<LValueReferenceType>()) {
7259 FnType = FnTypeRef->getPointeeType();
7260 isLValueReference = true;
7261 } else if (const RValueReferenceType *FnTypeRef =
7262 FnType->getAs<RValueReferenceType>()) {
7263 FnType = FnTypeRef->getPointeeType();
7264 isRValueReference = true;
7265 }
7266 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7267 FnType = FnTypePtr->getPointeeType();
7268 isPointer = true;
7269 }
7270 // Desugar down to a function type.
7271 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7272 // Reconstruct the pointer/reference as appropriate.
7273 if (isPointer) FnType = S.Context.getPointerType(FnType);
7274 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7275 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7276
7277 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7278 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007279 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007280}
7281
7282void NoteBuiltinOperatorCandidate(Sema &S,
7283 const char *Opc,
7284 SourceLocation OpLoc,
7285 OverloadCandidate *Cand) {
7286 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7287 std::string TypeStr("operator");
7288 TypeStr += Opc;
7289 TypeStr += "(";
7290 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7291 if (Cand->Conversions.size() == 1) {
7292 TypeStr += ")";
7293 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7294 } else {
7295 TypeStr += ", ";
7296 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7297 TypeStr += ")";
7298 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7299 }
7300}
7301
7302void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7303 OverloadCandidate *Cand) {
7304 unsigned NoOperands = Cand->Conversions.size();
7305 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7306 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007307 if (ICS.isBad()) break; // all meaningless after first invalid
7308 if (!ICS.isAmbiguous()) continue;
7309
John McCall5c32be02010-08-24 20:38:10 +00007310 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007311 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007312 }
7313}
7314
John McCall3712d9e2010-01-15 23:32:50 +00007315SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7316 if (Cand->Function)
7317 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007318 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007319 return Cand->Surrogate->getLocation();
7320 return SourceLocation();
7321}
7322
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007323static unsigned
7324RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00007325 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007326 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00007327 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007328
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007329 case Sema::TDK_Incomplete:
7330 return 1;
7331
7332 case Sema::TDK_Underqualified:
7333 case Sema::TDK_Inconsistent:
7334 return 2;
7335
7336 case Sema::TDK_SubstitutionFailure:
7337 case Sema::TDK_NonDeducedMismatch:
7338 return 3;
7339
7340 case Sema::TDK_InstantiationDepth:
7341 case Sema::TDK_FailedOverloadResolution:
7342 return 4;
7343
7344 case Sema::TDK_InvalidExplicitArguments:
7345 return 5;
7346
7347 case Sema::TDK_TooManyArguments:
7348 case Sema::TDK_TooFewArguments:
7349 return 6;
7350 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007351 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007352}
7353
John McCallad2587a2010-01-12 00:48:53 +00007354struct CompareOverloadCandidatesForDisplay {
7355 Sema &S;
7356 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007357
7358 bool operator()(const OverloadCandidate *L,
7359 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007360 // Fast-path this check.
7361 if (L == R) return false;
7362
John McCall12f97bc2010-01-08 04:41:39 +00007363 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007364 if (L->Viable) {
7365 if (!R->Viable) return true;
7366
7367 // TODO: introduce a tri-valued comparison for overload
7368 // candidates. Would be more worthwhile if we had a sort
7369 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007370 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7371 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007372 } else if (R->Viable)
7373 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007374
John McCall3712d9e2010-01-15 23:32:50 +00007375 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007376
John McCall3712d9e2010-01-15 23:32:50 +00007377 // Criteria by which we can sort non-viable candidates:
7378 if (!L->Viable) {
7379 // 1. Arity mismatches come after other candidates.
7380 if (L->FailureKind == ovl_fail_too_many_arguments ||
7381 L->FailureKind == ovl_fail_too_few_arguments)
7382 return false;
7383 if (R->FailureKind == ovl_fail_too_many_arguments ||
7384 R->FailureKind == ovl_fail_too_few_arguments)
7385 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007386
John McCallfe796dd2010-01-23 05:17:32 +00007387 // 2. Bad conversions come first and are ordered by the number
7388 // of bad conversions and quality of good conversions.
7389 if (L->FailureKind == ovl_fail_bad_conversion) {
7390 if (R->FailureKind != ovl_fail_bad_conversion)
7391 return true;
7392
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007393 // The conversion that can be fixed with a smaller number of changes,
7394 // comes first.
7395 unsigned numLFixes = L->Fix.NumConversionsFixed;
7396 unsigned numRFixes = R->Fix.NumConversionsFixed;
7397 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7398 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007399 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007400 if (numLFixes < numRFixes)
7401 return true;
7402 else
7403 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007404 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007405
John McCallfe796dd2010-01-23 05:17:32 +00007406 // If there's any ordering between the defined conversions...
7407 // FIXME: this might not be transitive.
7408 assert(L->Conversions.size() == R->Conversions.size());
7409
7410 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007411 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7412 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007413 switch (CompareImplicitConversionSequences(S,
7414 L->Conversions[I],
7415 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007416 case ImplicitConversionSequence::Better:
7417 leftBetter++;
7418 break;
7419
7420 case ImplicitConversionSequence::Worse:
7421 leftBetter--;
7422 break;
7423
7424 case ImplicitConversionSequence::Indistinguishable:
7425 break;
7426 }
7427 }
7428 if (leftBetter > 0) return true;
7429 if (leftBetter < 0) return false;
7430
7431 } else if (R->FailureKind == ovl_fail_bad_conversion)
7432 return false;
7433
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007434 if (L->FailureKind == ovl_fail_bad_deduction) {
7435 if (R->FailureKind != ovl_fail_bad_deduction)
7436 return true;
7437
7438 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7439 return RankDeductionFailure(L->DeductionFailure)
7440 <= RankDeductionFailure(R->DeductionFailure);
7441 }
7442
John McCall3712d9e2010-01-15 23:32:50 +00007443 // TODO: others?
7444 }
7445
7446 // Sort everything else by location.
7447 SourceLocation LLoc = GetLocationForCandidate(L);
7448 SourceLocation RLoc = GetLocationForCandidate(R);
7449
7450 // Put candidates without locations (e.g. builtins) at the end.
7451 if (LLoc.isInvalid()) return false;
7452 if (RLoc.isInvalid()) return true;
7453
7454 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007455 }
7456};
7457
John McCallfe796dd2010-01-23 05:17:32 +00007458/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007459/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00007460void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7461 Expr **Args, unsigned NumArgs) {
7462 assert(!Cand->Viable);
7463
7464 // Don't do anything on failures other than bad conversion.
7465 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7466
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007467 // We only want the FixIts if all the arguments can be corrected.
7468 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00007469 // Use a implicit copy initialization to check conversion fixes.
7470 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007471
John McCallfe796dd2010-01-23 05:17:32 +00007472 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007473 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007474 unsigned ConvCount = Cand->Conversions.size();
7475 while (true) {
7476 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7477 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007478 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00007479 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00007480 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007481 }
John McCallfe796dd2010-01-23 05:17:32 +00007482 }
7483
7484 if (ConvIdx == ConvCount)
7485 return;
7486
John McCall65eb8792010-02-25 01:37:24 +00007487 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7488 "remaining conversion is initialized?");
7489
Douglas Gregoradc7a702010-04-16 17:45:54 +00007490 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007491 // operation somehow.
7492 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007493
7494 const FunctionProtoType* Proto;
7495 unsigned ArgIdx = ConvIdx;
7496
7497 if (Cand->IsSurrogate) {
7498 QualType ConvType
7499 = Cand->Surrogate->getConversionType().getNonReferenceType();
7500 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7501 ConvType = ConvPtrType->getPointeeType();
7502 Proto = ConvType->getAs<FunctionProtoType>();
7503 ArgIdx--;
7504 } else if (Cand->Function) {
7505 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7506 if (isa<CXXMethodDecl>(Cand->Function) &&
7507 !isa<CXXConstructorDecl>(Cand->Function))
7508 ArgIdx--;
7509 } else {
7510 // Builtin binary operator with a bad first conversion.
7511 assert(ConvCount <= 3);
7512 for (; ConvIdx != ConvCount; ++ConvIdx)
7513 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007514 = TryCopyInitialization(S, Args[ConvIdx],
7515 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007516 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007517 /*InOverloadResolution*/ true,
7518 /*AllowObjCWritebackConversion=*/
7519 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00007520 return;
7521 }
7522
7523 // Fill in the rest of the conversions.
7524 unsigned NumArgsInProto = Proto->getNumArgs();
7525 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007526 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00007527 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007528 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007529 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007530 /*InOverloadResolution=*/true,
7531 /*AllowObjCWritebackConversion=*/
7532 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007533 // Store the FixIt in the candidate if it exists.
7534 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00007535 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007536 }
John McCallfe796dd2010-01-23 05:17:32 +00007537 else
7538 Cand->Conversions[ConvIdx].setEllipsis();
7539 }
7540}
7541
John McCalld3224162010-01-08 00:58:21 +00007542} // end anonymous namespace
7543
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007544/// PrintOverloadCandidates - When overload resolution fails, prints
7545/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007546/// set.
John McCall5c32be02010-08-24 20:38:10 +00007547void OverloadCandidateSet::NoteCandidates(Sema &S,
7548 OverloadCandidateDisplayKind OCD,
7549 Expr **Args, unsigned NumArgs,
7550 const char *Opc,
7551 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007552 // Sort the candidates by viability and position. Sorting directly would
7553 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007554 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007555 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7556 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007557 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007558 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007559 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007560 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007561 if (Cand->Function || Cand->IsSurrogate)
7562 Cands.push_back(Cand);
7563 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7564 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007565 }
7566 }
7567
John McCallad2587a2010-01-12 00:48:53 +00007568 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007569 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007570
John McCall0d1da222010-01-12 00:44:57 +00007571 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007572
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007573 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00007574 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007575 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007576 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7577 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007578
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007579 // Set an arbitrary limit on the number of candidate functions we'll spam
7580 // the user with. FIXME: This limit should depend on details of the
7581 // candidate list.
7582 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7583 break;
7584 }
7585 ++CandsShown;
7586
John McCalld3224162010-01-08 00:58:21 +00007587 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007588 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007589 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007590 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007591 else {
7592 assert(Cand->Viable &&
7593 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007594 // Generally we only see ambiguities including viable builtin
7595 // operators if overload resolution got screwed up by an
7596 // ambiguous user-defined conversion.
7597 //
7598 // FIXME: It's quite possible for different conversions to see
7599 // different ambiguities, though.
7600 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007601 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007602 ReportedAmbiguousConversions = true;
7603 }
John McCalld3224162010-01-08 00:58:21 +00007604
John McCall0d1da222010-01-12 00:44:57 +00007605 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007606 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007607 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007608 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007609
7610 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007611 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007612}
7613
Douglas Gregorb491ed32011-02-19 21:32:49 +00007614// [PossiblyAFunctionType] --> [Return]
7615// NonFunctionType --> NonFunctionType
7616// R (A) --> R(A)
7617// R (*)(A) --> R (A)
7618// R (&)(A) --> R (A)
7619// R (S::*)(A) --> R (A)
7620QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7621 QualType Ret = PossiblyAFunctionType;
7622 if (const PointerType *ToTypePtr =
7623 PossiblyAFunctionType->getAs<PointerType>())
7624 Ret = ToTypePtr->getPointeeType();
7625 else if (const ReferenceType *ToTypeRef =
7626 PossiblyAFunctionType->getAs<ReferenceType>())
7627 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007628 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007629 PossiblyAFunctionType->getAs<MemberPointerType>())
7630 Ret = MemTypePtr->getPointeeType();
7631 Ret =
7632 Context.getCanonicalType(Ret).getUnqualifiedType();
7633 return Ret;
7634}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007635
Douglas Gregorb491ed32011-02-19 21:32:49 +00007636// A helper class to help with address of function resolution
7637// - allows us to avoid passing around all those ugly parameters
7638class AddressOfFunctionResolver
7639{
7640 Sema& S;
7641 Expr* SourceExpr;
7642 const QualType& TargetType;
7643 QualType TargetFunctionType; // Extracted function type from target type
7644
7645 bool Complain;
7646 //DeclAccessPair& ResultFunctionAccessPair;
7647 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007648
Douglas Gregorb491ed32011-02-19 21:32:49 +00007649 bool TargetTypeIsNonStaticMemberFunction;
7650 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007651
Douglas Gregorb491ed32011-02-19 21:32:49 +00007652 OverloadExpr::FindResult OvlExprInfo;
7653 OverloadExpr *OvlExpr;
7654 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007655 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007656
Douglas Gregorb491ed32011-02-19 21:32:49 +00007657public:
7658 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7659 const QualType& TargetType, bool Complain)
7660 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7661 Complain(Complain), Context(S.getASTContext()),
7662 TargetTypeIsNonStaticMemberFunction(
7663 !!TargetType->getAs<MemberPointerType>()),
7664 FoundNonTemplateFunction(false),
7665 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7666 OvlExpr(OvlExprInfo.Expression)
7667 {
7668 ExtractUnqualifiedFunctionTypeFromTargetType();
7669
7670 if (!TargetFunctionType->isFunctionType()) {
7671 if (OvlExpr->hasExplicitTemplateArgs()) {
7672 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00007673 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00007674 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00007675
7676 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7677 if (!Method->isStatic()) {
7678 // If the target type is a non-function type and the function
7679 // found is a non-static member function, pretend as if that was
7680 // the target, it's the only possible type to end up with.
7681 TargetTypeIsNonStaticMemberFunction = true;
7682
7683 // And skip adding the function if its not in the proper form.
7684 // We'll diagnose this due to an empty set of functions.
7685 if (!OvlExprInfo.HasFormOfMemberPointer)
7686 return;
7687 }
7688 }
7689
Douglas Gregorb491ed32011-02-19 21:32:49 +00007690 Matches.push_back(std::make_pair(dap,Fn));
7691 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007692 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007693 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007694 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007695
7696 if (OvlExpr->hasExplicitTemplateArgs())
7697 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007698
Douglas Gregorb491ed32011-02-19 21:32:49 +00007699 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7700 // C++ [over.over]p4:
7701 // If more than one function is selected, [...]
7702 if (Matches.size() > 1) {
7703 if (FoundNonTemplateFunction)
7704 EliminateAllTemplateMatches();
7705 else
7706 EliminateAllExceptMostSpecializedTemplate();
7707 }
7708 }
7709 }
7710
7711private:
7712 bool isTargetTypeAFunction() const {
7713 return TargetFunctionType->isFunctionType();
7714 }
7715
7716 // [ToType] [Return]
7717
7718 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7719 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7720 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7721 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7722 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7723 }
7724
7725 // return true if any matching specializations were found
7726 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7727 const DeclAccessPair& CurAccessFunPair) {
7728 if (CXXMethodDecl *Method
7729 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7730 // Skip non-static function templates when converting to pointer, and
7731 // static when converting to member pointer.
7732 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7733 return false;
7734 }
7735 else if (TargetTypeIsNonStaticMemberFunction)
7736 return false;
7737
7738 // C++ [over.over]p2:
7739 // If the name is a function template, template argument deduction is
7740 // done (14.8.2.2), and if the argument deduction succeeds, the
7741 // resulting template argument list is used to generate a single
7742 // function template specialization, which is added to the set of
7743 // overloaded functions considered.
7744 FunctionDecl *Specialization = 0;
7745 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7746 if (Sema::TemplateDeductionResult Result
7747 = S.DeduceTemplateArguments(FunctionTemplate,
7748 &OvlExplicitTemplateArgs,
7749 TargetFunctionType, Specialization,
7750 Info)) {
7751 // FIXME: make a note of the failed deduction for diagnostics.
7752 (void)Result;
7753 return false;
7754 }
7755
7756 // Template argument deduction ensures that we have an exact match.
7757 // This function template specicalization works.
7758 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7759 assert(TargetFunctionType
7760 == Context.getCanonicalType(Specialization->getType()));
7761 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7762 return true;
7763 }
7764
7765 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7766 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007767 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007768 // Skip non-static functions when converting to pointer, and static
7769 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007770 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7771 return false;
7772 }
7773 else if (TargetTypeIsNonStaticMemberFunction)
7774 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007775
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007776 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007777 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007778 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7779 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00007780 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
7781 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007782 Matches.push_back(std::make_pair(CurAccessFunPair,
7783 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007784 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007785 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007786 }
Mike Stump11289f42009-09-09 15:08:12 +00007787 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007788
7789 return false;
7790 }
7791
7792 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7793 bool Ret = false;
7794
7795 // If the overload expression doesn't have the form of a pointer to
7796 // member, don't try to convert it to a pointer-to-member type.
7797 if (IsInvalidFormOfPointerToMemberFunction())
7798 return false;
7799
7800 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7801 E = OvlExpr->decls_end();
7802 I != E; ++I) {
7803 // Look through any using declarations to find the underlying function.
7804 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7805
7806 // C++ [over.over]p3:
7807 // Non-member functions and static member functions match
7808 // targets of type "pointer-to-function" or "reference-to-function."
7809 // Nonstatic member functions match targets of
7810 // type "pointer-to-member-function."
7811 // Note that according to DR 247, the containing class does not matter.
7812 if (FunctionTemplateDecl *FunctionTemplate
7813 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7814 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7815 Ret = true;
7816 }
7817 // If we have explicit template arguments supplied, skip non-templates.
7818 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7819 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7820 Ret = true;
7821 }
7822 assert(Ret || Matches.empty());
7823 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007824 }
7825
Douglas Gregorb491ed32011-02-19 21:32:49 +00007826 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00007827 // [...] and any given function template specialization F1 is
7828 // eliminated if the set contains a second function template
7829 // specialization whose function template is more specialized
7830 // than the function template of F1 according to the partial
7831 // ordering rules of 14.5.5.2.
7832
7833 // The algorithm specified above is quadratic. We instead use a
7834 // two-pass algorithm (similar to the one used to identify the
7835 // best viable function in an overload set) that identifies the
7836 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007837
7838 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7839 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7840 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007841
John McCall58cc69d2010-01-27 01:50:18 +00007842 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007843 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7844 TPOC_Other, 0, SourceExpr->getLocStart(),
7845 S.PDiag(),
7846 S.PDiag(diag::err_addr_ovl_ambiguous)
7847 << Matches[0].second->getDeclName(),
7848 S.PDiag(diag::note_ovl_candidate)
7849 << (unsigned) oc_function_template,
7850 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007851
Douglas Gregorb491ed32011-02-19 21:32:49 +00007852 if (Result != MatchesCopy.end()) {
7853 // Make it the first and only element
7854 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7855 Matches[0].second = cast<FunctionDecl>(*Result);
7856 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00007857 }
7858 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007859
Douglas Gregorb491ed32011-02-19 21:32:49 +00007860 void EliminateAllTemplateMatches() {
7861 // [...] any function template specializations in the set are
7862 // eliminated if the set also contains a non-template function, [...]
7863 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7864 if (Matches[I].second->getPrimaryTemplate() == 0)
7865 ++I;
7866 else {
7867 Matches[I] = Matches[--N];
7868 Matches.set_size(N);
7869 }
7870 }
7871 }
7872
7873public:
7874 void ComplainNoMatchesFound() const {
7875 assert(Matches.empty());
7876 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7877 << OvlExpr->getName() << TargetFunctionType
7878 << OvlExpr->getSourceRange();
7879 S.NoteAllOverloadCandidates(OvlExpr);
7880 }
7881
7882 bool IsInvalidFormOfPointerToMemberFunction() const {
7883 return TargetTypeIsNonStaticMemberFunction &&
7884 !OvlExprInfo.HasFormOfMemberPointer;
7885 }
7886
7887 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7888 // TODO: Should we condition this on whether any functions might
7889 // have matched, or is it more appropriate to do that in callers?
7890 // TODO: a fixit wouldn't hurt.
7891 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7892 << TargetType << OvlExpr->getSourceRange();
7893 }
7894
7895 void ComplainOfInvalidConversion() const {
7896 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7897 << OvlExpr->getName() << TargetType;
7898 }
7899
7900 void ComplainMultipleMatchesFound() const {
7901 assert(Matches.size() > 1);
7902 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7903 << OvlExpr->getName()
7904 << OvlExpr->getSourceRange();
7905 S.NoteAllOverloadCandidates(OvlExpr);
7906 }
7907
7908 int getNumMatches() const { return Matches.size(); }
7909
7910 FunctionDecl* getMatchingFunctionDecl() const {
7911 if (Matches.size() != 1) return 0;
7912 return Matches[0].second;
7913 }
7914
7915 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7916 if (Matches.size() != 1) return 0;
7917 return &Matches[0].first;
7918 }
7919};
7920
7921/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7922/// an overloaded function (C++ [over.over]), where @p From is an
7923/// expression with overloaded function type and @p ToType is the type
7924/// we're trying to resolve to. For example:
7925///
7926/// @code
7927/// int f(double);
7928/// int f(int);
7929///
7930/// int (*pfd)(double) = f; // selects f(double)
7931/// @endcode
7932///
7933/// This routine returns the resulting FunctionDecl if it could be
7934/// resolved, and NULL otherwise. When @p Complain is true, this
7935/// routine will emit diagnostics if there is an error.
7936FunctionDecl *
7937Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7938 bool Complain,
7939 DeclAccessPair &FoundResult) {
7940
7941 assert(AddressOfExpr->getType() == Context.OverloadTy);
7942
7943 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7944 int NumMatches = Resolver.getNumMatches();
7945 FunctionDecl* Fn = 0;
7946 if ( NumMatches == 0 && Complain) {
7947 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7948 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7949 else
7950 Resolver.ComplainNoMatchesFound();
7951 }
7952 else if (NumMatches > 1 && Complain)
7953 Resolver.ComplainMultipleMatchesFound();
7954 else if (NumMatches == 1) {
7955 Fn = Resolver.getMatchingFunctionDecl();
7956 assert(Fn);
7957 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7958 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007959 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00007960 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007961 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007962
7963 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007964}
7965
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007966/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007967/// resolve that overloaded function expression down to a single function.
7968///
7969/// This routine can only resolve template-ids that refer to a single function
7970/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007971/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007972/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00007973FunctionDecl *
7974Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
7975 bool Complain,
7976 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007977 // C++ [over.over]p1:
7978 // [...] [Note: any redundant set of parentheses surrounding the
7979 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007980 // C++ [over.over]p1:
7981 // [...] The overloaded function name can be preceded by the &
7982 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007983
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007984 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00007985 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007986 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007987
7988 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00007989 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007990
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007991 // Look through all of the overloaded functions, searching for one
7992 // whose type matches exactly.
7993 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00007994 for (UnresolvedSetIterator I = ovl->decls_begin(),
7995 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007996 // C++0x [temp.arg.explicit]p3:
7997 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007998 // where deduction is not done, if a template argument list is
7999 // specified and it, along with any default template arguments,
8000 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008001 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00008002 FunctionTemplateDecl *FunctionTemplate
8003 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008004
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008005 // C++ [over.over]p2:
8006 // If the name is a function template, template argument deduction is
8007 // done (14.8.2.2), and if the argument deduction succeeds, the
8008 // resulting template argument list is used to generate a single
8009 // function template specialization, which is added to the set of
8010 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008011 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008012 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008013 if (TemplateDeductionResult Result
8014 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8015 Specialization, Info)) {
8016 // FIXME: make a note of the failed deduction for diagnostics.
8017 (void)Result;
8018 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008019 }
8020
John McCall0009fcc2011-04-26 20:42:42 +00008021 assert(Specialization && "no specialization and no error?");
8022
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008023 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008024 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008025 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00008026 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8027 << ovl->getName();
8028 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008029 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008030 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00008031 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008032
John McCall0009fcc2011-04-26 20:42:42 +00008033 Matched = Specialization;
8034 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008035 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008036
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008037 return Matched;
8038}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008039
Douglas Gregor1beec452011-03-12 01:48:56 +00008040
8041
8042
8043// Resolve and fix an overloaded expression that
8044// can be resolved because it identifies a single function
8045// template specialization
8046// Last three arguments should only be supplied if Complain = true
8047ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
John McCall0009fcc2011-04-26 20:42:42 +00008048 Expr *SrcExpr, bool doFunctionPointerConverion, bool complain,
Douglas Gregor1beec452011-03-12 01:48:56 +00008049 const SourceRange& OpRangeForComplaining,
8050 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00008051 unsigned DiagIDForComplaining) {
8052 assert(SrcExpr->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00008053
John McCall0009fcc2011-04-26 20:42:42 +00008054 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr);
Douglas Gregor1beec452011-03-12 01:48:56 +00008055
John McCall0009fcc2011-04-26 20:42:42 +00008056 DeclAccessPair found;
8057 ExprResult SingleFunctionExpression;
8058 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8059 ovl.Expression, /*complain*/ false, &found)) {
8060 if (DiagnoseUseOfDecl(fn, SrcExpr->getSourceRange().getBegin()))
8061 return ExprError();
8062
8063 // It is only correct to resolve to an instance method if we're
8064 // resolving a form that's permitted to be a pointer to member.
8065 // Otherwise we'll end up making a bound member expression, which
8066 // is illegal in all the contexts we resolve like this.
8067 if (!ovl.HasFormOfMemberPointer &&
8068 isa<CXXMethodDecl>(fn) &&
8069 cast<CXXMethodDecl>(fn)->isInstance()) {
8070 if (complain) {
8071 Diag(ovl.Expression->getExprLoc(),
8072 diag::err_invalid_use_of_bound_member_func)
8073 << ovl.Expression->getSourceRange();
8074 // TODO: I believe we only end up here if there's a mix of
8075 // static and non-static candidates (otherwise the expression
8076 // would have 'bound member' type, not 'overload' type).
8077 // Ideally we would note which candidate was chosen and why
8078 // the static candidates were rejected.
8079 }
8080
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008081 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00008082 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008083
John McCall0009fcc2011-04-26 20:42:42 +00008084 // Fix the expresion to refer to 'fn'.
8085 SingleFunctionExpression =
8086 Owned(FixOverloadedFunctionReference(SrcExpr, found, fn));
8087
8088 // If desired, do function-to-pointer decay.
8089 if (doFunctionPointerConverion)
8090 SingleFunctionExpression =
8091 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
8092 }
8093
8094 if (!SingleFunctionExpression.isUsable()) {
8095 if (complain) {
8096 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8097 << ovl.Expression->getName()
8098 << DestTypeForComplaining
8099 << OpRangeForComplaining
8100 << ovl.Expression->getQualifierLoc().getSourceRange();
8101 NoteAllOverloadCandidates(SrcExpr);
8102 }
8103 return ExprError();
8104 }
8105
8106 return SingleFunctionExpression;
Douglas Gregor1beec452011-03-12 01:48:56 +00008107}
8108
Douglas Gregorcabea402009-09-22 15:41:20 +00008109/// \brief Add a single candidate to the overload set.
8110static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00008111 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008112 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008113 Expr **Args, unsigned NumArgs,
8114 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008115 bool PartialOverloading,
8116 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00008117 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00008118 if (isa<UsingShadowDecl>(Callee))
8119 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8120
Douglas Gregorcabea402009-09-22 15:41:20 +00008121 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00008122 if (ExplicitTemplateArgs) {
8123 assert(!KnownValid && "Explicit template arguments?");
8124 return;
8125 }
John McCalla0296f72010-03-19 07:35:19 +00008126 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00008127 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008128 return;
John McCalld14a8642009-11-21 08:51:07 +00008129 }
8130
8131 if (FunctionTemplateDecl *FuncTemplate
8132 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00008133 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8134 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00008135 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00008136 return;
8137 }
8138
Richard Smith95ce4f62011-06-26 22:19:54 +00008139 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00008140}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008141
Douglas Gregorcabea402009-09-22 15:41:20 +00008142/// \brief Add the overload candidates named by callee and/or found by argument
8143/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00008144void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00008145 Expr **Args, unsigned NumArgs,
8146 OverloadCandidateSet &CandidateSet,
8147 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00008148
8149#ifndef NDEBUG
8150 // Verify that ArgumentDependentLookup is consistent with the rules
8151 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00008152 //
Douglas Gregorcabea402009-09-22 15:41:20 +00008153 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8154 // and let Y be the lookup set produced by argument dependent
8155 // lookup (defined as follows). If X contains
8156 //
8157 // -- a declaration of a class member, or
8158 //
8159 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00008160 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00008161 //
8162 // -- a declaration that is neither a function or a function
8163 // template
8164 //
8165 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00008166
John McCall57500772009-12-16 12:17:52 +00008167 if (ULE->requiresADL()) {
8168 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8169 E = ULE->decls_end(); I != E; ++I) {
8170 assert(!(*I)->getDeclContext()->isRecord());
8171 assert(isa<UsingShadowDecl>(*I) ||
8172 !(*I)->getDeclContext()->isFunctionOrMethod());
8173 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008174 }
8175 }
8176#endif
8177
John McCall57500772009-12-16 12:17:52 +00008178 // It would be nice to avoid this copy.
8179 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008180 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008181 if (ULE->hasExplicitTemplateArgs()) {
8182 ULE->copyTemplateArgumentsInto(TABuffer);
8183 ExplicitTemplateArgs = &TABuffer;
8184 }
8185
8186 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8187 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008188 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008189 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008190 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008191
John McCall57500772009-12-16 12:17:52 +00008192 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008193 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8194 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008195 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008196 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008197 PartialOverloading,
8198 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008199}
John McCalld681c392009-12-16 08:11:27 +00008200
Richard Smith998a5912011-06-05 22:42:48 +00008201/// Attempt to recover from an ill-formed use of a non-dependent name in a
8202/// template, where the non-dependent name was declared after the template
8203/// was defined. This is common in code written for a compilers which do not
8204/// correctly implement two-stage name lookup.
8205///
8206/// Returns true if a viable candidate was found and a diagnostic was issued.
8207static bool
8208DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8209 const CXXScopeSpec &SS, LookupResult &R,
8210 TemplateArgumentListInfo *ExplicitTemplateArgs,
8211 Expr **Args, unsigned NumArgs) {
8212 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8213 return false;
8214
8215 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8216 SemaRef.LookupQualifiedName(R, DC);
8217
8218 if (!R.empty()) {
8219 R.suppressDiagnostics();
8220
8221 if (isa<CXXRecordDecl>(DC)) {
8222 // Don't diagnose names we find in classes; we get much better
8223 // diagnostics for these from DiagnoseEmptyLookup.
8224 R.clear();
8225 return false;
8226 }
8227
8228 OverloadCandidateSet Candidates(FnLoc);
8229 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8230 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8231 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008232 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008233
8234 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008235 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008236 // No viable functions. Don't bother the user with notes for functions
8237 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008238 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008239 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008240 }
Richard Smith998a5912011-06-05 22:42:48 +00008241
8242 // Find the namespaces where ADL would have looked, and suggest
8243 // declaring the function there instead.
8244 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8245 Sema::AssociatedClassSet AssociatedClasses;
8246 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8247 AssociatedNamespaces,
8248 AssociatedClasses);
8249 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008250 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008251 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008252 for (Sema::AssociatedNamespaceSet::iterator
8253 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008254 end = AssociatedNamespaces.end(); it != end; ++it) {
8255 if (!Std->Encloses(*it))
8256 SuggestedNamespaces.insert(*it);
8257 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008258 } else {
8259 // Lacking the 'std::' namespace, use all of the associated namespaces.
8260 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008261 }
8262
8263 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8264 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008265 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008266 SemaRef.Diag(Best->Function->getLocation(),
8267 diag::note_not_found_by_two_phase_lookup)
8268 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008269 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008270 SemaRef.Diag(Best->Function->getLocation(),
8271 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008272 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008273 } else {
8274 // FIXME: It would be useful to list the associated namespaces here,
8275 // but the diagnostics infrastructure doesn't provide a way to produce
8276 // a localized representation of a list of items.
8277 SemaRef.Diag(Best->Function->getLocation(),
8278 diag::note_not_found_by_two_phase_lookup)
8279 << R.getLookupName() << 2;
8280 }
8281
8282 // Try to recover by calling this function.
8283 return true;
8284 }
8285
8286 R.clear();
8287 }
8288
8289 return false;
8290}
8291
8292/// Attempt to recover from ill-formed use of a non-dependent operator in a
8293/// template, where the non-dependent operator was declared after the template
8294/// was defined.
8295///
8296/// Returns true if a viable candidate was found and a diagnostic was issued.
8297static bool
8298DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8299 SourceLocation OpLoc,
8300 Expr **Args, unsigned NumArgs) {
8301 DeclarationName OpName =
8302 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8303 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8304 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8305 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8306}
8307
John McCalld681c392009-12-16 08:11:27 +00008308/// Attempts to recover from a call where no functions were found.
8309///
8310/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008311static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008312BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008313 UnresolvedLookupExpr *ULE,
8314 SourceLocation LParenLoc,
8315 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008316 SourceLocation RParenLoc,
8317 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008318
8319 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008320 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008321
John McCall57500772009-12-16 12:17:52 +00008322 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008323 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008324 if (ULE->hasExplicitTemplateArgs()) {
8325 ULE->copyTemplateArgumentsInto(TABuffer);
8326 ExplicitTemplateArgs = &TABuffer;
8327 }
8328
John McCalld681c392009-12-16 08:11:27 +00008329 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8330 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008331 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8332 ExplicitTemplateArgs, Args, NumArgs) &&
8333 (!EmptyLookup ||
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00008334 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00008335 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00008336 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008337
John McCall57500772009-12-16 12:17:52 +00008338 assert(!R.empty() && "lookup results empty despite recovery");
8339
8340 // Build an implicit member call if appropriate. Just drop the
8341 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008342 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008343 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008344 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8345 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008346 else if (ExplicitTemplateArgs)
8347 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8348 else
8349 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8350
8351 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008352 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008353
8354 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008355 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008356 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008357 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008358 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008359}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008360
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008361/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008362/// (which eventually refers to the declaration Func) and the call
8363/// arguments Args/NumArgs, attempt to resolve the function call down
8364/// to a specific function. If overload resolution succeeds, returns
8365/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008366/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008367/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008368ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008369Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008370 SourceLocation LParenLoc,
8371 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008372 SourceLocation RParenLoc,
8373 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008374#ifndef NDEBUG
8375 if (ULE->requiresADL()) {
8376 // To do ADL, we must have found an unqualified name.
8377 assert(!ULE->getQualifier() && "qualified name with ADL");
8378
8379 // We don't perform ADL for implicit declarations of builtins.
8380 // Verify that this was correctly set up.
8381 FunctionDecl *F;
8382 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8383 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8384 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00008385 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008386
John McCall57500772009-12-16 12:17:52 +00008387 // We don't perform ADL in C.
8388 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008389 } else
8390 assert(!ULE->isStdAssociatedNamespace() &&
8391 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008392#endif
8393
John McCallbc077cf2010-02-08 23:07:23 +00008394 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008395
John McCall57500772009-12-16 12:17:52 +00008396 // Add the functions denoted by the callee to the set of candidate
8397 // functions, including those from argument-dependent lookup.
8398 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008399
8400 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008401 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8402 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00008403 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008404 // In Microsoft mode, if we are inside a template class member function then
8405 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00008406 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008407 // classes.
8408 if (getLangOptions().MicrosoftExt && CurContext->isDependentContext() &&
8409 isa<CXXMethodDecl>(CurContext)) {
8410 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8411 Context.DependentTy, VK_RValue,
8412 RParenLoc);
8413 CE->setTypeDependent(true);
8414 return Owned(CE);
8415 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008416 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008417 RParenLoc, /*EmptyLookup=*/true);
Francois Pichetbcf64712011-09-07 00:14:57 +00008418 }
John McCalld681c392009-12-16 08:11:27 +00008419
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008420 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008421 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008422 case OR_Success: {
8423 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008424 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008425 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008426 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
8427 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008428 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008429 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8430 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008431 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008432
Richard Smith998a5912011-06-05 22:42:48 +00008433 case OR_No_Viable_Function: {
8434 // Try to recover by looking for viable functions which the user might
8435 // have meant to call.
8436 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8437 Args, NumArgs, RParenLoc,
8438 /*EmptyLookup=*/false);
8439 if (!Recovery.isInvalid())
8440 return Recovery;
8441
Chris Lattner45d9d602009-02-17 07:29:20 +00008442 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008443 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008444 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008445 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008446 break;
Richard Smith998a5912011-06-05 22:42:48 +00008447 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008448
8449 case OR_Ambiguous:
8450 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008451 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008452 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008453 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008454
8455 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008456 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008457 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8458 << Best->Function->isDeleted()
8459 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008460 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008461 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008462 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8463 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008464 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008465 }
8466
Douglas Gregorb412e172010-07-25 18:17:45 +00008467 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00008468 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008469}
8470
John McCall4c4c1df2010-01-26 03:27:55 +00008471static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00008472 return Functions.size() > 1 ||
8473 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8474}
8475
Douglas Gregor084d8552009-03-13 23:49:33 +00008476/// \brief Create a unary operation that may resolve to an overloaded
8477/// operator.
8478///
8479/// \param OpLoc The location of the operator itself (e.g., '*').
8480///
8481/// \param OpcIn The UnaryOperator::Opcode that describes this
8482/// operator.
8483///
8484/// \param Functions The set of non-member functions that will be
8485/// considered by overload resolution. The caller needs to build this
8486/// set based on the context using, e.g.,
8487/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8488/// set should not contain any member functions; those will be added
8489/// by CreateOverloadedUnaryOp().
8490///
8491/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00008492ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00008493Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8494 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00008495 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008496 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00008497
8498 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8499 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8500 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008501 // TODO: provide better source location info.
8502 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008503
John Wiegley01296292011-04-08 18:41:53 +00008504 if (Input->getObjectKind() == OK_ObjCProperty) {
8505 ExprResult Result = ConvertPropertyForRValue(Input);
8506 if (Result.isInvalid())
8507 return ExprError();
8508 Input = Result.take();
8509 }
John McCalle26a8722010-12-04 08:14:53 +00008510
Douglas Gregor084d8552009-03-13 23:49:33 +00008511 Expr *Args[2] = { Input, 0 };
8512 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00008513
Douglas Gregor084d8552009-03-13 23:49:33 +00008514 // For post-increment and post-decrement, add the implicit '0' as
8515 // the second argument, so that we know this is a post-increment or
8516 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00008517 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008518 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008519 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8520 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00008521 NumArgs = 2;
8522 }
8523
8524 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00008525 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00008526 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008527 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00008528 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008529 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00008530 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008531
John McCall58cc69d2010-01-27 01:50:18 +00008532 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00008533 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008534 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008535 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008536 /*ADL*/ true, IsOverloaded(Fns),
8537 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00008538 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008539 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00008540 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008541 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00008542 OpLoc));
8543 }
8544
8545 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008546 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008547
8548 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008549 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00008550
8551 // Add operator candidates that are member functions.
8552 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8553
John McCall4c4c1df2010-01-26 03:27:55 +00008554 // Add candidates from ADL.
8555 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00008556 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00008557 /*ExplicitTemplateArgs*/ 0,
8558 CandidateSet);
8559
Douglas Gregor084d8552009-03-13 23:49:33 +00008560 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008561 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00008562
8563 // Perform overload resolution.
8564 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008565 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008566 case OR_Success: {
8567 // We found a built-in operator or an overloaded operator.
8568 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00008569
Douglas Gregor084d8552009-03-13 23:49:33 +00008570 if (FnDecl) {
8571 // We matched an overloaded operator. Build a call to that
8572 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00008573
Chandler Carruth30141632011-02-25 19:41:05 +00008574 MarkDeclarationReferenced(OpLoc, FnDecl);
8575
Douglas Gregor084d8552009-03-13 23:49:33 +00008576 // Convert the arguments.
8577 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00008578 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008579
John Wiegley01296292011-04-08 18:41:53 +00008580 ExprResult InputRes =
8581 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8582 Best->FoundDecl, Method);
8583 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008584 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008585 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008586 } else {
8587 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008588 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00008589 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008590 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00008591 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008592 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00008593 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00008594 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008595 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008596 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008597 }
8598
John McCall4fa0d5f2010-05-06 18:15:07 +00008599 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8600
John McCall7decc9e2010-11-18 06:31:45 +00008601 // Determine the result type.
8602 QualType ResultTy = FnDecl->getResultType();
8603 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8604 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00008605
Douglas Gregor084d8552009-03-13 23:49:33 +00008606 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008607 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl);
8608 if (FnExpr.isInvalid())
8609 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00008610
Eli Friedman030eee42009-11-18 03:58:17 +00008611 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00008612 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008613 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008614 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00008615
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008616 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00008617 FnDecl))
8618 return ExprError();
8619
John McCallb268a282010-08-23 23:25:46 +00008620 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00008621 } else {
8622 // We matched a built-in operator. Convert the arguments, then
8623 // break out so that we will build the appropriate built-in
8624 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008625 ExprResult InputRes =
8626 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8627 Best->Conversions[0], AA_Passing);
8628 if (InputRes.isInvalid())
8629 return ExprError();
8630 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008631 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00008632 }
John Wiegley01296292011-04-08 18:41:53 +00008633 }
8634
8635 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00008636 // This is an erroneous use of an operator which can be overloaded by
8637 // a non-member function. Check for non-member operators which were
8638 // defined too late to be candidates.
8639 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8640 // FIXME: Recover by calling the found function.
8641 return ExprError();
8642
John Wiegley01296292011-04-08 18:41:53 +00008643 // No viable function; fall through to handling this as a
8644 // built-in operator, which will produce an error message for us.
8645 break;
8646
8647 case OR_Ambiguous:
8648 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8649 << UnaryOperator::getOpcodeStr(Opc)
8650 << Input->getType()
8651 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008652 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00008653 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8654 return ExprError();
8655
8656 case OR_Deleted:
8657 Diag(OpLoc, diag::err_ovl_deleted_oper)
8658 << Best->Function->isDeleted()
8659 << UnaryOperator::getOpcodeStr(Opc)
8660 << getDeletedOrUnavailableSuffix(Best->Function)
8661 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008662 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
8663 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00008664 return ExprError();
8665 }
Douglas Gregor084d8552009-03-13 23:49:33 +00008666
8667 // Either we found no viable overloaded operator or we matched a
8668 // built-in operator. In either case, fall through to trying to
8669 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00008670 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008671}
8672
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008673/// \brief Create a binary operation that may resolve to an overloaded
8674/// operator.
8675///
8676/// \param OpLoc The location of the operator itself (e.g., '+').
8677///
8678/// \param OpcIn The BinaryOperator::Opcode that describes this
8679/// operator.
8680///
8681/// \param Functions The set of non-member functions that will be
8682/// considered by overload resolution. The caller needs to build this
8683/// set based on the context using, e.g.,
8684/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8685/// set should not contain any member functions; those will be added
8686/// by CreateOverloadedBinOp().
8687///
8688/// \param LHS Left-hand argument.
8689/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00008690ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008691Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008692 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00008693 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008694 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008695 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00008696 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008697
8698 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8699 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8700 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8701
8702 // If either side is type-dependent, create an appropriate dependent
8703 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00008704 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00008705 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008706 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00008707 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00008708 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00008709 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00008710 Context.DependentTy,
8711 VK_RValue, OK_Ordinary,
8712 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008713
Douglas Gregor5287f092009-11-05 00:51:44 +00008714 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8715 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008716 VK_LValue,
8717 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00008718 Context.DependentTy,
8719 Context.DependentTy,
8720 OpLoc));
8721 }
John McCall4c4c1df2010-01-26 03:27:55 +00008722
8723 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00008724 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008725 // TODO: provide better source location info in DNLoc component.
8726 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00008727 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00008728 = UnresolvedLookupExpr::Create(Context, NamingClass,
8729 NestedNameSpecifierLoc(), OpNameInfo,
8730 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008731 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008732 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00008733 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008734 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008735 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008736 OpLoc));
8737 }
8738
John McCalle26a8722010-12-04 08:14:53 +00008739 // Always do property rvalue conversions on the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008740 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8741 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8742 if (Result.isInvalid())
8743 return ExprError();
8744 Args[1] = Result.take();
8745 }
John McCalle26a8722010-12-04 08:14:53 +00008746
8747 // The LHS is more complicated.
8748 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8749
8750 // There's a tension for assignment operators between primitive
8751 // property assignment and the overloaded operators.
8752 if (BinaryOperator::isAssignmentOp(Opc)) {
8753 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8754
8755 // Is the property "logically" settable?
8756 bool Settable = (PRE->isExplicitProperty() ||
8757 PRE->getImplicitPropertySetter());
8758
8759 // To avoid gratuitously inventing semantics, use the primitive
8760 // unless it isn't. Thoughts in case we ever really care:
8761 // - If the property isn't logically settable, we have to
8762 // load and hope.
8763 // - If the property is settable and this is simple assignment,
8764 // we really should use the primitive.
8765 // - If the property is settable, then we could try overloading
8766 // on a generic lvalue of the appropriate type; if it works
8767 // out to a builtin candidate, we would do that same operation
8768 // on the property, and otherwise just error.
8769 if (Settable)
8770 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8771 }
8772
John Wiegley01296292011-04-08 18:41:53 +00008773 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8774 if (Result.isInvalid())
8775 return ExprError();
8776 Args[0] = Result.take();
John McCalle26a8722010-12-04 08:14:53 +00008777 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008778
Sebastian Redl6a96bf72009-11-18 23:10:33 +00008779 // If this is the assignment operator, we only perform overload resolution
8780 // if the left-hand side is a class or enumeration type. This is actually
8781 // a hack. The standard requires that we do overload resolution between the
8782 // various built-in candidates, but as DR507 points out, this can lead to
8783 // problems. So we do it this way, which pretty much follows what GCC does.
8784 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00008785 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00008786 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008787
John McCalle26a8722010-12-04 08:14:53 +00008788 // If this is the .* operator, which is not overloadable, just
8789 // create a built-in binary operator.
8790 if (Opc == BO_PtrMemD)
8791 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8792
Douglas Gregor084d8552009-03-13 23:49:33 +00008793 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008794 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008795
8796 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008797 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008798
8799 // Add operator candidates that are member functions.
8800 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8801
John McCall4c4c1df2010-01-26 03:27:55 +00008802 // Add candidates from ADL.
8803 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8804 Args, 2,
8805 /*ExplicitTemplateArgs*/ 0,
8806 CandidateSet);
8807
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008808 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008809 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008810
8811 // Perform overload resolution.
8812 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008813 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00008814 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008815 // We found a built-in operator or an overloaded operator.
8816 FunctionDecl *FnDecl = Best->Function;
8817
8818 if (FnDecl) {
8819 // We matched an overloaded operator. Build a call to that
8820 // operator.
8821
Chandler Carruth30141632011-02-25 19:41:05 +00008822 MarkDeclarationReferenced(OpLoc, FnDecl);
8823
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008824 // Convert the arguments.
8825 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00008826 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00008827 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008828
Chandler Carruth8e543b32010-12-12 08:17:55 +00008829 ExprResult Arg1 =
8830 PerformCopyInitialization(
8831 InitializedEntity::InitializeParameter(Context,
8832 FnDecl->getParamDecl(0)),
8833 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008834 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008835 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008836
John Wiegley01296292011-04-08 18:41:53 +00008837 ExprResult Arg0 =
8838 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8839 Best->FoundDecl, Method);
8840 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008841 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008842 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008843 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008844 } else {
8845 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00008846 ExprResult Arg0 = PerformCopyInitialization(
8847 InitializedEntity::InitializeParameter(Context,
8848 FnDecl->getParamDecl(0)),
8849 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008850 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008851 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008852
Chandler Carruth8e543b32010-12-12 08:17:55 +00008853 ExprResult Arg1 =
8854 PerformCopyInitialization(
8855 InitializedEntity::InitializeParameter(Context,
8856 FnDecl->getParamDecl(1)),
8857 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008858 if (Arg1.isInvalid())
8859 return ExprError();
8860 Args[0] = LHS = Arg0.takeAs<Expr>();
8861 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008862 }
8863
John McCall4fa0d5f2010-05-06 18:15:07 +00008864 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8865
John McCall7decc9e2010-11-18 06:31:45 +00008866 // Determine the result type.
8867 QualType ResultTy = FnDecl->getResultType();
8868 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8869 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008870
8871 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008872 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
8873 if (FnExpr.isInvalid())
8874 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008875
John McCallb268a282010-08-23 23:25:46 +00008876 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008877 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008878 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008879
8880 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008881 FnDecl))
8882 return ExprError();
8883
John McCallb268a282010-08-23 23:25:46 +00008884 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008885 } else {
8886 // We matched a built-in operator. Convert the arguments, then
8887 // break out so that we will build the appropriate built-in
8888 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008889 ExprResult ArgsRes0 =
8890 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8891 Best->Conversions[0], AA_Passing);
8892 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008893 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008894 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008895
John Wiegley01296292011-04-08 18:41:53 +00008896 ExprResult ArgsRes1 =
8897 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8898 Best->Conversions[1], AA_Passing);
8899 if (ArgsRes1.isInvalid())
8900 return ExprError();
8901 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008902 break;
8903 }
8904 }
8905
Douglas Gregor66950a32009-09-30 21:46:01 +00008906 case OR_No_Viable_Function: {
8907 // C++ [over.match.oper]p9:
8908 // If the operator is the operator , [...] and there are no
8909 // viable functions, then the operator is assumed to be the
8910 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00008911 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00008912 break;
8913
Chandler Carruth8e543b32010-12-12 08:17:55 +00008914 // For class as left operand for assignment or compound assigment
8915 // operator do not fall through to handling in built-in, but report that
8916 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00008917 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008918 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00008919 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00008920 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8921 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00008922 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00008923 } else {
Richard Smith998a5912011-06-05 22:42:48 +00008924 // This is an erroneous use of an operator which can be overloaded by
8925 // a non-member function. Check for non-member operators which were
8926 // defined too late to be candidates.
8927 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
8928 // FIXME: Recover by calling the found function.
8929 return ExprError();
8930
Douglas Gregor66950a32009-09-30 21:46:01 +00008931 // No viable function; try to create a built-in operation, which will
8932 // produce an error. Then, show the non-viable candidates.
8933 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00008934 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008935 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00008936 "C++ binary operator overloading is missing candidates!");
8937 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00008938 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8939 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00008940 return move(Result);
8941 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008942
8943 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008944 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008945 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00008946 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00008947 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008948 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8949 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008950 return ExprError();
8951
8952 case OR_Deleted:
8953 Diag(OpLoc, diag::err_ovl_deleted_oper)
8954 << Best->Function->isDeleted()
8955 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008956 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00008957 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008958 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8959 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008960 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00008961 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008962
Douglas Gregor66950a32009-09-30 21:46:01 +00008963 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00008964 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008965}
8966
John McCalldadc5752010-08-24 06:29:42 +00008967ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00008968Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8969 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00008970 Expr *Base, Expr *Idx) {
8971 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00008972 DeclarationName OpName =
8973 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8974
8975 // If either side is type-dependent, create an appropriate dependent
8976 // expression.
8977 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8978
John McCall58cc69d2010-01-27 01:50:18 +00008979 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008980 // CHECKME: no 'operator' keyword?
8981 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8982 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00008983 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008984 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008985 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008986 /*ADL*/ true, /*Overloaded*/ false,
8987 UnresolvedSetIterator(),
8988 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00008989 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00008990
Sebastian Redladba46e2009-10-29 20:17:01 +00008991 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8992 Args, 2,
8993 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008994 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00008995 RLoc));
8996 }
8997
John Wiegley01296292011-04-08 18:41:53 +00008998 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8999 ExprResult Result = ConvertPropertyForRValue(Args[0]);
9000 if (Result.isInvalid())
9001 return ExprError();
9002 Args[0] = Result.take();
9003 }
9004 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
9005 ExprResult Result = ConvertPropertyForRValue(Args[1]);
9006 if (Result.isInvalid())
9007 return ExprError();
9008 Args[1] = Result.take();
9009 }
John McCalle26a8722010-12-04 08:14:53 +00009010
Sebastian Redladba46e2009-10-29 20:17:01 +00009011 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009012 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009013
9014 // Subscript can only be overloaded as a member function.
9015
9016 // Add operator candidates that are member functions.
9017 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9018
9019 // Add builtin operator candidates.
9020 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9021
9022 // Perform overload resolution.
9023 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009024 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00009025 case OR_Success: {
9026 // We found a built-in operator or an overloaded operator.
9027 FunctionDecl *FnDecl = Best->Function;
9028
9029 if (FnDecl) {
9030 // We matched an overloaded operator. Build a call to that
9031 // operator.
9032
Chandler Carruth30141632011-02-25 19:41:05 +00009033 MarkDeclarationReferenced(LLoc, FnDecl);
9034
John McCalla0296f72010-03-19 07:35:19 +00009035 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009036 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00009037
Sebastian Redladba46e2009-10-29 20:17:01 +00009038 // Convert the arguments.
9039 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00009040 ExprResult Arg0 =
9041 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9042 Best->FoundDecl, Method);
9043 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009044 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009045 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009046
Anders Carlssona68e51e2010-01-29 18:37:50 +00009047 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009048 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00009049 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009050 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00009051 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009052 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00009053 Owned(Args[1]));
9054 if (InputInit.isInvalid())
9055 return ExprError();
9056
9057 Args[1] = InputInit.takeAs<Expr>();
9058
Sebastian Redladba46e2009-10-29 20:17:01 +00009059 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00009060 QualType ResultTy = FnDecl->getResultType();
9061 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9062 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00009063
9064 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00009065 DeclarationNameLoc LocInfo;
9066 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9067 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
9068 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00009069 if (FnExpr.isInvalid())
9070 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009071
John McCallb268a282010-08-23 23:25:46 +00009072 CXXOperatorCallExpr *TheCall =
9073 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00009074 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00009075 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009076
John McCallb268a282010-08-23 23:25:46 +00009077 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00009078 FnDecl))
9079 return ExprError();
9080
John McCallb268a282010-08-23 23:25:46 +00009081 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00009082 } else {
9083 // We matched a built-in operator. Convert the arguments, then
9084 // break out so that we will build the appropriate built-in
9085 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009086 ExprResult ArgsRes0 =
9087 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9088 Best->Conversions[0], AA_Passing);
9089 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009090 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009091 Args[0] = ArgsRes0.take();
9092
9093 ExprResult ArgsRes1 =
9094 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9095 Best->Conversions[1], AA_Passing);
9096 if (ArgsRes1.isInvalid())
9097 return ExprError();
9098 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009099
9100 break;
9101 }
9102 }
9103
9104 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00009105 if (CandidateSet.empty())
9106 Diag(LLoc, diag::err_ovl_no_oper)
9107 << Args[0]->getType() << /*subscript*/ 0
9108 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9109 else
9110 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9111 << Args[0]->getType()
9112 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009113 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9114 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00009115 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009116 }
9117
9118 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009119 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009120 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00009121 << Args[0]->getType() << Args[1]->getType()
9122 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009123 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9124 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009125 return ExprError();
9126
9127 case OR_Deleted:
9128 Diag(LLoc, diag::err_ovl_deleted_oper)
9129 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009130 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00009131 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009132 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9133 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009134 return ExprError();
9135 }
9136
9137 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00009138 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009139}
9140
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009141/// BuildCallToMemberFunction - Build a call to a member
9142/// function. MemExpr is the expression that refers to the member
9143/// function (and includes the object parameter), Args/NumArgs are the
9144/// arguments to the function call (not including the object
9145/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00009146/// expression refers to a non-static member function or an overloaded
9147/// member function.
John McCalldadc5752010-08-24 06:29:42 +00009148ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00009149Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9150 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009151 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00009152 assert(MemExprE->getType() == Context.BoundMemberTy ||
9153 MemExprE->getType() == Context.OverloadTy);
9154
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009155 // Dig out the member expression. This holds both the object
9156 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00009157 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009158
John McCall0009fcc2011-04-26 20:42:42 +00009159 // Determine whether this is a call to a pointer-to-member function.
9160 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9161 assert(op->getType() == Context.BoundMemberTy);
9162 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9163
9164 QualType fnType =
9165 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9166
9167 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9168 QualType resultType = proto->getCallResultType(Context);
9169 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9170
9171 // Check that the object type isn't more qualified than the
9172 // member function we're calling.
9173 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9174
9175 QualType objectType = op->getLHS()->getType();
9176 if (op->getOpcode() == BO_PtrMemI)
9177 objectType = objectType->castAs<PointerType>()->getPointeeType();
9178 Qualifiers objectQuals = objectType.getQualifiers();
9179
9180 Qualifiers difference = objectQuals - funcQuals;
9181 difference.removeObjCGCAttr();
9182 difference.removeAddressSpace();
9183 if (difference) {
9184 std::string qualsString = difference.getAsString();
9185 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9186 << fnType.getUnqualifiedType()
9187 << qualsString
9188 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9189 }
9190
9191 CXXMemberCallExpr *call
9192 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9193 resultType, valueKind, RParenLoc);
9194
9195 if (CheckCallReturnType(proto->getResultType(),
9196 op->getRHS()->getSourceRange().getBegin(),
9197 call, 0))
9198 return ExprError();
9199
9200 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9201 return ExprError();
9202
9203 return MaybeBindToTemporary(call);
9204 }
9205
John McCall10eae182009-11-30 22:42:35 +00009206 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009207 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009208 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009209 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009210 if (isa<MemberExpr>(NakedMemExpr)) {
9211 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009212 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009213 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009214 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00009215 } else {
9216 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009217 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009218
John McCall6e9f8f62009-12-03 04:06:58 +00009219 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009220 Expr::Classification ObjectClassification
9221 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9222 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009223
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009224 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009225 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009226
John McCall2d74de92009-12-01 22:10:20 +00009227 // FIXME: avoid copy.
9228 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9229 if (UnresExpr->hasExplicitTemplateArgs()) {
9230 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9231 TemplateArgs = &TemplateArgsBuffer;
9232 }
9233
John McCall10eae182009-11-30 22:42:35 +00009234 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9235 E = UnresExpr->decls_end(); I != E; ++I) {
9236
John McCall6e9f8f62009-12-03 04:06:58 +00009237 NamedDecl *Func = *I;
9238 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9239 if (isa<UsingShadowDecl>(Func))
9240 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9241
Douglas Gregor02824322011-01-26 19:30:28 +00009242
Francois Pichet64225792011-01-18 05:04:39 +00009243 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +00009244 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +00009245 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9246 CandidateSet);
9247 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009248 // If explicit template arguments were provided, we can't call a
9249 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009250 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009251 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009252
John McCalla0296f72010-03-19 07:35:19 +00009253 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009254 ObjectClassification,
9255 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009256 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009257 } else {
John McCall10eae182009-11-30 22:42:35 +00009258 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009259 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009260 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009261 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009262 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009263 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009264 }
Mike Stump11289f42009-09-09 15:08:12 +00009265
John McCall10eae182009-11-30 22:42:35 +00009266 DeclarationName DeclName = UnresExpr->getMemberName();
9267
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009268 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009269 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009270 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009271 case OR_Success:
9272 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009273 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009274 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009275 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009276 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009277 break;
9278
9279 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009280 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009281 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009282 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009283 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009284 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009285 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009286
9287 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009288 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009289 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009290 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009291 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009292 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009293
9294 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009295 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009296 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009297 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009298 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009299 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009300 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009301 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009302 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009303 }
9304
John McCall16df1e52010-03-30 21:47:33 +00009305 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009306
John McCall2d74de92009-12-01 22:10:20 +00009307 // If overload resolution picked a static member, build a
9308 // non-member call based on that function.
9309 if (Method->isStatic()) {
9310 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9311 Args, NumArgs, RParenLoc);
9312 }
9313
John McCall10eae182009-11-30 22:42:35 +00009314 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009315 }
9316
John McCall7decc9e2010-11-18 06:31:45 +00009317 QualType ResultType = Method->getResultType();
9318 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9319 ResultType = ResultType.getNonLValueExprType(Context);
9320
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009321 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009322 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009323 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009324 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009325
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009326 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009327 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009328 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009329 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009330
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009331 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009332 // We only need to do this if there was actually an overload; otherwise
9333 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009334 if (!Method->isStatic()) {
9335 ExprResult ObjectArg =
9336 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9337 FoundDecl, Method);
9338 if (ObjectArg.isInvalid())
9339 return ExprError();
9340 MemExpr->setBase(ObjectArg.take());
9341 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009342
9343 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009344 const FunctionProtoType *Proto =
9345 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009346 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009347 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009348 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009349
John McCallb268a282010-08-23 23:25:46 +00009350 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009351 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009352
Anders Carlsson47061ee2011-05-06 14:25:31 +00009353 if ((isa<CXXConstructorDecl>(CurContext) ||
9354 isa<CXXDestructorDecl>(CurContext)) &&
9355 TheCall->getMethodDecl()->isPure()) {
9356 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9357
Chandler Carruth59259262011-06-27 08:31:58 +00009358 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009359 Diag(MemExpr->getLocStart(),
9360 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9361 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9362 << MD->getParent()->getDeclName();
9363
9364 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009365 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009366 }
John McCallb268a282010-08-23 23:25:46 +00009367 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009368}
9369
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009370/// BuildCallToObjectOfClassType - Build a call to an object of class
9371/// type (C++ [over.call.object]), which can end up invoking an
9372/// overloaded function call operator (@c operator()) or performing a
9373/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009374ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009375Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009376 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009377 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009378 SourceLocation RParenLoc) {
John Wiegley01296292011-04-08 18:41:53 +00009379 ExprResult Object = Owned(Obj);
9380 if (Object.get()->getObjectKind() == OK_ObjCProperty) {
9381 Object = ConvertPropertyForRValue(Object.take());
9382 if (Object.isInvalid())
9383 return ExprError();
9384 }
John McCalle26a8722010-12-04 08:14:53 +00009385
John Wiegley01296292011-04-08 18:41:53 +00009386 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9387 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009388
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009389 // C++ [over.call.object]p1:
9390 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009391 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009392 // candidate functions includes at least the function call
9393 // operators of T. The function call operators of T are obtained by
9394 // ordinary lookup of the name operator() in the context of
9395 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009396 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009397 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009398
John Wiegley01296292011-04-08 18:41:53 +00009399 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009400 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009401 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009402 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009403
John McCall27b18f82009-11-17 02:14:36 +00009404 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9405 LookupQualifiedName(R, Record->getDecl());
9406 R.suppressDiagnostics();
9407
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009408 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009409 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009410 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9411 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009412 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009413 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009414
Douglas Gregorab7897a2008-11-19 22:57:39 +00009415 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009416 // In addition, for each (non-explicit in C++0x) conversion function
9417 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +00009418 //
9419 // operator conversion-type-id () cv-qualifier;
9420 //
9421 // where cv-qualifier is the same cv-qualification as, or a
9422 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009423 // denotes the type "pointer to function of (P1,...,Pn) returning
9424 // R", or the type "reference to pointer to function of
9425 // (P1,...,Pn) returning R", or the type "reference to function
9426 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009427 // is also considered as a candidate function. Similarly,
9428 // surrogate call functions are added to the set of candidate
9429 // functions for each conversion function declared in an
9430 // accessible base class provided the function is not hidden
9431 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009432 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009433 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009434 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009435 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009436 NamedDecl *D = *I;
9437 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9438 if (isa<UsingShadowDecl>(D))
9439 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009440
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009441 // Skip over templated conversion functions; they aren't
9442 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009443 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009444 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009445
John McCall6e9f8f62009-12-03 04:06:58 +00009446 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009447 if (!Conv->isExplicit()) {
9448 // Strip the reference type (if any) and then the pointer type (if
9449 // any) to get down to what might be a function type.
9450 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9451 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9452 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +00009453
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009454 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9455 {
9456 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9457 Object.get(), Args, NumArgs, CandidateSet);
9458 }
9459 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00009460 }
Mike Stump11289f42009-09-09 15:08:12 +00009461
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009462 // Perform overload resolution.
9463 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009464 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009465 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009466 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009467 // Overload resolution succeeded; we'll build the appropriate call
9468 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009469 break;
9470
9471 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009472 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009473 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9474 << Object.get()->getType() << /*call*/ 1
9475 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009476 else
John Wiegley01296292011-04-08 18:41:53 +00009477 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009478 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009479 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009480 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009481 break;
9482
9483 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009484 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009485 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009486 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009487 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009488 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009489
9490 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00009491 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00009492 diag::err_ovl_deleted_object_call)
9493 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +00009494 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009495 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +00009496 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009497 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009498 break;
Mike Stump11289f42009-09-09 15:08:12 +00009499 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009500
Douglas Gregorb412e172010-07-25 18:17:45 +00009501 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009502 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009503
Douglas Gregorab7897a2008-11-19 22:57:39 +00009504 if (Best->Function == 0) {
9505 // Since there is no function declaration, this is one of the
9506 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00009507 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00009508 = cast<CXXConversionDecl>(
9509 Best->Conversions[0].UserDefined.ConversionFunction);
9510
John Wiegley01296292011-04-08 18:41:53 +00009511 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009512 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009513
Douglas Gregorab7897a2008-11-19 22:57:39 +00009514 // We selected one of the surrogate functions that converts the
9515 // object parameter to a function pointer. Perform the conversion
9516 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009517
Fariborz Jahanian774cf792009-09-28 18:35:46 +00009518 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00009519 // and then call it.
John Wiegley01296292011-04-08 18:41:53 +00009520 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv);
Douglas Gregor668443e2011-01-20 00:18:04 +00009521 if (Call.isInvalid())
9522 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009523
Douglas Gregor668443e2011-01-20 00:18:04 +00009524 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00009525 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00009526 }
9527
Chandler Carruth30141632011-02-25 19:41:05 +00009528 MarkDeclarationReferenced(LParenLoc, Best->Function);
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 found an overloaded operator(). Build a CXXOperatorCallExpr
9533 // that calls this method, using Object for the implicit object
9534 // parameter and passing along the remaining arguments.
9535 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00009536 const FunctionProtoType *Proto =
9537 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009538
9539 unsigned NumArgsInProto = Proto->getNumArgs();
9540 unsigned NumArgsToCheck = NumArgs;
9541
9542 // Build the full argument list for the method call (the
9543 // implicit object parameter is placed at the beginning of the
9544 // list).
9545 Expr **MethodArgs;
9546 if (NumArgs < NumArgsInProto) {
9547 NumArgsToCheck = NumArgsInProto;
9548 MethodArgs = new Expr*[NumArgsInProto + 1];
9549 } else {
9550 MethodArgs = new Expr*[NumArgs + 1];
9551 }
John Wiegley01296292011-04-08 18:41:53 +00009552 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009553 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9554 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00009555
John Wiegley01296292011-04-08 18:41:53 +00009556 ExprResult NewFn = CreateFunctionRefExpr(*this, Method);
9557 if (NewFn.isInvalid())
9558 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009559
9560 // Once we've built TheCall, all of the expressions are properly
9561 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00009562 QualType ResultTy = Method->getResultType();
9563 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9564 ResultTy = ResultTy.getNonLValueExprType(Context);
9565
John McCallb268a282010-08-23 23:25:46 +00009566 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009567 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +00009568 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00009569 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009570 delete [] MethodArgs;
9571
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009572 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00009573 Method))
9574 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009575
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009576 // We may have default arguments. If so, we need to allocate more
9577 // slots in the call for them.
9578 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00009579 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009580 else if (NumArgs > NumArgsInProto)
9581 NumArgsToCheck = NumArgsInProto;
9582
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009583 bool IsError = false;
9584
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009585 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +00009586 ExprResult ObjRes =
9587 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9588 Best->FoundDecl, Method);
9589 if (ObjRes.isInvalid())
9590 IsError = true;
9591 else
9592 Object = move(ObjRes);
9593 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009594
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009595 // Check the argument types.
9596 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009597 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009598 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009599 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00009600
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009601 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009602
John McCalldadc5752010-08-24 06:29:42 +00009603 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009604 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009605 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009606 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00009607 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009608
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009609 IsError |= InputInit.isInvalid();
9610 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009611 } else {
John McCalldadc5752010-08-24 06:29:42 +00009612 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009613 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9614 if (DefArg.isInvalid()) {
9615 IsError = true;
9616 break;
9617 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009618
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009619 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009620 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009621
9622 TheCall->setArg(i + 1, Arg);
9623 }
9624
9625 // If this is a variadic call, handle args passed through "...".
9626 if (Proto->isVariadic()) {
9627 // Promote the arguments (C99 6.5.2.2p7).
9628 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +00009629 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9630 IsError |= Arg.isInvalid();
9631 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009632 }
9633 }
9634
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009635 if (IsError) return true;
9636
John McCallb268a282010-08-23 23:25:46 +00009637 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00009638 return true;
9639
John McCalle172be52010-08-24 06:09:16 +00009640 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009641}
9642
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009643/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00009644/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009645/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00009646ExprResult
John McCallb268a282010-08-23 23:25:46 +00009647Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009648 assert(Base->getType()->isRecordType() &&
9649 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00009650
John Wiegley01296292011-04-08 18:41:53 +00009651 if (Base->getObjectKind() == OK_ObjCProperty) {
9652 ExprResult Result = ConvertPropertyForRValue(Base);
9653 if (Result.isInvalid())
9654 return ExprError();
9655 Base = Result.take();
9656 }
John McCalle26a8722010-12-04 08:14:53 +00009657
John McCallbc077cf2010-02-08 23:07:23 +00009658 SourceLocation Loc = Base->getExprLoc();
9659
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009660 // C++ [over.ref]p1:
9661 //
9662 // [...] An expression x->m is interpreted as (x.operator->())->m
9663 // for a class object x of type T if T::operator->() exists and if
9664 // the operator is selected as the best match function by the
9665 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00009666 DeclarationName OpName =
9667 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00009668 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009669 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00009670
John McCallbc077cf2010-02-08 23:07:23 +00009671 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00009672 PDiag(diag::err_typecheck_incomplete_tag)
9673 << Base->getSourceRange()))
9674 return ExprError();
9675
John McCall27b18f82009-11-17 02:14:36 +00009676 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9677 LookupQualifiedName(R, BaseRecord->getDecl());
9678 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00009679
9680 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00009681 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00009682 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9683 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00009684 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009685
9686 // Perform overload resolution.
9687 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009688 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009689 case OR_Success:
9690 // Overload resolution succeeded; we'll build the call below.
9691 break;
9692
9693 case OR_No_Viable_Function:
9694 if (CandidateSet.empty())
9695 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00009696 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009697 else
9698 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00009699 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009700 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009701 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009702
9703 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009704 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9705 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009706 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009707 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009708
9709 case OR_Deleted:
9710 Diag(OpLoc, diag::err_ovl_deleted_oper)
9711 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009712 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009713 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009714 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009715 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009716 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009717 }
9718
Chandler Carruth30141632011-02-25 19:41:05 +00009719 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00009720 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009721 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00009722
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009723 // Convert the object parameter.
9724 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009725 ExprResult BaseResult =
9726 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9727 Best->FoundDecl, Method);
9728 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +00009729 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009730 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +00009731
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009732 // Build the operator call.
John Wiegley01296292011-04-08 18:41:53 +00009733 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method);
9734 if (FnExpr.isInvalid())
9735 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009736
John McCall7decc9e2010-11-18 06:31:45 +00009737 QualType ResultTy = Method->getResultType();
9738 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9739 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00009740 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009741 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009742 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009743
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009744 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009745 Method))
9746 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +00009747
9748 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009749}
9750
Douglas Gregorcd695e52008-11-10 20:40:00 +00009751/// FixOverloadedFunctionReference - E is an expression that refers to
9752/// a C++ overloaded function (possibly with some parentheses and
9753/// perhaps a '&' around it). We have resolved the overloaded function
9754/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00009755/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00009756Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00009757 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00009758 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009759 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9760 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009761 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009762 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009763
Douglas Gregor51c538b2009-11-20 19:42:02 +00009764 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009765 }
9766
Douglas Gregor51c538b2009-11-20 19:42:02 +00009767 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009768 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9769 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009770 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00009771 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00009772 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00009773 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00009774 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009775 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009776
9777 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +00009778 ICE->getCastKind(),
9779 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00009780 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009781 }
9782
Douglas Gregor51c538b2009-11-20 19:42:02 +00009783 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00009784 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00009785 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009786 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9787 if (Method->isStatic()) {
9788 // Do nothing: static member functions aren't any different
9789 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00009790 } else {
John McCalle66edc12009-11-24 19:00:30 +00009791 // Fix the sub expression, which really has to be an
9792 // UnresolvedLookupExpr holding an overloaded member function
9793 // or template.
John McCall16df1e52010-03-30 21:47:33 +00009794 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9795 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00009796 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009797 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00009798
John McCalld14a8642009-11-21 08:51:07 +00009799 assert(isa<DeclRefExpr>(SubExpr)
9800 && "fixed to something other than a decl ref");
9801 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9802 && "fixed to a member ref with no nested name qualifier");
9803
9804 // We have taken the address of a pointer to member
9805 // function. Perform the computation here so that we get the
9806 // appropriate pointer to member type.
9807 QualType ClassType
9808 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9809 QualType MemPtrType
9810 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9811
John McCall7decc9e2010-11-18 06:31:45 +00009812 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9813 VK_RValue, OK_Ordinary,
9814 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009815 }
9816 }
John McCall16df1e52010-03-30 21:47:33 +00009817 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9818 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009819 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009820 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009821
John McCalle3027922010-08-25 11:45:40 +00009822 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009823 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00009824 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009825 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009826 }
John McCalld14a8642009-11-21 08:51:07 +00009827
9828 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00009829 // FIXME: avoid copy.
9830 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00009831 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00009832 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9833 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00009834 }
9835
John McCalld14a8642009-11-21 08:51:07 +00009836 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009837 ULE->getQualifierLoc(),
John McCalld14a8642009-11-21 08:51:07 +00009838 Fn,
9839 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009840 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009841 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009842 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009843 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00009844 }
9845
John McCall10eae182009-11-30 22:42:35 +00009846 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00009847 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00009848 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9849 if (MemExpr->hasExplicitTemplateArgs()) {
9850 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9851 TemplateArgs = &TemplateArgsBuffer;
9852 }
John McCall6b51f282009-11-23 01:53:49 +00009853
John McCall2d74de92009-12-01 22:10:20 +00009854 Expr *Base;
9855
John McCall7decc9e2010-11-18 06:31:45 +00009856 // If we're filling in a static method where we used to have an
9857 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00009858 if (MemExpr->isImplicitAccess()) {
9859 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9860 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009861 MemExpr->getQualifierLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009862 Fn,
9863 MemExpr->getMemberLoc(),
9864 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009865 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009866 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009867 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00009868 } else {
9869 SourceLocation Loc = MemExpr->getMemberLoc();
9870 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +00009871 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +00009872 Base = new (Context) CXXThisExpr(Loc,
9873 MemExpr->getBaseType(),
9874 /*isImplicit=*/true);
9875 }
John McCall2d74de92009-12-01 22:10:20 +00009876 } else
John McCallc3007a22010-10-26 07:05:15 +00009877 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00009878
John McCall4adb38c2011-04-27 00:36:17 +00009879 ExprValueKind valueKind;
9880 QualType type;
9881 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9882 valueKind = VK_LValue;
9883 type = Fn->getType();
9884 } else {
9885 valueKind = VK_RValue;
9886 type = Context.BoundMemberTy;
9887 }
9888
John McCall2d74de92009-12-01 22:10:20 +00009889 return MemberExpr::Create(Context, Base,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009890 MemExpr->isArrow(),
Douglas Gregorea972d32011-02-28 21:54:11 +00009891 MemExpr->getQualifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009892 Fn,
John McCall16df1e52010-03-30 21:47:33 +00009893 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009894 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00009895 TemplateArgs,
John McCall4adb38c2011-04-27 00:36:17 +00009896 type, valueKind, OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009897 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009898
John McCallc3007a22010-10-26 07:05:15 +00009899 llvm_unreachable("Invalid reference to overloaded function");
9900 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009901}
9902
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009903ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +00009904 DeclAccessPair Found,
9905 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00009906 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00009907}
9908
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009909} // end namespace clang