blob: c0b83d9b47aef441f9776cf224ec44dbf61a033a [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,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000912 AssignmentAction Action, bool AllowExplicit) {
913 ImplicitConversionSequence ICS;
914 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
915}
916
John Wiegley01296292011-04-08 18:41:53 +0000917ExprResult
918Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000919 AssignmentAction Action, bool AllowExplicit,
920 ImplicitConversionSequence& ICS) {
John McCall31168b02011-06-15 23:02:42 +0000921 // Objective-C ARC: Determine whether we will allow the writeback conversion.
922 bool AllowObjCWritebackConversion
923 = getLangOptions().ObjCAutoRefCount &&
924 (Action == AA_Passing || Action == AA_Sending);
925
926
John McCall5c32be02010-08-24 20:38:10 +0000927 ICS = clang::TryImplicitConversion(*this, From, ToType,
928 /*SuppressUserConversions=*/false,
929 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000930 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +0000931 /*CStyle=*/false,
932 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000933 return PerformImplicitConversion(From, ToType, ICS, Action);
934}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000935
936/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000937/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +0000938bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
939 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000940 if (Context.hasSameUnqualifiedType(FromType, ToType))
941 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000942
John McCall991eb4b2010-12-21 00:44:39 +0000943 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
944 // where F adds one of the following at most once:
945 // - a pointer
946 // - a member pointer
947 // - a block pointer
948 CanQualType CanTo = Context.getCanonicalType(ToType);
949 CanQualType CanFrom = Context.getCanonicalType(FromType);
950 Type::TypeClass TyClass = CanTo->getTypeClass();
951 if (TyClass != CanFrom->getTypeClass()) return false;
952 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
953 if (TyClass == Type::Pointer) {
954 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
955 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
956 } else if (TyClass == Type::BlockPointer) {
957 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
958 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
959 } else if (TyClass == Type::MemberPointer) {
960 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
961 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
962 } else {
963 return false;
964 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000965
John McCall991eb4b2010-12-21 00:44:39 +0000966 TyClass = CanTo->getTypeClass();
967 if (TyClass != CanFrom->getTypeClass()) return false;
968 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
969 return false;
970 }
971
972 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
973 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
974 if (!EInfo.getNoReturn()) return false;
975
976 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
977 assert(QualType(FromFn, 0).isCanonical());
978 if (QualType(FromFn, 0) != CanTo) return false;
979
980 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000981 return true;
982}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000983
Douglas Gregor46188682010-05-18 22:42:18 +0000984/// \brief Determine whether the conversion from FromType to ToType is a valid
985/// vector conversion.
986///
987/// \param ICK Will be set to the vector conversion kind, if this is a vector
988/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000989static bool IsVectorConversion(ASTContext &Context, QualType FromType,
990 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +0000991 // We need at least one of these types to be a vector type to have a vector
992 // conversion.
993 if (!ToType->isVectorType() && !FromType->isVectorType())
994 return false;
995
996 // Identical types require no conversions.
997 if (Context.hasSameUnqualifiedType(FromType, ToType))
998 return false;
999
1000 // There are no conversions between extended vector types, only identity.
1001 if (ToType->isExtVectorType()) {
1002 // There are no conversions between extended vector types other than the
1003 // identity conversion.
1004 if (FromType->isExtVectorType())
1005 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001006
Douglas Gregor46188682010-05-18 22:42:18 +00001007 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001008 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001009 ICK = ICK_Vector_Splat;
1010 return true;
1011 }
1012 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001013
1014 // We can perform the conversion between vector types in the following cases:
1015 // 1)vector types are equivalent AltiVec and GCC vector types
1016 // 2)lax vector conversions are permitted and the vector types are of the
1017 // same size
1018 if (ToType->isVectorType() && FromType->isVectorType()) {
1019 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001020 (Context.getLangOptions().LaxVectorConversions &&
1021 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001022 ICK = ICK_Vector_Conversion;
1023 return true;
1024 }
Douglas Gregor46188682010-05-18 22:42:18 +00001025 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001026
Douglas Gregor46188682010-05-18 22:42:18 +00001027 return false;
1028}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001029
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001030/// IsStandardConversion - Determines whether there is a standard
1031/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1032/// expression From to the type ToType. Standard conversion sequences
1033/// only consider non-class types; for conversions that involve class
1034/// types, use TryImplicitConversion. If a conversion exists, SCS will
1035/// contain the standard conversion sequence required to perform this
1036/// conversion and this routine will return true. Otherwise, this
1037/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001038static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1039 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001040 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001041 bool CStyle,
1042 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001043 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001044
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001045 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001046 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001047 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001048 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001049 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001050 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001051
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001052 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001053 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001054 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001055 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001056 return false;
1057
Mike Stump11289f42009-09-09 15:08:12 +00001058 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001059 }
1060
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001061 // The first conversion can be an lvalue-to-rvalue conversion,
1062 // array-to-pointer conversion, or function-to-pointer conversion
1063 // (C++ 4p1).
1064
John McCall5c32be02010-08-24 20:38:10 +00001065 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001066 DeclAccessPair AccessPair;
1067 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001068 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001069 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001070 // We were able to resolve the address of the overloaded function,
1071 // so we can convert to the type of that function.
1072 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001073
1074 // we can sometimes resolve &foo<int> regardless of ToType, so check
1075 // if the type matches (identity) or we are converting to bool
1076 if (!S.Context.hasSameUnqualifiedType(
1077 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1078 QualType resultTy;
1079 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001080 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001081 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1082 // otherwise, only a boolean conversion is standard
1083 if (!ToType->isBooleanType())
1084 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001085 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001086
Chandler Carruthffce2452011-03-29 08:08:18 +00001087 // Check if the "from" expression is taking the address of an overloaded
1088 // function and recompute the FromType accordingly. Take advantage of the
1089 // fact that non-static member functions *must* have such an address-of
1090 // expression.
1091 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1092 if (Method && !Method->isStatic()) {
1093 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1094 "Non-unary operator on non-static member address");
1095 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1096 == UO_AddrOf &&
1097 "Non-address-of operator on non-static member address");
1098 const Type *ClassType
1099 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1100 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001101 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1102 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1103 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001104 "Non-address-of operator for overloaded function expression");
1105 FromType = S.Context.getPointerType(FromType);
1106 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001107
Douglas Gregor980fb162010-04-29 18:24:40 +00001108 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001109 assert(S.Context.hasSameType(
1110 FromType,
1111 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001112 } else {
1113 return false;
1114 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001115 }
John McCall154a2fd2011-08-30 00:57:29 +00001116 // Lvalue-to-rvalue conversion (C++11 4.1):
1117 // A glvalue (3.10) of a non-function, non-array type T can
1118 // be converted to a prvalue.
1119 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001120 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001121 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001122 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001123 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001124
1125 // If T is a non-class type, the type of the rvalue is the
1126 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001127 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1128 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001129 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001130 } else if (FromType->isArrayType()) {
1131 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001132 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001133
1134 // An lvalue or rvalue of type "array of N T" or "array of unknown
1135 // bound of T" can be converted to an rvalue of type "pointer to
1136 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001137 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001138
John McCall5c32be02010-08-24 20:38:10 +00001139 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001140 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001141 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001142
1143 // For the purpose of ranking in overload resolution
1144 // (13.3.3.1.1), this conversion is considered an
1145 // array-to-pointer conversion followed by a qualification
1146 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001147 SCS.Second = ICK_Identity;
1148 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001149 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001150 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001151 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001152 }
John McCall086a4642010-11-24 05:12:34 +00001153 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001154 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001155 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001156
1157 // An lvalue of function type T can be converted to an rvalue of
1158 // type "pointer to T." The result is a pointer to the
1159 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001160 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001161 } else {
1162 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001163 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001164 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001165 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001166
1167 // The second conversion can be an integral promotion, floating
1168 // point promotion, integral conversion, floating point conversion,
1169 // floating-integral conversion, pointer conversion,
1170 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001171 // For overloading in C, this can also be a "compatible-type"
1172 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001173 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001174 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001175 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001176 // The unqualified versions of the types are the same: there's no
1177 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001178 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001179 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001180 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001181 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001182 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001183 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001184 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001185 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001186 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001187 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001188 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001189 SCS.Second = ICK_Complex_Promotion;
1190 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001191 } else if (ToType->isBooleanType() &&
1192 (FromType->isArithmeticType() ||
1193 FromType->isAnyPointerType() ||
1194 FromType->isBlockPointerType() ||
1195 FromType->isMemberPointerType() ||
1196 FromType->isNullPtrType())) {
1197 // Boolean conversions (C++ 4.12).
1198 SCS.Second = ICK_Boolean_Conversion;
1199 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001200 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001201 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001202 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001203 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001204 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001205 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001206 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001207 SCS.Second = ICK_Complex_Conversion;
1208 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001209 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1210 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001211 // Complex-real conversions (C99 6.3.1.7)
1212 SCS.Second = ICK_Complex_Real;
1213 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001214 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001215 // Floating point conversions (C++ 4.8).
1216 SCS.Second = ICK_Floating_Conversion;
1217 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001218 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001219 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001220 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001221 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001222 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001223 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001224 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001225 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001226 SCS.Second = ICK_Block_Pointer_Conversion;
1227 } else if (AllowObjCWritebackConversion &&
1228 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1229 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001230 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1231 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001232 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001233 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001234 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001235 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001236 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001237 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001238 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001239 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001240 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001241 SCS.Second = SecondICK;
1242 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001243 } else if (!S.getLangOptions().CPlusPlus &&
1244 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001245 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001246 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001247 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001248 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001249 // Treat a conversion that strips "noreturn" as an identity conversion.
1250 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001251 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1252 InOverloadResolution,
1253 SCS, CStyle)) {
1254 SCS.Second = ICK_TransparentUnionConversion;
1255 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001256 } else {
1257 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001258 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001259 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001260 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001261
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001262 QualType CanonFrom;
1263 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001264 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001265 bool ObjCLifetimeConversion;
1266 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1267 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001268 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001269 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001270 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001271 CanonFrom = S.Context.getCanonicalType(FromType);
1272 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001273 } else {
1274 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001275 SCS.Third = ICK_Identity;
1276
Mike Stump11289f42009-09-09 15:08:12 +00001277 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001278 // [...] Any difference in top-level cv-qualification is
1279 // subsumed by the initialization itself and does not constitute
1280 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001281 CanonFrom = S.Context.getCanonicalType(FromType);
1282 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001283 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001284 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001285 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001286 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1287 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001288 FromType = ToType;
1289 CanonFrom = CanonTo;
1290 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001291 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001292 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001293
1294 // If we have not converted the argument type to the parameter type,
1295 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001296 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001297 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001298
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001299 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001300}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001301
1302static bool
1303IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1304 QualType &ToType,
1305 bool InOverloadResolution,
1306 StandardConversionSequence &SCS,
1307 bool CStyle) {
1308
1309 const RecordType *UT = ToType->getAsUnionType();
1310 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1311 return false;
1312 // The field to initialize within the transparent union.
1313 RecordDecl *UD = UT->getDecl();
1314 // It's compatible if the expression matches any of the fields.
1315 for (RecordDecl::field_iterator it = UD->field_begin(),
1316 itend = UD->field_end();
1317 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001318 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1319 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001320 ToType = it->getType();
1321 return true;
1322 }
1323 }
1324 return false;
1325}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001326
1327/// IsIntegralPromotion - Determines whether the conversion from the
1328/// expression From (whose potentially-adjusted type is FromType) to
1329/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1330/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001331bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001332 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001333 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001334 if (!To) {
1335 return false;
1336 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001337
1338 // An rvalue of type char, signed char, unsigned char, short int, or
1339 // unsigned short int can be converted to an rvalue of type int if
1340 // int can represent all the values of the source type; otherwise,
1341 // the source rvalue can be converted to an rvalue of type unsigned
1342 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001343 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1344 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001345 if (// We can promote any signed, promotable integer type to an int
1346 (FromType->isSignedIntegerType() ||
1347 // We can promote any unsigned integer type whose size is
1348 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001349 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001350 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001351 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001352 }
1353
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001354 return To->getKind() == BuiltinType::UInt;
1355 }
1356
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001357 // C++0x [conv.prom]p3:
1358 // A prvalue of an unscoped enumeration type whose underlying type is not
1359 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1360 // following types that can represent all the values of the enumeration
1361 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1362 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001363 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001364 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001365 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001366 // with lowest integer conversion rank (4.13) greater than the rank of long
1367 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001368 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001369 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1370 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1371 // provided for a scoped enumeration.
1372 if (FromEnumType->getDecl()->isScoped())
1373 return false;
1374
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001375 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001376 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001377 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001378 return Context.hasSameUnqualifiedType(ToType,
1379 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001380 }
John McCall56774992009-12-09 09:09:27 +00001381
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001382 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001383 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1384 // to an rvalue a prvalue of the first of the following types that can
1385 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001386 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001388 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001389 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001390 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001391 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001392 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001393 // Determine whether the type we're converting from is signed or
1394 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001395 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001396 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001397
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001398 // The types we'll try to promote to, in the appropriate
1399 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001400 QualType PromoteTypes[6] = {
1401 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001402 Context.LongTy, Context.UnsignedLongTy ,
1403 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001404 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001405 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001406 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1407 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001408 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001409 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1410 // We found the type that we can promote to. If this is the
1411 // type we wanted, we have a promotion. Otherwise, no
1412 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001413 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001414 }
1415 }
1416 }
1417
1418 // An rvalue for an integral bit-field (9.6) can be converted to an
1419 // rvalue of type int if int can represent all the values of the
1420 // bit-field; otherwise, it can be converted to unsigned int if
1421 // unsigned int can represent all the values of the bit-field. If
1422 // the bit-field is larger yet, no integral promotion applies to
1423 // it. If the bit-field has an enumerated type, it is treated as any
1424 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001425 // FIXME: We should delay checking of bit-fields until we actually perform the
1426 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001427 using llvm::APSInt;
1428 if (From)
1429 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001430 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001431 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001432 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1433 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1434 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001435
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001436 // Are we promoting to an int from a bitfield that fits in an int?
1437 if (BitWidth < ToSize ||
1438 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1439 return To->getKind() == BuiltinType::Int;
1440 }
Mike Stump11289f42009-09-09 15:08:12 +00001441
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001442 // Are we promoting to an unsigned int from an unsigned bitfield
1443 // that fits into an unsigned int?
1444 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1445 return To->getKind() == BuiltinType::UInt;
1446 }
Mike Stump11289f42009-09-09 15:08:12 +00001447
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001448 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001449 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001450 }
Mike Stump11289f42009-09-09 15:08:12 +00001451
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001452 // An rvalue of type bool can be converted to an rvalue of type int,
1453 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001454 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001455 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001456 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001457
1458 return false;
1459}
1460
1461/// IsFloatingPointPromotion - Determines whether the conversion from
1462/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1463/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001464bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001465 /// An rvalue of type float can be converted to an rvalue of type
1466 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001467 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1468 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001469 if (FromBuiltin->getKind() == BuiltinType::Float &&
1470 ToBuiltin->getKind() == BuiltinType::Double)
1471 return true;
1472
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001473 // C99 6.3.1.5p1:
1474 // When a float is promoted to double or long double, or a
1475 // double is promoted to long double [...].
1476 if (!getLangOptions().CPlusPlus &&
1477 (FromBuiltin->getKind() == BuiltinType::Float ||
1478 FromBuiltin->getKind() == BuiltinType::Double) &&
1479 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1480 return true;
1481 }
1482
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001483 return false;
1484}
1485
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001486/// \brief Determine if a conversion is a complex promotion.
1487///
1488/// A complex promotion is defined as a complex -> complex conversion
1489/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001490/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001491bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001492 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001493 if (!FromComplex)
1494 return false;
1495
John McCall9dd450b2009-09-21 23:43:11 +00001496 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001497 if (!ToComplex)
1498 return false;
1499
1500 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001501 ToComplex->getElementType()) ||
1502 IsIntegralPromotion(0, FromComplex->getElementType(),
1503 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001504}
1505
Douglas Gregor237f96c2008-11-26 23:31:11 +00001506/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1507/// the pointer type FromPtr to a pointer to type ToPointee, with the
1508/// same type qualifiers as FromPtr has on its pointee type. ToType,
1509/// if non-empty, will be a pointer to ToType that may or may not have
1510/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001511///
Mike Stump11289f42009-09-09 15:08:12 +00001512static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001513BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001514 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001515 ASTContext &Context,
1516 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001517 assert((FromPtr->getTypeClass() == Type::Pointer ||
1518 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1519 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001520
John McCall31168b02011-06-15 23:02:42 +00001521 /// Conversions to 'id' subsume cv-qualifier conversions.
1522 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001523 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001524
1525 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001526 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001527 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001528 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001529
John McCall31168b02011-06-15 23:02:42 +00001530 if (StripObjCLifetime)
1531 Quals.removeObjCLifetime();
1532
Mike Stump11289f42009-09-09 15:08:12 +00001533 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001534 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001535 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001536 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001537 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001538
1539 // Build a pointer to ToPointee. It has the right qualifiers
1540 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001541 if (isa<ObjCObjectPointerType>(ToType))
1542 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001543 return Context.getPointerType(ToPointee);
1544 }
1545
1546 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001547 QualType QualifiedCanonToPointee
1548 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001549
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001550 if (isa<ObjCObjectPointerType>(ToType))
1551 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1552 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001553}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001554
Mike Stump11289f42009-09-09 15:08:12 +00001555static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001556 bool InOverloadResolution,
1557 ASTContext &Context) {
1558 // Handle value-dependent integral null pointer constants correctly.
1559 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1560 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001561 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001562 return !InOverloadResolution;
1563
Douglas Gregor56751b52009-09-25 04:25:58 +00001564 return Expr->isNullPointerConstant(Context,
1565 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1566 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001567}
Mike Stump11289f42009-09-09 15:08:12 +00001568
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001569/// IsPointerConversion - Determines whether the conversion of the
1570/// expression From, which has the (possibly adjusted) type FromType,
1571/// can be converted to the type ToType via a pointer conversion (C++
1572/// 4.10). If so, returns true and places the converted type (that
1573/// might differ from ToType in its cv-qualifiers at some level) into
1574/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001575///
Douglas Gregora29dc052008-11-27 01:19:21 +00001576/// This routine also supports conversions to and from block pointers
1577/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1578/// pointers to interfaces. FIXME: Once we've determined the
1579/// appropriate overloading rules for Objective-C, we may want to
1580/// split the Objective-C checks into a different routine; however,
1581/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001582/// conversions, so for now they live here. IncompatibleObjC will be
1583/// set if the conversion is an allowed Objective-C conversion that
1584/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001585bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001586 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001587 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001588 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001589 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001590 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1591 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001592 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001593
Mike Stump11289f42009-09-09 15:08:12 +00001594 // Conversion from a null pointer constant to any Objective-C pointer type.
1595 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001596 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001597 ConvertedType = ToType;
1598 return true;
1599 }
1600
Douglas Gregor231d1c62008-11-27 00:15:41 +00001601 // Blocks: Block pointers can be converted to void*.
1602 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001603 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001604 ConvertedType = ToType;
1605 return true;
1606 }
1607 // Blocks: A null pointer constant can be converted to a block
1608 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001609 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001610 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001611 ConvertedType = ToType;
1612 return true;
1613 }
1614
Sebastian Redl576fd422009-05-10 18:38:11 +00001615 // If the left-hand-side is nullptr_t, the right side can be a null
1616 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001617 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001618 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001619 ConvertedType = ToType;
1620 return true;
1621 }
1622
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001623 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001624 if (!ToTypePtr)
1625 return false;
1626
1627 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001628 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001629 ConvertedType = ToType;
1630 return true;
1631 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001632
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001633 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001634 // , including objective-c pointers.
1635 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001636 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1637 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001638 ConvertedType = BuildSimilarlyQualifiedPointerType(
1639 FromType->getAs<ObjCObjectPointerType>(),
1640 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001641 ToType, Context);
1642 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001643 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001644 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001645 if (!FromTypePtr)
1646 return false;
1647
1648 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001649
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001650 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001651 // pointer conversion, so don't do all of the work below.
1652 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1653 return false;
1654
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001655 // An rvalue of type "pointer to cv T," where T is an object type,
1656 // can be converted to an rvalue of type "pointer to cv void" (C++
1657 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001658 if (FromPointeeType->isIncompleteOrObjectType() &&
1659 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001660 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001661 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001662 ToType, Context,
1663 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001664 return true;
1665 }
1666
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001667 // MSVC allows implicit function to void* type conversion.
1668 if (getLangOptions().Microsoft && FromPointeeType->isFunctionType() &&
1669 ToPointeeType->isVoidType()) {
1670 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1671 ToPointeeType,
1672 ToType, Context);
1673 return true;
1674 }
1675
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001676 // When we're overloading in C, we allow a special kind of pointer
1677 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001678 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001679 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001680 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001681 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001682 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001683 return true;
1684 }
1685
Douglas Gregor5c407d92008-10-23 00:40:37 +00001686 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001687 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001688 // An rvalue of type "pointer to cv D," where D is a class type,
1689 // can be converted to an rvalue of type "pointer to cv B," where
1690 // B is a base class (clause 10) of D. If B is an inaccessible
1691 // (clause 11) or ambiguous (10.2) base class of D, a program that
1692 // necessitates this conversion is ill-formed. The result of the
1693 // conversion is a pointer to the base class sub-object of the
1694 // derived class object. The null pointer value is converted to
1695 // the null pointer value of the destination type.
1696 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001697 // Note that we do not check for ambiguity or inaccessibility
1698 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001699 if (getLangOptions().CPlusPlus &&
1700 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001701 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001702 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001703 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001704 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001705 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001706 ToType, Context);
1707 return true;
1708 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001709
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001710 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1711 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1712 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1713 ToPointeeType,
1714 ToType, Context);
1715 return true;
1716 }
1717
Douglas Gregora119f102008-12-19 19:13:09 +00001718 return false;
1719}
Douglas Gregoraec25842011-04-26 23:16:46 +00001720
1721/// \brief Adopt the given qualifiers for the given type.
1722static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1723 Qualifiers TQs = T.getQualifiers();
1724
1725 // Check whether qualifiers already match.
1726 if (TQs == Qs)
1727 return T;
1728
1729 if (Qs.compatiblyIncludes(TQs))
1730 return Context.getQualifiedType(T, Qs);
1731
1732 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1733}
Douglas Gregora119f102008-12-19 19:13:09 +00001734
1735/// isObjCPointerConversion - Determines whether this is an
1736/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1737/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001738bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001739 QualType& ConvertedType,
1740 bool &IncompatibleObjC) {
1741 if (!getLangOptions().ObjC1)
1742 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001743
Douglas Gregoraec25842011-04-26 23:16:46 +00001744 // The set of qualifiers on the type we're converting from.
1745 Qualifiers FromQualifiers = FromType.getQualifiers();
1746
Steve Naroff7cae42b2009-07-10 23:34:53 +00001747 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001748 const ObjCObjectPointerType* ToObjCPtr =
1749 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001750 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001751 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001752
Steve Naroff7cae42b2009-07-10 23:34:53 +00001753 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001754 // If the pointee types are the same (ignoring qualifications),
1755 // then this is not a pointer conversion.
1756 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1757 FromObjCPtr->getPointeeType()))
1758 return false;
1759
Douglas Gregoraec25842011-04-26 23:16:46 +00001760 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00001761 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001762 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001763 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001764 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001765 return true;
1766 }
1767 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001768 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001769 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001770 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001771 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001772 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001773 return true;
1774 }
1775 // Objective C++: We're able to convert from a pointer to an
1776 // interface to a pointer to a different interface.
1777 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001778 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1779 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1780 if (getLangOptions().CPlusPlus && LHS && RHS &&
1781 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1782 FromObjCPtr->getPointeeType()))
1783 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001784 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001785 ToObjCPtr->getPointeeType(),
1786 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001787 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001788 return true;
1789 }
1790
1791 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1792 // Okay: this is some kind of implicit downcast of Objective-C
1793 // interfaces, which is permitted. However, we're going to
1794 // complain about it.
1795 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001796 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001797 ToObjCPtr->getPointeeType(),
1798 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001799 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001800 return true;
1801 }
Mike Stump11289f42009-09-09 15:08:12 +00001802 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001803 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001804 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001805 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001806 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001807 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001808 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001809 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001810 // to a block pointer type.
1811 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001812 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001813 return true;
1814 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001815 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001816 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001817 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001818 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001819 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001820 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00001821 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001822 return true;
1823 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001824 else
Douglas Gregora119f102008-12-19 19:13:09 +00001825 return false;
1826
Douglas Gregor033f56d2008-12-23 00:53:59 +00001827 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001828 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001829 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001830 else if (const BlockPointerType *FromBlockPtr =
1831 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001832 FromPointeeType = FromBlockPtr->getPointeeType();
1833 else
Douglas Gregora119f102008-12-19 19:13:09 +00001834 return false;
1835
Douglas Gregora119f102008-12-19 19:13:09 +00001836 // If we have pointers to pointers, recursively check whether this
1837 // is an Objective-C conversion.
1838 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1839 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1840 IncompatibleObjC)) {
1841 // We always complain about this conversion.
1842 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001843 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001844 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001845 return true;
1846 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001847 // Allow conversion of pointee being objective-c pointer to another one;
1848 // as in I* to id.
1849 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1850 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1851 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1852 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00001853
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001854 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001855 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001856 return true;
1857 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001858
Douglas Gregor033f56d2008-12-23 00:53:59 +00001859 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001860 // differences in the argument and result types are in Objective-C
1861 // pointer conversions. If so, we permit the conversion (but
1862 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001863 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001864 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001865 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001866 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001867 if (FromFunctionType && ToFunctionType) {
1868 // If the function types are exactly the same, this isn't an
1869 // Objective-C pointer conversion.
1870 if (Context.getCanonicalType(FromPointeeType)
1871 == Context.getCanonicalType(ToPointeeType))
1872 return false;
1873
1874 // Perform the quick checks that will tell us whether these
1875 // function types are obviously different.
1876 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1877 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1878 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1879 return false;
1880
1881 bool HasObjCConversion = false;
1882 if (Context.getCanonicalType(FromFunctionType->getResultType())
1883 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1884 // Okay, the types match exactly. Nothing to do.
1885 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1886 ToFunctionType->getResultType(),
1887 ConvertedType, IncompatibleObjC)) {
1888 // Okay, we have an Objective-C pointer conversion.
1889 HasObjCConversion = true;
1890 } else {
1891 // Function types are too different. Abort.
1892 return false;
1893 }
Mike Stump11289f42009-09-09 15:08:12 +00001894
Douglas Gregora119f102008-12-19 19:13:09 +00001895 // Check argument types.
1896 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1897 ArgIdx != NumArgs; ++ArgIdx) {
1898 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1899 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1900 if (Context.getCanonicalType(FromArgType)
1901 == Context.getCanonicalType(ToArgType)) {
1902 // Okay, the types match exactly. Nothing to do.
1903 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1904 ConvertedType, IncompatibleObjC)) {
1905 // Okay, we have an Objective-C pointer conversion.
1906 HasObjCConversion = true;
1907 } else {
1908 // Argument types are too different. Abort.
1909 return false;
1910 }
1911 }
1912
1913 if (HasObjCConversion) {
1914 // We had an Objective-C conversion. Allow this pointer
1915 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00001916 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001917 IncompatibleObjC = true;
1918 return true;
1919 }
1920 }
1921
Sebastian Redl72b597d2009-01-25 19:43:20 +00001922 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001923}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001924
John McCall31168b02011-06-15 23:02:42 +00001925/// \brief Determine whether this is an Objective-C writeback conversion,
1926/// used for parameter passing when performing automatic reference counting.
1927///
1928/// \param FromType The type we're converting form.
1929///
1930/// \param ToType The type we're converting to.
1931///
1932/// \param ConvertedType The type that will be produced after applying
1933/// this conversion.
1934bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
1935 QualType &ConvertedType) {
1936 if (!getLangOptions().ObjCAutoRefCount ||
1937 Context.hasSameUnqualifiedType(FromType, ToType))
1938 return false;
1939
1940 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
1941 QualType ToPointee;
1942 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
1943 ToPointee = ToPointer->getPointeeType();
1944 else
1945 return false;
1946
1947 Qualifiers ToQuals = ToPointee.getQualifiers();
1948 if (!ToPointee->isObjCLifetimeType() ||
1949 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
1950 !ToQuals.withoutObjCGLifetime().empty())
1951 return false;
1952
1953 // Argument must be a pointer to __strong to __weak.
1954 QualType FromPointee;
1955 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
1956 FromPointee = FromPointer->getPointeeType();
1957 else
1958 return false;
1959
1960 Qualifiers FromQuals = FromPointee.getQualifiers();
1961 if (!FromPointee->isObjCLifetimeType() ||
1962 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
1963 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
1964 return false;
1965
1966 // Make sure that we have compatible qualifiers.
1967 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
1968 if (!ToQuals.compatiblyIncludes(FromQuals))
1969 return false;
1970
1971 // Remove qualifiers from the pointee type we're converting from; they
1972 // aren't used in the compatibility check belong, and we'll be adding back
1973 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
1974 FromPointee = FromPointee.getUnqualifiedType();
1975
1976 // The unqualified form of the pointee types must be compatible.
1977 ToPointee = ToPointee.getUnqualifiedType();
1978 bool IncompatibleObjC;
1979 if (Context.typesAreCompatible(FromPointee, ToPointee))
1980 FromPointee = ToPointee;
1981 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
1982 IncompatibleObjC))
1983 return false;
1984
1985 /// \brief Construct the type we're converting to, which is a pointer to
1986 /// __autoreleasing pointee.
1987 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
1988 ConvertedType = Context.getPointerType(FromPointee);
1989 return true;
1990}
1991
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001992bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1993 QualType& ConvertedType) {
1994 QualType ToPointeeType;
1995 if (const BlockPointerType *ToBlockPtr =
1996 ToType->getAs<BlockPointerType>())
1997 ToPointeeType = ToBlockPtr->getPointeeType();
1998 else
1999 return false;
2000
2001 QualType FromPointeeType;
2002 if (const BlockPointerType *FromBlockPtr =
2003 FromType->getAs<BlockPointerType>())
2004 FromPointeeType = FromBlockPtr->getPointeeType();
2005 else
2006 return false;
2007 // We have pointer to blocks, check whether the only
2008 // differences in the argument and result types are in Objective-C
2009 // pointer conversions. If so, we permit the conversion.
2010
2011 const FunctionProtoType *FromFunctionType
2012 = FromPointeeType->getAs<FunctionProtoType>();
2013 const FunctionProtoType *ToFunctionType
2014 = ToPointeeType->getAs<FunctionProtoType>();
2015
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002016 if (!FromFunctionType || !ToFunctionType)
2017 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002018
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002019 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002020 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002021
2022 // Perform the quick checks that will tell us whether these
2023 // function types are obviously different.
2024 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2025 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2026 return false;
2027
2028 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2029 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2030 if (FromEInfo != ToEInfo)
2031 return false;
2032
2033 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002034 if (Context.hasSameType(FromFunctionType->getResultType(),
2035 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002036 // Okay, the types match exactly. Nothing to do.
2037 } else {
2038 QualType RHS = FromFunctionType->getResultType();
2039 QualType LHS = ToFunctionType->getResultType();
2040 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2041 !RHS.hasQualifiers() && LHS.hasQualifiers())
2042 LHS = LHS.getUnqualifiedType();
2043
2044 if (Context.hasSameType(RHS,LHS)) {
2045 // OK exact match.
2046 } else if (isObjCPointerConversion(RHS, LHS,
2047 ConvertedType, IncompatibleObjC)) {
2048 if (IncompatibleObjC)
2049 return false;
2050 // Okay, we have an Objective-C pointer conversion.
2051 }
2052 else
2053 return false;
2054 }
2055
2056 // Check argument types.
2057 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2058 ArgIdx != NumArgs; ++ArgIdx) {
2059 IncompatibleObjC = false;
2060 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2061 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2062 if (Context.hasSameType(FromArgType, ToArgType)) {
2063 // Okay, the types match exactly. Nothing to do.
2064 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2065 ConvertedType, IncompatibleObjC)) {
2066 if (IncompatibleObjC)
2067 return false;
2068 // Okay, we have an Objective-C pointer conversion.
2069 } else
2070 // Argument types are too different. Abort.
2071 return false;
2072 }
2073 ConvertedType = ToType;
2074 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002075}
2076
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002077/// FunctionArgTypesAreEqual - This routine checks two function proto types
2078/// for equlity of their argument types. Caller has already checked that
2079/// they have same number of arguments. This routine assumes that Objective-C
2080/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002081bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00002082 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002083 if (!getLangOptions().ObjC1)
2084 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2085 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002086
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002087 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2088 N = NewType->arg_type_begin(),
2089 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2090 QualType ToType = (*O);
2091 QualType FromType = (*N);
2092 if (ToType != FromType) {
2093 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2094 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002095 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2096 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2097 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2098 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002099 continue;
2100 }
John McCall8b07ec22010-05-15 11:32:37 +00002101 else if (const ObjCObjectPointerType *PTTo =
2102 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002103 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002104 FromType->getAs<ObjCObjectPointerType>())
2105 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2106 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002107 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002108 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002109 }
2110 }
2111 return true;
2112}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002113
Douglas Gregor39c16d42008-10-24 04:54:22 +00002114/// CheckPointerConversion - Check the pointer conversion from the
2115/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002116/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002117/// conversions for which IsPointerConversion has already returned
2118/// true. It returns true and produces a diagnostic if there was an
2119/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002120bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002121 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002122 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002123 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002124 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002125 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002126
John McCall8cb679e2010-11-15 09:13:47 +00002127 Kind = CK_BitCast;
2128
Chandler Carruthffab8732011-04-09 07:32:05 +00002129 if (!IsCStyleOrFunctionalCast &&
2130 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2131 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2132 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002133 PDiag(diag::warn_impcast_bool_to_null_pointer)
2134 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002135
John McCall9320b872011-09-09 05:25:32 +00002136 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2137 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002138 QualType FromPointeeType = FromPtrType->getPointeeType(),
2139 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002140
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002141 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2142 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002143 // We must have a derived-to-base conversion. Check an
2144 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002145 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2146 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002147 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002148 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002149 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002150
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002151 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002152 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002153 }
2154 }
John McCall9320b872011-09-09 05:25:32 +00002155 } else if (const ObjCObjectPointerType *ToPtrType =
2156 ToType->getAs<ObjCObjectPointerType>()) {
2157 if (const ObjCObjectPointerType *FromPtrType =
2158 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002159 // Objective-C++ conversions are always okay.
2160 // FIXME: We should have a different class of conversions for the
2161 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002162 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002163 return false;
John McCall9320b872011-09-09 05:25:32 +00002164 } else if (FromType->isBlockPointerType()) {
2165 Kind = CK_BlockPointerToObjCPointerCast;
2166 } else {
2167 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002168 }
John McCall9320b872011-09-09 05:25:32 +00002169 } else if (ToType->isBlockPointerType()) {
2170 if (!FromType->isBlockPointerType())
2171 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002172 }
John McCall8cb679e2010-11-15 09:13:47 +00002173
2174 // We shouldn't fall into this case unless it's valid for other
2175 // reasons.
2176 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2177 Kind = CK_NullToPointer;
2178
Douglas Gregor39c16d42008-10-24 04:54:22 +00002179 return false;
2180}
2181
Sebastian Redl72b597d2009-01-25 19:43:20 +00002182/// IsMemberPointerConversion - Determines whether the conversion of the
2183/// expression From, which has the (possibly adjusted) type FromType, can be
2184/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2185/// If so, returns true and places the converted type (that might differ from
2186/// ToType in its cv-qualifiers at some level) into ConvertedType.
2187bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002188 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002189 bool InOverloadResolution,
2190 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002191 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002192 if (!ToTypePtr)
2193 return false;
2194
2195 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002196 if (From->isNullPointerConstant(Context,
2197 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2198 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002199 ConvertedType = ToType;
2200 return true;
2201 }
2202
2203 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002204 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002205 if (!FromTypePtr)
2206 return false;
2207
2208 // A pointer to member of B can be converted to a pointer to member of D,
2209 // where D is derived from B (C++ 4.11p2).
2210 QualType FromClass(FromTypePtr->getClass(), 0);
2211 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002212
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002213 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2214 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2215 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002216 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2217 ToClass.getTypePtr());
2218 return true;
2219 }
2220
2221 return false;
2222}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002223
Sebastian Redl72b597d2009-01-25 19:43:20 +00002224/// CheckMemberPointerConversion - Check the member pointer conversion from the
2225/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002226/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002227/// for which IsMemberPointerConversion has already returned true. It returns
2228/// true and produces a diagnostic if there was an error, or returns false
2229/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002230bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002231 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002232 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002233 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002234 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002235 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002236 if (!FromPtrType) {
2237 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002238 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002239 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002240 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002241 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002242 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002243 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002244
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002245 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002246 assert(ToPtrType && "No member pointer cast has a target type "
2247 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002248
Sebastian Redled8f2002009-01-28 18:33:18 +00002249 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2250 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002251
Sebastian Redled8f2002009-01-28 18:33:18 +00002252 // FIXME: What about dependent types?
2253 assert(FromClass->isRecordType() && "Pointer into non-class.");
2254 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002255
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002256 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002257 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002258 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2259 assert(DerivationOkay &&
2260 "Should not have been called if derivation isn't OK.");
2261 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002262
Sebastian Redled8f2002009-01-28 18:33:18 +00002263 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2264 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002265 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2266 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2267 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2268 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002269 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002270
Douglas Gregor89ee6822009-02-28 01:32:25 +00002271 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002272 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2273 << FromClass << ToClass << QualType(VBase, 0)
2274 << From->getSourceRange();
2275 return true;
2276 }
2277
John McCall5b0829a2010-02-10 09:31:12 +00002278 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002279 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2280 Paths.front(),
2281 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002282
Anders Carlssond7923c62009-08-22 23:33:40 +00002283 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002284 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002285 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002286 return false;
2287}
2288
Douglas Gregor9a657932008-10-21 23:43:52 +00002289/// IsQualificationConversion - Determines whether the conversion from
2290/// an rvalue of type FromType to ToType is a qualification conversion
2291/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002292///
2293/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2294/// when the qualification conversion involves a change in the Objective-C
2295/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002296bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002297Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002298 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002299 FromType = Context.getCanonicalType(FromType);
2300 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002301 ObjCLifetimeConversion = false;
2302
Douglas Gregor9a657932008-10-21 23:43:52 +00002303 // If FromType and ToType are the same type, this is not a
2304 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002305 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002306 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002307
Douglas Gregor9a657932008-10-21 23:43:52 +00002308 // (C++ 4.4p4):
2309 // A conversion can add cv-qualifiers at levels other than the first
2310 // in multi-level pointers, subject to the following rules: [...]
2311 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002312 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002313 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002314 // Within each iteration of the loop, we check the qualifiers to
2315 // determine if this still looks like a qualification
2316 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002317 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002318 // until there are no more pointers or pointers-to-members left to
2319 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002320 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002321
Douglas Gregor90609aa2011-04-25 18:40:17 +00002322 Qualifiers FromQuals = FromType.getQualifiers();
2323 Qualifiers ToQuals = ToType.getQualifiers();
2324
John McCall31168b02011-06-15 23:02:42 +00002325 // Objective-C ARC:
2326 // Check Objective-C lifetime conversions.
2327 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2328 UnwrappedAnyPointer) {
2329 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2330 ObjCLifetimeConversion = true;
2331 FromQuals.removeObjCLifetime();
2332 ToQuals.removeObjCLifetime();
2333 } else {
2334 // Qualification conversions cannot cast between different
2335 // Objective-C lifetime qualifiers.
2336 return false;
2337 }
2338 }
2339
Douglas Gregorf30053d2011-05-08 06:09:53 +00002340 // Allow addition/removal of GC attributes but not changing GC attributes.
2341 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2342 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2343 FromQuals.removeObjCGCAttr();
2344 ToQuals.removeObjCGCAttr();
2345 }
2346
Douglas Gregor9a657932008-10-21 23:43:52 +00002347 // -- for every j > 0, if const is in cv 1,j then const is in cv
2348 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002349 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002350 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002351
Douglas Gregor9a657932008-10-21 23:43:52 +00002352 // -- if the cv 1,j and cv 2,j are different, then const is in
2353 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002354 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002355 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002356 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002357
Douglas Gregor9a657932008-10-21 23:43:52 +00002358 // Keep track of whether all prior cv-qualifiers in the "to" type
2359 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002360 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002361 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002362 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002363
2364 // We are left with FromType and ToType being the pointee types
2365 // after unwrapping the original FromType and ToType the same number
2366 // of types. If we unwrapped any pointers, and if FromType and
2367 // ToType have the same unqualified type (since we checked
2368 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002369 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002370}
2371
Douglas Gregor576e98c2009-01-30 23:27:23 +00002372/// Determines whether there is a user-defined conversion sequence
2373/// (C++ [over.ics.user]) that converts expression From to the type
2374/// ToType. If such a conversion exists, User will contain the
2375/// user-defined conversion sequence that performs such a conversion
2376/// and this routine will return true. Otherwise, this routine returns
2377/// false and User is unspecified.
2378///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002379/// \param AllowExplicit true if the conversion should consider C++0x
2380/// "explicit" conversion functions as well as non-explicit conversion
2381/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002382static OverloadingResult
2383IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2384 UserDefinedConversionSequence& User,
2385 OverloadCandidateSet& CandidateSet,
2386 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002387 // Whether we will only visit constructors.
2388 bool ConstructorsOnly = false;
2389
2390 // If the type we are conversion to is a class type, enumerate its
2391 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002392 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002393 // C++ [over.match.ctor]p1:
2394 // When objects of class type are direct-initialized (8.5), or
2395 // copy-initialized from an expression of the same or a
2396 // derived class type (8.5), overload resolution selects the
2397 // constructor. [...] For copy-initialization, the candidate
2398 // functions are all the converting constructors (12.3.1) of
2399 // that class. The argument list is the expression-list within
2400 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002401 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002402 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002403 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002404 ConstructorsOnly = true;
2405
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002406 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2407 // RequireCompleteType may have returned true due to some invalid decl
2408 // during template instantiation, but ToType may be complete enough now
2409 // to try to recover.
2410 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002411 // We're not going to find any constructors.
2412 } else if (CXXRecordDecl *ToRecordDecl
2413 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002414 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002415 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002416 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002417 NamedDecl *D = *Con;
2418 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2419
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002420 // Find the constructor (which may be a template).
2421 CXXConstructorDecl *Constructor = 0;
2422 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002423 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002424 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002425 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002426 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2427 else
John McCalla0296f72010-03-19 07:35:19 +00002428 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002429
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002430 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002431 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002432 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002433 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2434 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002435 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002436 /*SuppressUserConversions=*/
2437 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002438 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002439 // Allow one user-defined conversion when user specifies a
2440 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002441 S.AddOverloadCandidate(Constructor, FoundDecl,
2442 &From, 1, CandidateSet,
2443 /*SuppressUserConversions=*/
2444 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002445 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002446 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002447 }
2448 }
2449
Douglas Gregor5ab11652010-04-17 22:01:05 +00002450 // Enumerate conversion functions, if we're allowed to.
2451 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002452 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2453 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002454 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002455 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002456 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002457 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002458 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2459 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002460 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002461 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002462 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002463 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002464 DeclAccessPair FoundDecl = I.getPair();
2465 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002466 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2467 if (isa<UsingShadowDecl>(D))
2468 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2469
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002470 CXXConversionDecl *Conv;
2471 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002472 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2473 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002474 else
John McCallda4458e2010-03-31 01:36:47 +00002475 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002476
2477 if (AllowExplicit || !Conv->isExplicit()) {
2478 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002479 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2480 ActingContext, From, ToType,
2481 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002482 else
John McCall5c32be02010-08-24 20:38:10 +00002483 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2484 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002485 }
2486 }
2487 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002488 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002489
2490 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002491 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002492 case OR_Success:
2493 // Record the standard conversion we used and the conversion function.
2494 if (CXXConstructorDecl *Constructor
2495 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002496 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2497
John McCall5c32be02010-08-24 20:38:10 +00002498 // C++ [over.ics.user]p1:
2499 // If the user-defined conversion is specified by a
2500 // constructor (12.3.1), the initial standard conversion
2501 // sequence converts the source type to the type required by
2502 // the argument of the constructor.
2503 //
2504 QualType ThisType = Constructor->getThisType(S.Context);
2505 if (Best->Conversions[0].isEllipsis())
2506 User.EllipsisConversion = true;
2507 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002508 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002509 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002510 }
John McCall5c32be02010-08-24 20:38:10 +00002511 User.ConversionFunction = Constructor;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002512 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002513 User.After.setAsIdentityConversion();
2514 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2515 User.After.setAllToTypes(ToType);
2516 return OR_Success;
2517 } else if (CXXConversionDecl *Conversion
2518 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002519 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2520
John McCall5c32be02010-08-24 20:38:10 +00002521 // C++ [over.ics.user]p1:
2522 //
2523 // [...] If the user-defined conversion is specified by a
2524 // conversion function (12.3.2), the initial standard
2525 // conversion sequence converts the source type to the
2526 // implicit object parameter of the conversion function.
2527 User.Before = Best->Conversions[0].Standard;
2528 User.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002529 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002530 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002531
John McCall5c32be02010-08-24 20:38:10 +00002532 // C++ [over.ics.user]p2:
2533 // The second standard conversion sequence converts the
2534 // result of the user-defined conversion to the target type
2535 // for the sequence. Since an implicit conversion sequence
2536 // is an initialization, the special rules for
2537 // initialization by user-defined conversion apply when
2538 // selecting the best user-defined conversion for a
2539 // user-defined conversion sequence (see 13.3.3 and
2540 // 13.3.3.1).
2541 User.After = Best->FinalConversion;
2542 return OR_Success;
2543 } else {
2544 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002545 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002546 }
2547
John McCall5c32be02010-08-24 20:38:10 +00002548 case OR_No_Viable_Function:
2549 return OR_No_Viable_Function;
2550 case OR_Deleted:
2551 // No conversion here! We're done.
2552 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002553
John McCall5c32be02010-08-24 20:38:10 +00002554 case OR_Ambiguous:
2555 return OR_Ambiguous;
2556 }
2557
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002558 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002559}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002560
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002561bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002562Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002563 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002564 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002565 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002566 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002567 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002568 if (OvResult == OR_Ambiguous)
2569 Diag(From->getSourceRange().getBegin(),
2570 diag::err_typecheck_ambiguous_condition)
2571 << From->getType() << ToType << From->getSourceRange();
2572 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2573 Diag(From->getSourceRange().getBegin(),
2574 diag::err_typecheck_nonviable_condition)
2575 << From->getType() << ToType << From->getSourceRange();
2576 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002577 return false;
John McCall5c32be02010-08-24 20:38:10 +00002578 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002579 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002580}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002581
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002582/// CompareImplicitConversionSequences - Compare two implicit
2583/// conversion sequences to determine whether one is better than the
2584/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002585static ImplicitConversionSequence::CompareKind
2586CompareImplicitConversionSequences(Sema &S,
2587 const ImplicitConversionSequence& ICS1,
2588 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002589{
2590 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2591 // conversion sequences (as defined in 13.3.3.1)
2592 // -- a standard conversion sequence (13.3.3.1.1) is a better
2593 // conversion sequence than a user-defined conversion sequence or
2594 // an ellipsis conversion sequence, and
2595 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2596 // conversion sequence than an ellipsis conversion sequence
2597 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002598 //
John McCall0d1da222010-01-12 00:44:57 +00002599 // C++0x [over.best.ics]p10:
2600 // For the purpose of ranking implicit conversion sequences as
2601 // described in 13.3.3.2, the ambiguous conversion sequence is
2602 // treated as a user-defined sequence that is indistinguishable
2603 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002604 if (ICS1.getKindRank() < ICS2.getKindRank())
2605 return ImplicitConversionSequence::Better;
2606 else if (ICS2.getKindRank() < ICS1.getKindRank())
2607 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002608
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002609 // The following checks require both conversion sequences to be of
2610 // the same kind.
2611 if (ICS1.getKind() != ICS2.getKind())
2612 return ImplicitConversionSequence::Indistinguishable;
2613
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002614 // Two implicit conversion sequences of the same form are
2615 // indistinguishable conversion sequences unless one of the
2616 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002617 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002618 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002619 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002620 // User-defined conversion sequence U1 is a better conversion
2621 // sequence than another user-defined conversion sequence U2 if
2622 // they contain the same user-defined conversion function or
2623 // constructor and if the second standard conversion sequence of
2624 // U1 is better than the second standard conversion sequence of
2625 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002626 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002627 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002628 return CompareStandardConversionSequences(S,
2629 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002630 ICS2.UserDefined.After);
2631 }
2632
2633 return ImplicitConversionSequence::Indistinguishable;
2634}
2635
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002636static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2637 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2638 Qualifiers Quals;
2639 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002640 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002641 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002642
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002643 return Context.hasSameUnqualifiedType(T1, T2);
2644}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002645
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002646// Per 13.3.3.2p3, compare the given standard conversion sequences to
2647// determine if one is a proper subset of the other.
2648static ImplicitConversionSequence::CompareKind
2649compareStandardConversionSubsets(ASTContext &Context,
2650 const StandardConversionSequence& SCS1,
2651 const StandardConversionSequence& SCS2) {
2652 ImplicitConversionSequence::CompareKind Result
2653 = ImplicitConversionSequence::Indistinguishable;
2654
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002655 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002656 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00002657 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2658 return ImplicitConversionSequence::Better;
2659 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2660 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002661
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002662 if (SCS1.Second != SCS2.Second) {
2663 if (SCS1.Second == ICK_Identity)
2664 Result = ImplicitConversionSequence::Better;
2665 else if (SCS2.Second == ICK_Identity)
2666 Result = ImplicitConversionSequence::Worse;
2667 else
2668 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002669 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002670 return ImplicitConversionSequence::Indistinguishable;
2671
2672 if (SCS1.Third == SCS2.Third) {
2673 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2674 : ImplicitConversionSequence::Indistinguishable;
2675 }
2676
2677 if (SCS1.Third == ICK_Identity)
2678 return Result == ImplicitConversionSequence::Worse
2679 ? ImplicitConversionSequence::Indistinguishable
2680 : ImplicitConversionSequence::Better;
2681
2682 if (SCS2.Third == ICK_Identity)
2683 return Result == ImplicitConversionSequence::Better
2684 ? ImplicitConversionSequence::Indistinguishable
2685 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002686
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002687 return ImplicitConversionSequence::Indistinguishable;
2688}
2689
Douglas Gregore696ebb2011-01-26 14:52:12 +00002690/// \brief Determine whether one of the given reference bindings is better
2691/// than the other based on what kind of bindings they are.
2692static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2693 const StandardConversionSequence &SCS2) {
2694 // C++0x [over.ics.rank]p3b4:
2695 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2696 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002697 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002698 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002699 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002700 // reference*.
2701 //
2702 // FIXME: Rvalue references. We're going rogue with the above edits,
2703 // because the semantics in the current C++0x working paper (N3225 at the
2704 // time of this writing) break the standard definition of std::forward
2705 // and std::reference_wrapper when dealing with references to functions.
2706 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002707 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2708 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2709 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002710
Douglas Gregore696ebb2011-01-26 14:52:12 +00002711 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2712 SCS2.IsLvalueReference) ||
2713 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2714 !SCS2.IsLvalueReference);
2715}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002716
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002717/// CompareStandardConversionSequences - Compare two standard
2718/// conversion sequences to determine whether one is better than the
2719/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002720static ImplicitConversionSequence::CompareKind
2721CompareStandardConversionSequences(Sema &S,
2722 const StandardConversionSequence& SCS1,
2723 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002724{
2725 // Standard conversion sequence S1 is a better conversion sequence
2726 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2727
2728 // -- S1 is a proper subsequence of S2 (comparing the conversion
2729 // sequences in the canonical form defined by 13.3.3.1.1,
2730 // excluding any Lvalue Transformation; the identity conversion
2731 // sequence is considered to be a subsequence of any
2732 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002733 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002734 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002735 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002736
2737 // -- the rank of S1 is better than the rank of S2 (by the rules
2738 // defined below), or, if not that,
2739 ImplicitConversionRank Rank1 = SCS1.getRank();
2740 ImplicitConversionRank Rank2 = SCS2.getRank();
2741 if (Rank1 < Rank2)
2742 return ImplicitConversionSequence::Better;
2743 else if (Rank2 < Rank1)
2744 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002745
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002746 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2747 // are indistinguishable unless one of the following rules
2748 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002749
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002750 // A conversion that is not a conversion of a pointer, or
2751 // pointer to member, to bool is better than another conversion
2752 // that is such a conversion.
2753 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2754 return SCS2.isPointerConversionToBool()
2755 ? ImplicitConversionSequence::Better
2756 : ImplicitConversionSequence::Worse;
2757
Douglas Gregor5c407d92008-10-23 00:40:37 +00002758 // C++ [over.ics.rank]p4b2:
2759 //
2760 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002761 // conversion of B* to A* is better than conversion of B* to
2762 // void*, and conversion of A* to void* is better than conversion
2763 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002764 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002765 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002766 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002767 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002768 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2769 // Exactly one of the conversion sequences is a conversion to
2770 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002771 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2772 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002773 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2774 // Neither conversion sequence converts to a void pointer; compare
2775 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002776 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002777 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002778 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002779 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2780 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002781 // Both conversion sequences are conversions to void
2782 // pointers. Compare the source types to determine if there's an
2783 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002784 QualType FromType1 = SCS1.getFromType();
2785 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002786
2787 // Adjust the types we're converting from via the array-to-pointer
2788 // conversion, if we need to.
2789 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002790 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002791 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002792 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002793
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002794 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2795 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002796
John McCall5c32be02010-08-24 20:38:10 +00002797 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002798 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002799 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002800 return ImplicitConversionSequence::Worse;
2801
2802 // Objective-C++: If one interface is more specific than the
2803 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002804 const ObjCObjectPointerType* FromObjCPtr1
2805 = FromType1->getAs<ObjCObjectPointerType>();
2806 const ObjCObjectPointerType* FromObjCPtr2
2807 = FromType2->getAs<ObjCObjectPointerType>();
2808 if (FromObjCPtr1 && FromObjCPtr2) {
2809 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2810 FromObjCPtr2);
2811 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2812 FromObjCPtr1);
2813 if (AssignLeft != AssignRight) {
2814 return AssignLeft? ImplicitConversionSequence::Better
2815 : ImplicitConversionSequence::Worse;
2816 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002817 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002818 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002819
2820 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2821 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002822 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002823 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002824 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002825
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002826 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002827 // Check for a better reference binding based on the kind of bindings.
2828 if (isBetterReferenceBindingKind(SCS1, SCS2))
2829 return ImplicitConversionSequence::Better;
2830 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2831 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002832
Sebastian Redlb28b4072009-03-22 23:49:27 +00002833 // C++ [over.ics.rank]p3b4:
2834 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2835 // which the references refer are the same type except for
2836 // top-level cv-qualifiers, and the type to which the reference
2837 // initialized by S2 refers is more cv-qualified than the type
2838 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002839 QualType T1 = SCS1.getToType(2);
2840 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002841 T1 = S.Context.getCanonicalType(T1);
2842 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002843 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002844 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2845 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002846 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00002847 // Objective-C++ ARC: If the references refer to objects with different
2848 // lifetimes, prefer bindings that don't change lifetime.
2849 if (SCS1.ObjCLifetimeConversionBinding !=
2850 SCS2.ObjCLifetimeConversionBinding) {
2851 return SCS1.ObjCLifetimeConversionBinding
2852 ? ImplicitConversionSequence::Worse
2853 : ImplicitConversionSequence::Better;
2854 }
2855
Chandler Carruth8e543b32010-12-12 08:17:55 +00002856 // If the type is an array type, promote the element qualifiers to the
2857 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002858 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002859 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002860 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002861 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002862 if (T2.isMoreQualifiedThan(T1))
2863 return ImplicitConversionSequence::Better;
2864 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00002865 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002866 }
2867 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002868
2869 return ImplicitConversionSequence::Indistinguishable;
2870}
2871
2872/// CompareQualificationConversions - Compares two standard conversion
2873/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002874/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2875ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002876CompareQualificationConversions(Sema &S,
2877 const StandardConversionSequence& SCS1,
2878 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002879 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002880 // -- S1 and S2 differ only in their qualification conversion and
2881 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2882 // cv-qualification signature of type T1 is a proper subset of
2883 // the cv-qualification signature of type T2, and S1 is not the
2884 // deprecated string literal array-to-pointer conversion (4.2).
2885 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2886 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2887 return ImplicitConversionSequence::Indistinguishable;
2888
2889 // FIXME: the example in the standard doesn't use a qualification
2890 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002891 QualType T1 = SCS1.getToType(2);
2892 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002893 T1 = S.Context.getCanonicalType(T1);
2894 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002895 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002896 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2897 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002898
2899 // If the types are the same, we won't learn anything by unwrapped
2900 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002901 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002902 return ImplicitConversionSequence::Indistinguishable;
2903
Chandler Carruth607f38e2009-12-29 07:16:59 +00002904 // If the type is an array type, promote the element qualifiers to the type
2905 // for comparison.
2906 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002907 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002908 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002909 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002910
Mike Stump11289f42009-09-09 15:08:12 +00002911 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002912 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00002913
2914 // Objective-C++ ARC:
2915 // Prefer qualification conversions not involving a change in lifetime
2916 // to qualification conversions that do not change lifetime.
2917 if (SCS1.QualificationIncludesObjCLifetime !=
2918 SCS2.QualificationIncludesObjCLifetime) {
2919 Result = SCS1.QualificationIncludesObjCLifetime
2920 ? ImplicitConversionSequence::Worse
2921 : ImplicitConversionSequence::Better;
2922 }
2923
John McCall5c32be02010-08-24 20:38:10 +00002924 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002925 // Within each iteration of the loop, we check the qualifiers to
2926 // determine if this still looks like a qualification
2927 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002928 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002929 // until there are no more pointers or pointers-to-members left
2930 // to unwrap. This essentially mimics what
2931 // IsQualificationConversion does, but here we're checking for a
2932 // strict subset of qualifiers.
2933 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2934 // The qualifiers are the same, so this doesn't tell us anything
2935 // about how the sequences rank.
2936 ;
2937 else if (T2.isMoreQualifiedThan(T1)) {
2938 // T1 has fewer qualifiers, so it could be the better sequence.
2939 if (Result == ImplicitConversionSequence::Worse)
2940 // Neither has qualifiers that are a subset of the other's
2941 // qualifiers.
2942 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002943
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002944 Result = ImplicitConversionSequence::Better;
2945 } else if (T1.isMoreQualifiedThan(T2)) {
2946 // T2 has fewer qualifiers, so it could be the better sequence.
2947 if (Result == ImplicitConversionSequence::Better)
2948 // Neither has qualifiers that are a subset of the other's
2949 // qualifiers.
2950 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002951
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002952 Result = ImplicitConversionSequence::Worse;
2953 } else {
2954 // Qualifiers are disjoint.
2955 return ImplicitConversionSequence::Indistinguishable;
2956 }
2957
2958 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002959 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002960 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002961 }
2962
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002963 // Check that the winning standard conversion sequence isn't using
2964 // the deprecated string literal array to pointer conversion.
2965 switch (Result) {
2966 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002967 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002968 Result = ImplicitConversionSequence::Indistinguishable;
2969 break;
2970
2971 case ImplicitConversionSequence::Indistinguishable:
2972 break;
2973
2974 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002975 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002976 Result = ImplicitConversionSequence::Indistinguishable;
2977 break;
2978 }
2979
2980 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002981}
2982
Douglas Gregor5c407d92008-10-23 00:40:37 +00002983/// CompareDerivedToBaseConversions - Compares two standard conversion
2984/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002985/// various kinds of derived-to-base conversions (C++
2986/// [over.ics.rank]p4b3). As part of these checks, we also look at
2987/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002988ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002989CompareDerivedToBaseConversions(Sema &S,
2990 const StandardConversionSequence& SCS1,
2991 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002992 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002993 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002994 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002995 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002996
2997 // Adjust the types we're converting from via the array-to-pointer
2998 // conversion, if we need to.
2999 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003000 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003001 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003002 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003003
3004 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003005 FromType1 = S.Context.getCanonicalType(FromType1);
3006 ToType1 = S.Context.getCanonicalType(ToType1);
3007 FromType2 = S.Context.getCanonicalType(FromType2);
3008 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003009
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003010 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003011 //
3012 // If class B is derived directly or indirectly from class A and
3013 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003014 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003015 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003016 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003017 SCS2.Second == ICK_Pointer_Conversion &&
3018 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3019 FromType1->isPointerType() && FromType2->isPointerType() &&
3020 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003021 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003022 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003023 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003024 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003025 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003026 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003027 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003028 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003029
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003030 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003031 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003032 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003033 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003034 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003035 return ImplicitConversionSequence::Worse;
3036 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003037
3038 // -- conversion of B* to A* is better than conversion of C* to A*,
3039 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003040 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003041 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003042 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003043 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003044 }
3045 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3046 SCS2.Second == ICK_Pointer_Conversion) {
3047 const ObjCObjectPointerType *FromPtr1
3048 = FromType1->getAs<ObjCObjectPointerType>();
3049 const ObjCObjectPointerType *FromPtr2
3050 = FromType2->getAs<ObjCObjectPointerType>();
3051 const ObjCObjectPointerType *ToPtr1
3052 = ToType1->getAs<ObjCObjectPointerType>();
3053 const ObjCObjectPointerType *ToPtr2
3054 = ToType2->getAs<ObjCObjectPointerType>();
3055
3056 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3057 // Apply the same conversion ranking rules for Objective-C pointer types
3058 // that we do for C++ pointers to class types. However, we employ the
3059 // Objective-C pseudo-subtyping relationship used for assignment of
3060 // Objective-C pointer types.
3061 bool FromAssignLeft
3062 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3063 bool FromAssignRight
3064 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3065 bool ToAssignLeft
3066 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3067 bool ToAssignRight
3068 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3069
3070 // A conversion to an a non-id object pointer type or qualified 'id'
3071 // type is better than a conversion to 'id'.
3072 if (ToPtr1->isObjCIdType() &&
3073 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3074 return ImplicitConversionSequence::Worse;
3075 if (ToPtr2->isObjCIdType() &&
3076 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3077 return ImplicitConversionSequence::Better;
3078
3079 // A conversion to a non-id object pointer type is better than a
3080 // conversion to a qualified 'id' type
3081 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3082 return ImplicitConversionSequence::Worse;
3083 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3084 return ImplicitConversionSequence::Better;
3085
3086 // A conversion to an a non-Class object pointer type or qualified 'Class'
3087 // type is better than a conversion to 'Class'.
3088 if (ToPtr1->isObjCClassType() &&
3089 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3090 return ImplicitConversionSequence::Worse;
3091 if (ToPtr2->isObjCClassType() &&
3092 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3093 return ImplicitConversionSequence::Better;
3094
3095 // A conversion to a non-Class object pointer type is better than a
3096 // conversion to a qualified 'Class' type.
3097 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3098 return ImplicitConversionSequence::Worse;
3099 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3100 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003101
Douglas Gregor058d3de2011-01-31 18:51:41 +00003102 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3103 if (S.Context.hasSameType(FromType1, FromType2) &&
3104 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3105 (ToAssignLeft != ToAssignRight))
3106 return ToAssignLeft? ImplicitConversionSequence::Worse
3107 : ImplicitConversionSequence::Better;
3108
3109 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3110 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3111 (FromAssignLeft != FromAssignRight))
3112 return FromAssignLeft? ImplicitConversionSequence::Better
3113 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003114 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003115 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003116
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003117 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003118 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3119 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3120 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003121 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003122 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003123 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003124 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003125 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003126 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003127 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003128 ToType2->getAs<MemberPointerType>();
3129 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3130 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3131 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3132 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3133 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3134 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3135 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3136 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003137 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003138 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003139 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003140 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003141 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003142 return ImplicitConversionSequence::Better;
3143 }
3144 // conversion of B::* to C::* is better than conversion of A::* to C::*
3145 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003146 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003147 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003148 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003149 return ImplicitConversionSequence::Worse;
3150 }
3151 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003152
Douglas Gregor5ab11652010-04-17 22:01:05 +00003153 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003154 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003155 // -- binding of an expression of type C to a reference of type
3156 // B& is better than binding an expression of type C to a
3157 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003158 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3159 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3160 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003161 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003162 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003163 return ImplicitConversionSequence::Worse;
3164 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003165
Douglas Gregor2fe98832008-11-03 19:09:14 +00003166 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003167 // -- binding of an expression of type B to a reference of type
3168 // A& is better than binding an expression of type C to a
3169 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003170 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3171 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3172 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003173 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003174 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003175 return ImplicitConversionSequence::Worse;
3176 }
3177 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003178
Douglas Gregor5c407d92008-10-23 00:40:37 +00003179 return ImplicitConversionSequence::Indistinguishable;
3180}
3181
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003182/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3183/// determine whether they are reference-related,
3184/// reference-compatible, reference-compatible with added
3185/// qualification, or incompatible, for use in C++ initialization by
3186/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3187/// type, and the first type (T1) is the pointee type of the reference
3188/// type being initialized.
3189Sema::ReferenceCompareResult
3190Sema::CompareReferenceRelationship(SourceLocation Loc,
3191 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003192 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003193 bool &ObjCConversion,
3194 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003195 assert(!OrigT1->isReferenceType() &&
3196 "T1 must be the pointee type of the reference type");
3197 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3198
3199 QualType T1 = Context.getCanonicalType(OrigT1);
3200 QualType T2 = Context.getCanonicalType(OrigT2);
3201 Qualifiers T1Quals, T2Quals;
3202 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3203 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3204
3205 // C++ [dcl.init.ref]p4:
3206 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3207 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3208 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003209 DerivedToBase = false;
3210 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003211 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003212 if (UnqualT1 == UnqualT2) {
3213 // Nothing to do.
3214 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003215 IsDerivedFrom(UnqualT2, UnqualT1))
3216 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003217 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3218 UnqualT2->isObjCObjectOrInterfaceType() &&
3219 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3220 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003221 else
3222 return Ref_Incompatible;
3223
3224 // At this point, we know that T1 and T2 are reference-related (at
3225 // least).
3226
3227 // If the type is an array type, promote the element qualifiers to the type
3228 // for comparison.
3229 if (isa<ArrayType>(T1) && T1Quals)
3230 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3231 if (isa<ArrayType>(T2) && T2Quals)
3232 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3233
3234 // C++ [dcl.init.ref]p4:
3235 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3236 // reference-related to T2 and cv1 is the same cv-qualification
3237 // as, or greater cv-qualification than, cv2. For purposes of
3238 // overload resolution, cases for which cv1 is greater
3239 // cv-qualification than cv2 are identified as
3240 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003241 //
3242 // Note that we also require equivalence of Objective-C GC and address-space
3243 // qualifiers when performing these computations, so that e.g., an int in
3244 // address space 1 is not reference-compatible with an int in address
3245 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003246 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3247 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3248 T1Quals.removeObjCLifetime();
3249 T2Quals.removeObjCLifetime();
3250 ObjCLifetimeConversion = true;
3251 }
3252
Douglas Gregord517d552011-04-28 17:56:11 +00003253 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003254 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003255 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003256 return Ref_Compatible_With_Added_Qualification;
3257 else
3258 return Ref_Related;
3259}
3260
Douglas Gregor836a7e82010-08-11 02:15:33 +00003261/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003262/// with DeclType. Return true if something definite is found.
3263static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003264FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3265 QualType DeclType, SourceLocation DeclLoc,
3266 Expr *Init, QualType T2, bool AllowRvalues,
3267 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003268 assert(T2->isRecordType() && "Can only find conversions of record types.");
3269 CXXRecordDecl *T2RecordDecl
3270 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3271
3272 OverloadCandidateSet CandidateSet(DeclLoc);
3273 const UnresolvedSetImpl *Conversions
3274 = T2RecordDecl->getVisibleConversionFunctions();
3275 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3276 E = Conversions->end(); I != E; ++I) {
3277 NamedDecl *D = *I;
3278 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3279 if (isa<UsingShadowDecl>(D))
3280 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3281
3282 FunctionTemplateDecl *ConvTemplate
3283 = dyn_cast<FunctionTemplateDecl>(D);
3284 CXXConversionDecl *Conv;
3285 if (ConvTemplate)
3286 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3287 else
3288 Conv = cast<CXXConversionDecl>(D);
3289
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003290 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003291 // explicit conversions, skip it.
3292 if (!AllowExplicit && Conv->isExplicit())
3293 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003294
Douglas Gregor836a7e82010-08-11 02:15:33 +00003295 if (AllowRvalues) {
3296 bool DerivedToBase = false;
3297 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003298 bool ObjCLifetimeConversion = false;
Douglas Gregor836a7e82010-08-11 02:15:33 +00003299 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003300 S.CompareReferenceRelationship(
3301 DeclLoc,
3302 Conv->getConversionType().getNonReferenceType()
3303 .getUnqualifiedType(),
3304 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003305 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003306 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003307 continue;
3308 } else {
3309 // If the conversion function doesn't return a reference type,
3310 // it can't be considered for this conversion. An rvalue reference
3311 // is only acceptable if its referencee is a function type.
3312
3313 const ReferenceType *RefType =
3314 Conv->getConversionType()->getAs<ReferenceType>();
3315 if (!RefType ||
3316 (!RefType->isLValueReferenceType() &&
3317 !RefType->getPointeeType()->isFunctionType()))
3318 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003319 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003320
Douglas Gregor836a7e82010-08-11 02:15:33 +00003321 if (ConvTemplate)
3322 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003323 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003324 else
3325 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003326 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003327 }
3328
3329 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003330 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003331 case OR_Success:
3332 // C++ [over.ics.ref]p1:
3333 //
3334 // [...] If the parameter binds directly to the result of
3335 // applying a conversion function to the argument
3336 // expression, the implicit conversion sequence is a
3337 // user-defined conversion sequence (13.3.3.1.2), with the
3338 // second standard conversion sequence either an identity
3339 // conversion or, if the conversion function returns an
3340 // entity of a type that is a derived class of the parameter
3341 // type, a derived-to-base Conversion.
3342 if (!Best->FinalConversion.DirectBinding)
3343 return false;
3344
Chandler Carruth30141632011-02-25 19:41:05 +00003345 if (Best->Function)
3346 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003347 ICS.setUserDefined();
3348 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3349 ICS.UserDefined.After = Best->FinalConversion;
3350 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00003351 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redld92badf2010-06-30 18:13:39 +00003352 ICS.UserDefined.EllipsisConversion = false;
3353 assert(ICS.UserDefined.After.ReferenceBinding &&
3354 ICS.UserDefined.After.DirectBinding &&
3355 "Expected a direct reference binding!");
3356 return true;
3357
3358 case OR_Ambiguous:
3359 ICS.setAmbiguous();
3360 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3361 Cand != CandidateSet.end(); ++Cand)
3362 if (Cand->Viable)
3363 ICS.Ambiguous.addConversion(Cand->Function);
3364 return true;
3365
3366 case OR_No_Viable_Function:
3367 case OR_Deleted:
3368 // There was no suitable conversion, or we found a deleted
3369 // conversion; continue with other checks.
3370 return false;
3371 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003372
Eric Christopheraba9fb22010-06-30 18:36:32 +00003373 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003374}
3375
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003376/// \brief Compute an implicit conversion sequence for reference
3377/// initialization.
3378static ImplicitConversionSequence
3379TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3380 SourceLocation DeclLoc,
3381 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003382 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003383 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3384
3385 // Most paths end in a failed conversion.
3386 ImplicitConversionSequence ICS;
3387 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3388
3389 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3390 QualType T2 = Init->getType();
3391
3392 // If the initializer is the address of an overloaded function, try
3393 // to resolve the overloaded function. If all goes well, T2 is the
3394 // type of the resulting function.
3395 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3396 DeclAccessPair Found;
3397 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3398 false, Found))
3399 T2 = Fn->getType();
3400 }
3401
3402 // Compute some basic properties of the types and the initializer.
3403 bool isRValRef = DeclType->isRValueReferenceType();
3404 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003405 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003406 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003407 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003408 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003409 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003410 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003411
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003412
Sebastian Redld92badf2010-06-30 18:13:39 +00003413 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003414 // A reference to type "cv1 T1" is initialized by an expression
3415 // of type "cv2 T2" as follows:
3416
Sebastian Redld92badf2010-06-30 18:13:39 +00003417 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003418 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003419 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3420 // reference-compatible with "cv2 T2," or
3421 //
3422 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3423 if (InitCategory.isLValue() &&
3424 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003425 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003426 // When a parameter of reference type binds directly (8.5.3)
3427 // to an argument expression, the implicit conversion sequence
3428 // is the identity conversion, unless the argument expression
3429 // has a type that is a derived class of the parameter type,
3430 // in which case the implicit conversion sequence is a
3431 // derived-to-base Conversion (13.3.3.1).
3432 ICS.setStandard();
3433 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003434 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3435 : ObjCConversion? ICK_Compatible_Conversion
3436 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003437 ICS.Standard.Third = ICK_Identity;
3438 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3439 ICS.Standard.setToType(0, T2);
3440 ICS.Standard.setToType(1, T1);
3441 ICS.Standard.setToType(2, T1);
3442 ICS.Standard.ReferenceBinding = true;
3443 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003444 ICS.Standard.IsLvalueReference = !isRValRef;
3445 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3446 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003447 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003448 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003449 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003450
Sebastian Redld92badf2010-06-30 18:13:39 +00003451 // Nothing more to do: the inaccessibility/ambiguity check for
3452 // derived-to-base conversions is suppressed when we're
3453 // computing the implicit conversion sequence (C++
3454 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003455 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003456 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003457
Sebastian Redld92badf2010-06-30 18:13:39 +00003458 // -- has a class type (i.e., T2 is a class type), where T1 is
3459 // not reference-related to T2, and can be implicitly
3460 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3461 // is reference-compatible with "cv3 T3" 92) (this
3462 // conversion is selected by enumerating the applicable
3463 // conversion functions (13.3.1.6) and choosing the best
3464 // one through overload resolution (13.3)),
3465 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003466 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003467 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003468 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3469 Init, T2, /*AllowRvalues=*/false,
3470 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003471 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003472 }
3473 }
3474
Sebastian Redld92badf2010-06-30 18:13:39 +00003475 // -- Otherwise, the reference shall be an lvalue reference to a
3476 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003477 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003478 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003479 // We actually handle one oddity of C++ [over.ics.ref] at this
3480 // point, which is that, due to p2 (which short-circuits reference
3481 // binding by only attempting a simple conversion for non-direct
3482 // bindings) and p3's strange wording, we allow a const volatile
3483 // reference to bind to an rvalue. Hence the check for the presence
3484 // of "const" rather than checking for "const" being the only
3485 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003486 // This is also the point where rvalue references and lvalue inits no longer
3487 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003488 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003489 return ICS;
3490
Douglas Gregorf143cd52011-01-24 16:14:37 +00003491 // -- If the initializer expression
3492 //
3493 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003494 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003495 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3496 (InitCategory.isXValue() ||
3497 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3498 (InitCategory.isLValue() && T2->isFunctionType()))) {
3499 ICS.setStandard();
3500 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003501 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003502 : ObjCConversion? ICK_Compatible_Conversion
3503 : ICK_Identity;
3504 ICS.Standard.Third = ICK_Identity;
3505 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3506 ICS.Standard.setToType(0, T2);
3507 ICS.Standard.setToType(1, T1);
3508 ICS.Standard.setToType(2, T1);
3509 ICS.Standard.ReferenceBinding = true;
3510 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3511 // binding unless we're binding to a class prvalue.
3512 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3513 // allow the use of rvalue references in C++98/03 for the benefit of
3514 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003515 ICS.Standard.DirectBinding =
3516 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003517 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003518 ICS.Standard.IsLvalueReference = !isRValRef;
3519 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003520 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003521 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003522 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003523 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003524 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003525 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003526
Douglas Gregorf143cd52011-01-24 16:14:37 +00003527 // -- has a class type (i.e., T2 is a class type), where T1 is not
3528 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003529 // an xvalue, class prvalue, or function lvalue of type
3530 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003531 // "cv3 T3",
3532 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003533 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003534 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003535 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003536 // class subobject).
3537 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003538 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003539 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3540 Init, T2, /*AllowRvalues=*/true,
3541 AllowExplicit)) {
3542 // In the second case, if the reference is an rvalue reference
3543 // and the second standard conversion sequence of the
3544 // user-defined conversion sequence includes an lvalue-to-rvalue
3545 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003546 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003547 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3548 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3549
Douglas Gregor95273c32011-01-21 16:36:05 +00003550 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003551 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003552
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003553 // -- Otherwise, a temporary of type "cv1 T1" is created and
3554 // initialized from the initializer expression using the
3555 // rules for a non-reference copy initialization (8.5). The
3556 // reference is then bound to the temporary. If T1 is
3557 // reference-related to T2, cv1 must be the same
3558 // cv-qualification as, or greater cv-qualification than,
3559 // cv2; otherwise, the program is ill-formed.
3560 if (RefRelationship == Sema::Ref_Related) {
3561 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3562 // we would be reference-compatible or reference-compatible with
3563 // added qualification. But that wasn't the case, so the reference
3564 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00003565 //
3566 // Note that we only want to check address spaces and cvr-qualifiers here.
3567 // ObjC GC and lifetime qualifiers aren't important.
3568 Qualifiers T1Quals = T1.getQualifiers();
3569 Qualifiers T2Quals = T2.getQualifiers();
3570 T1Quals.removeObjCGCAttr();
3571 T1Quals.removeObjCLifetime();
3572 T2Quals.removeObjCGCAttr();
3573 T2Quals.removeObjCLifetime();
3574 if (!T1Quals.compatiblyIncludes(T2Quals))
3575 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003576 }
3577
3578 // If at least one of the types is a class type, the types are not
3579 // related, and we aren't allowed any user conversions, the
3580 // reference binding fails. This case is important for breaking
3581 // recursion, since TryImplicitConversion below will attempt to
3582 // create a temporary through the use of a copy constructor.
3583 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3584 (T1->isRecordType() || T2->isRecordType()))
3585 return ICS;
3586
Douglas Gregorcba72b12011-01-21 05:18:22 +00003587 // If T1 is reference-related to T2 and the reference is an rvalue
3588 // reference, the initializer expression shall not be an lvalue.
3589 if (RefRelationship >= Sema::Ref_Related &&
3590 isRValRef && Init->Classify(S.Context).isLValue())
3591 return ICS;
3592
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003593 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003594 // When a parameter of reference type is not bound directly to
3595 // an argument expression, the conversion sequence is the one
3596 // required to convert the argument expression to the
3597 // underlying type of the reference according to
3598 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3599 // to copy-initializing a temporary of the underlying type with
3600 // the argument expression. Any difference in top-level
3601 // cv-qualification is subsumed by the initialization itself
3602 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003603 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3604 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003605 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003606 /*CStyle=*/false,
3607 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003608
3609 // Of course, that's still a reference binding.
3610 if (ICS.isStandard()) {
3611 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003612 ICS.Standard.IsLvalueReference = !isRValRef;
3613 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3614 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003615 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003616 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003617 } else if (ICS.isUserDefined()) {
3618 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00003619 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3620 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3621 ICS.UserDefined.After.BindsToRvalue = true;
3622 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3623 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003624 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003625
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003626 return ICS;
3627}
3628
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003629/// TryCopyInitialization - Try to copy-initialize a value of type
3630/// ToType from the expression From. Return the implicit conversion
3631/// sequence required to pass this argument, which may be a bad
3632/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003633/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003634/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003635static ImplicitConversionSequence
3636TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003637 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00003638 bool InOverloadResolution,
3639 bool AllowObjCWritebackConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003640 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003641 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003642 /*FIXME:*/From->getLocStart(),
3643 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003644 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003645
John McCall5c32be02010-08-24 20:38:10 +00003646 return TryImplicitConversion(S, From, ToType,
3647 SuppressUserConversions,
3648 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003649 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00003650 /*CStyle=*/false,
3651 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003652}
3653
Anna Zaks1b068122011-07-28 19:46:48 +00003654static bool TryCopyInitialization(const CanQualType FromQTy,
3655 const CanQualType ToQTy,
3656 Sema &S,
3657 SourceLocation Loc,
3658 ExprValueKind FromVK) {
3659 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
3660 ImplicitConversionSequence ICS =
3661 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
3662
3663 return !ICS.isBad();
3664}
3665
Douglas Gregor436424c2008-11-18 23:14:02 +00003666/// TryObjectArgumentInitialization - Try to initialize the object
3667/// parameter of the given member function (@c Method) from the
3668/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003669static ImplicitConversionSequence
3670TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003671 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003672 CXXMethodDecl *Method,
3673 CXXRecordDecl *ActingContext) {
3674 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003675 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3676 // const volatile object.
3677 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3678 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003679 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003680
3681 // Set up the conversion sequence as a "bad" conversion, to allow us
3682 // to exit early.
3683 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003684
3685 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003686 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003687 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003688 FromType = PT->getPointeeType();
3689
Douglas Gregor02824322011-01-26 19:30:28 +00003690 // When we had a pointer, it's implicitly dereferenced, so we
3691 // better have an lvalue.
3692 assert(FromClassification.isLValue());
3693 }
3694
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003695 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003696
Douglas Gregor02824322011-01-26 19:30:28 +00003697 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003698 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003699 // parameter is
3700 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003701 // - "lvalue reference to cv X" for functions declared without a
3702 // ref-qualifier or with the & ref-qualifier
3703 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003704 // ref-qualifier
3705 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003706 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003707 // cv-qualification on the member function declaration.
3708 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003709 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003710 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003711 // (C++ [over.match.funcs]p5). We perform a simplified version of
3712 // reference binding here, that allows class rvalues to bind to
3713 // non-constant references.
3714
Douglas Gregor02824322011-01-26 19:30:28 +00003715 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003716 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003717 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003718 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003719 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003720 ICS.setBad(BadConversionSequence::bad_qualifiers,
3721 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003722 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003723 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003724
3725 // Check that we have either the same type or a derived type. It
3726 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003727 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003728 ImplicitConversionKind SecondKind;
3729 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3730 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003731 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003732 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003733 else {
John McCall65eb8792010-02-25 01:37:24 +00003734 ICS.setBad(BadConversionSequence::unrelated_class,
3735 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003736 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003737 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003738
Douglas Gregor02824322011-01-26 19:30:28 +00003739 // Check the ref-qualifier.
3740 switch (Method->getRefQualifier()) {
3741 case RQ_None:
3742 // Do nothing; we don't care about lvalueness or rvalueness.
3743 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003744
Douglas Gregor02824322011-01-26 19:30:28 +00003745 case RQ_LValue:
3746 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3747 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003748 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003749 ImplicitParamType);
3750 return ICS;
3751 }
3752 break;
3753
3754 case RQ_RValue:
3755 if (!FromClassification.isRValue()) {
3756 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003757 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003758 ImplicitParamType);
3759 return ICS;
3760 }
3761 break;
3762 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003763
Douglas Gregor436424c2008-11-18 23:14:02 +00003764 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003765 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003766 ICS.Standard.setAsIdentityConversion();
3767 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003768 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003769 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003770 ICS.Standard.ReferenceBinding = true;
3771 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003772 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003773 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003774 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3775 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3776 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003777 return ICS;
3778}
3779
3780/// PerformObjectArgumentInitialization - Perform initialization of
3781/// the implicit object parameter for the given Method with the given
3782/// expression.
John Wiegley01296292011-04-08 18:41:53 +00003783ExprResult
3784Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003785 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003786 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003787 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003788 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003789 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003790 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003791
Douglas Gregor02824322011-01-26 19:30:28 +00003792 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003793 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003794 FromRecordType = PT->getPointeeType();
3795 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003796 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003797 } else {
3798 FromRecordType = From->getType();
3799 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003800 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003801 }
3802
John McCall6e9f8f62009-12-03 04:06:58 +00003803 // Note that we always use the true parent context when performing
3804 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003805 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003806 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3807 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003808 if (ICS.isBad()) {
3809 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3810 Qualifiers FromQs = FromRecordType.getQualifiers();
3811 Qualifiers ToQs = DestType.getQualifiers();
3812 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3813 if (CVR) {
3814 Diag(From->getSourceRange().getBegin(),
3815 diag::err_member_function_call_bad_cvr)
3816 << Method->getDeclName() << FromRecordType << (CVR - 1)
3817 << From->getSourceRange();
3818 Diag(Method->getLocation(), diag::note_previous_decl)
3819 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00003820 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003821 }
3822 }
3823
Douglas Gregor436424c2008-11-18 23:14:02 +00003824 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003825 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003826 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003827 }
Mike Stump11289f42009-09-09 15:08:12 +00003828
John Wiegley01296292011-04-08 18:41:53 +00003829 if (ICS.Standard.Second == ICK_Derived_To_Base) {
3830 ExprResult FromRes =
3831 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3832 if (FromRes.isInvalid())
3833 return ExprError();
3834 From = FromRes.take();
3835 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003836
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003837 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00003838 From = ImpCastExprToType(From, DestType, CK_NoOp,
3839 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3840 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00003841}
3842
Douglas Gregor5fb53972009-01-14 15:45:31 +00003843/// TryContextuallyConvertToBool - Attempt to contextually convert the
3844/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003845static ImplicitConversionSequence
3846TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003847 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003848 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003849 // FIXME: Are these flags correct?
3850 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003851 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003852 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003853 /*CStyle=*/false,
3854 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003855}
3856
3857/// PerformContextuallyConvertToBool - Perform a contextual conversion
3858/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00003859ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00003860 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003861 if (!ICS.isBad())
3862 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003863
Fariborz Jahanian76197412009-11-18 18:26:29 +00003864 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00003865 return Diag(From->getSourceRange().getBegin(),
3866 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003867 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003868 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00003869}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003870
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003871/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3872/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003873static ImplicitConversionSequence
3874TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3875 QualType Ty = S.Context.getObjCIdType();
3876 return TryImplicitConversion(S, From, Ty,
3877 // FIXME: Are these flags correct?
3878 /*SuppressUserConversions=*/false,
3879 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003880 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003881 /*CStyle=*/false,
3882 /*AllowObjCWritebackConversion=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003883}
John McCall5c32be02010-08-24 20:38:10 +00003884
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003885/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3886/// of the expression From to 'id'.
John Wiegley01296292011-04-08 18:41:53 +00003887ExprResult Sema::PerformContextuallyConvertToObjCId(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003888 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003889 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003890 if (!ICS.isBad())
3891 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00003892 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003893}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003894
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003895/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003896/// enumeration type.
3897///
3898/// This routine will attempt to convert an expression of class type to an
3899/// integral or enumeration type, if that class type only has a single
3900/// conversion to an integral or enumeration type.
3901///
Douglas Gregor4799d032010-06-30 00:20:43 +00003902/// \param Loc The source location of the construct that requires the
3903/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003904///
Douglas Gregor4799d032010-06-30 00:20:43 +00003905/// \param FromE The expression we're converting from.
3906///
3907/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3908/// have integral or enumeration type.
3909///
3910/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3911/// incomplete class type.
3912///
3913/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3914/// explicit conversion function (because no implicit conversion functions
3915/// were available). This is a recovery mode.
3916///
3917/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3918/// showing which conversion was picked.
3919///
3920/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3921/// conversion function that could convert to integral or enumeration type.
3922///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003923/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00003924/// usable conversion function.
3925///
3926/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3927/// function, which may be an extension in this case.
3928///
3929/// \returns The expression, converted to an integral or enumeration type if
3930/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003931ExprResult
John McCallb268a282010-08-23 23:25:46 +00003932Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003933 const PartialDiagnostic &NotIntDiag,
3934 const PartialDiagnostic &IncompleteDiag,
3935 const PartialDiagnostic &ExplicitConvDiag,
3936 const PartialDiagnostic &ExplicitConvNote,
3937 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003938 const PartialDiagnostic &AmbigNote,
3939 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003940 // We can't perform any more checking for type-dependent expressions.
3941 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003942 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003943
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003944 // If the expression already has integral or enumeration type, we're golden.
3945 QualType T = From->getType();
3946 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003947 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003948
3949 // FIXME: Check for missing '()' if T is a function type?
3950
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003951 // 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 +00003952 // expression of integral or enumeration type.
3953 const RecordType *RecordTy = T->getAs<RecordType>();
3954 if (!RecordTy || !getLangOptions().CPlusPlus) {
3955 Diag(Loc, NotIntDiag)
3956 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003957 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003958 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003959
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003960 // We must have a complete class type.
3961 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003962 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003963
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003964 // Look for a conversion to an integral or enumeration type.
3965 UnresolvedSet<4> ViableConversions;
3966 UnresolvedSet<4> ExplicitConversions;
3967 const UnresolvedSetImpl *Conversions
3968 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003969
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003970 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003971 E = Conversions->end();
3972 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003973 ++I) {
3974 if (CXXConversionDecl *Conversion
3975 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3976 if (Conversion->getConversionType().getNonReferenceType()
3977 ->isIntegralOrEnumerationType()) {
3978 if (Conversion->isExplicit())
3979 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3980 else
3981 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3982 }
3983 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003984
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003985 switch (ViableConversions.size()) {
3986 case 0:
3987 if (ExplicitConversions.size() == 1) {
3988 DeclAccessPair Found = ExplicitConversions[0];
3989 CXXConversionDecl *Conversion
3990 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003991
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003992 // The user probably meant to invoke the given explicit
3993 // conversion; use it.
3994 QualType ConvTy
3995 = Conversion->getConversionType().getNonReferenceType();
3996 std::string TypeStr;
3997 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003998
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003999 Diag(Loc, ExplicitConvDiag)
4000 << T << ConvTy
4001 << FixItHint::CreateInsertion(From->getLocStart(),
4002 "static_cast<" + TypeStr + ">(")
4003 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4004 ")");
4005 Diag(Conversion->getLocation(), ExplicitConvNote)
4006 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004007
4008 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004009 // explicit conversion function.
4010 if (isSFINAEContext())
4011 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004012
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004013 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00004014 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
4015 if (Result.isInvalid())
4016 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004017
Douglas Gregor668443e2011-01-20 00:18:04 +00004018 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004019 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004020
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004021 // We'll complain below about a non-integral condition type.
4022 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004023
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004024 case 1: {
4025 // Apply this conversion.
4026 DeclAccessPair Found = ViableConversions[0];
4027 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004028
Douglas Gregor4799d032010-06-30 00:20:43 +00004029 CXXConversionDecl *Conversion
4030 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4031 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004032 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004033 if (ConvDiag.getDiagID()) {
4034 if (isSFINAEContext())
4035 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004036
Douglas Gregor4799d032010-06-30 00:20:43 +00004037 Diag(Loc, ConvDiag)
4038 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4039 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004040
Douglas Gregor668443e2011-01-20 00:18:04 +00004041 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004042 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00004043 if (Result.isInvalid())
4044 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004045
Douglas Gregor668443e2011-01-20 00:18:04 +00004046 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004047 break;
4048 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004049
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004050 default:
4051 Diag(Loc, AmbigDiag)
4052 << T << From->getSourceRange();
4053 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4054 CXXConversionDecl *Conv
4055 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4056 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4057 Diag(Conv->getLocation(), AmbigNote)
4058 << ConvTy->isEnumeralType() << ConvTy;
4059 }
John McCallb268a282010-08-23 23:25:46 +00004060 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004061 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004062
Douglas Gregor5823da32010-06-29 23:25:20 +00004063 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004064 Diag(Loc, NotIntDiag)
4065 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004066
John McCallb268a282010-08-23 23:25:46 +00004067 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004068}
4069
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004070/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004071/// candidate functions, using the given function call arguments. If
4072/// @p SuppressUserConversions, then don't allow user-defined
4073/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004074///
4075/// \para PartialOverloading true if we are performing "partial" overloading
4076/// based on an incomplete set of function arguments. This feature is used by
4077/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004078void
4079Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004080 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004081 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004082 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004083 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004084 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004085 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004086 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004087 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004088 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004089 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004090
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004091 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004092 if (!isa<CXXConstructorDecl>(Method)) {
4093 // If we get here, it's because we're calling a member function
4094 // that is named without a member access expression (e.g.,
4095 // "this->f") that was either written explicitly or created
4096 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004097 // function, e.g., X::f(). We use an empty type for the implied
4098 // object argument (C++ [over.call.func]p3), and the acting context
4099 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004100 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004101 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004102 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004103 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004104 return;
4105 }
4106 // We treat a constructor like a non-member function, since its object
4107 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004108 }
4109
Douglas Gregorff7028a2009-11-13 23:59:09 +00004110 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004111 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004112
Douglas Gregor27381f32009-11-23 12:27:39 +00004113 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004114 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004115
Douglas Gregorffe14e32009-11-14 01:20:54 +00004116 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4117 // C++ [class.copy]p3:
4118 // A member function template is never instantiated to perform the copy
4119 // of a class object to an object of its class type.
4120 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004121 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004122 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004123 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4124 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004125 return;
4126 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004127
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004128 // Add this candidate
4129 CandidateSet.push_back(OverloadCandidate());
4130 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004131 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004132 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004133 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004134 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004135 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004136 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004137
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004138 unsigned NumArgsInProto = Proto->getNumArgs();
4139
4140 // (C++ 13.3.2p2): A candidate function having fewer than m
4141 // parameters is viable only if it has an ellipsis in its parameter
4142 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004143 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004144 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004145 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004146 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004147 return;
4148 }
4149
4150 // (C++ 13.3.2p2): A candidate function having more than m parameters
4151 // is viable only if the (m+1)st parameter has a default argument
4152 // (8.3.6). For the purposes of overload resolution, the
4153 // parameter list is truncated on the right, so that there are
4154 // exactly m parameters.
4155 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004156 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004157 // Not enough arguments.
4158 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004159 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004160 return;
4161 }
4162
4163 // Determine the implicit conversion sequences for each of the
4164 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004165 Candidate.Conversions.resize(NumArgs);
4166 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4167 if (ArgIdx < NumArgsInProto) {
4168 // (C++ 13.3.2p3): for F to be a viable function, there shall
4169 // exist for each argument an implicit conversion sequence
4170 // (13.3.3.1) that converts that argument to the corresponding
4171 // parameter of F.
4172 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004173 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004174 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004175 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004176 /*InOverloadResolution=*/true,
4177 /*AllowObjCWritebackConversion=*/
4178 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004179 if (Candidate.Conversions[ArgIdx].isBad()) {
4180 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004181 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004182 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004183 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004184 } else {
4185 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4186 // argument for which there is no corresponding parameter is
4187 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004188 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004189 }
4190 }
4191}
4192
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004193/// \brief Add all of the function declarations in the given function set to
4194/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004195void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004196 Expr **Args, unsigned NumArgs,
4197 OverloadCandidateSet& CandidateSet,
4198 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004199 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004200 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4201 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004202 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004203 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004204 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004205 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004206 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004207 CandidateSet, SuppressUserConversions);
4208 else
John McCalla0296f72010-03-19 07:35:19 +00004209 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004210 SuppressUserConversions);
4211 } else {
John McCalla0296f72010-03-19 07:35:19 +00004212 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004213 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4214 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004215 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004216 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004217 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004218 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004219 Args[0]->Classify(Context),
4220 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004221 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004222 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004223 else
John McCalla0296f72010-03-19 07:35:19 +00004224 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004225 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004226 Args, NumArgs, CandidateSet,
4227 SuppressUserConversions);
4228 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004229 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004230}
4231
John McCallf0f1cf02009-11-17 07:50:12 +00004232/// AddMethodCandidate - Adds a named decl (which is some kind of
4233/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004234void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004235 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004236 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004237 Expr **Args, unsigned NumArgs,
4238 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004239 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004240 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004241 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004242
4243 if (isa<UsingShadowDecl>(Decl))
4244 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004245
John McCallf0f1cf02009-11-17 07:50:12 +00004246 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4247 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4248 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004249 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4250 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004251 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004252 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004253 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004254 } else {
John McCalla0296f72010-03-19 07:35:19 +00004255 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004256 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004257 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004258 }
4259}
4260
Douglas Gregor436424c2008-11-18 23:14:02 +00004261/// AddMethodCandidate - Adds the given C++ member function to the set
4262/// of candidate functions, using the given function call arguments
4263/// and the object argument (@c Object). For example, in a call
4264/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4265/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4266/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004267/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004268void
John McCalla0296f72010-03-19 07:35:19 +00004269Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004270 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004271 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004272 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004273 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004274 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004275 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004276 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004277 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004278 assert(!isa<CXXConstructorDecl>(Method) &&
4279 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004280
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004281 if (!CandidateSet.isNewCandidate(Method))
4282 return;
4283
Douglas Gregor27381f32009-11-23 12:27:39 +00004284 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004285 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004286
Douglas Gregor436424c2008-11-18 23:14:02 +00004287 // Add this candidate
4288 CandidateSet.push_back(OverloadCandidate());
4289 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004290 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004291 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004292 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004293 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004294 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004295
4296 unsigned NumArgsInProto = Proto->getNumArgs();
4297
4298 // (C++ 13.3.2p2): A candidate function having fewer than m
4299 // parameters is viable only if it has an ellipsis in its parameter
4300 // list (8.3.5).
4301 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4302 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004303 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004304 return;
4305 }
4306
4307 // (C++ 13.3.2p2): A candidate function having more than m parameters
4308 // is viable only if the (m+1)st parameter has a default argument
4309 // (8.3.6). For the purposes of overload resolution, the
4310 // parameter list is truncated on the right, so that there are
4311 // exactly m parameters.
4312 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4313 if (NumArgs < MinRequiredArgs) {
4314 // Not enough arguments.
4315 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004316 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004317 return;
4318 }
4319
4320 Candidate.Viable = true;
4321 Candidate.Conversions.resize(NumArgs + 1);
4322
John McCall6e9f8f62009-12-03 04:06:58 +00004323 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004324 // The implicit object argument is ignored.
4325 Candidate.IgnoreObjectArgument = true;
4326 else {
4327 // Determine the implicit conversion sequence for the object
4328 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004329 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004330 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4331 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004332 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004333 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004334 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004335 return;
4336 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004337 }
4338
4339 // Determine the implicit conversion sequences for each of the
4340 // arguments.
4341 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4342 if (ArgIdx < NumArgsInProto) {
4343 // (C++ 13.3.2p3): for F to be a viable function, there shall
4344 // exist for each argument an implicit conversion sequence
4345 // (13.3.3.1) that converts that argument to the corresponding
4346 // parameter of F.
4347 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004348 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004349 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004350 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004351 /*InOverloadResolution=*/true,
4352 /*AllowObjCWritebackConversion=*/
4353 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004354 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004355 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004356 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004357 break;
4358 }
4359 } else {
4360 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4361 // argument for which there is no corresponding parameter is
4362 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004363 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004364 }
4365 }
4366}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004367
Douglas Gregor97628d62009-08-21 00:16:32 +00004368/// \brief Add a C++ member function template as a candidate to the candidate
4369/// set, using template argument deduction to produce an appropriate member
4370/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004371void
Douglas Gregor97628d62009-08-21 00:16:32 +00004372Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004373 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004374 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004375 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004376 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004377 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004378 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004379 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004380 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004381 if (!CandidateSet.isNewCandidate(MethodTmpl))
4382 return;
4383
Douglas Gregor97628d62009-08-21 00:16:32 +00004384 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004385 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004386 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004387 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004388 // candidate functions in the usual way.113) A given name can refer to one
4389 // or more function templates and also to a set of overloaded non-template
4390 // functions. In such a case, the candidate functions generated from each
4391 // function template are combined with the set of non-template candidate
4392 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004393 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004394 FunctionDecl *Specialization = 0;
4395 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004396 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004397 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004398 CandidateSet.push_back(OverloadCandidate());
4399 OverloadCandidate &Candidate = CandidateSet.back();
4400 Candidate.FoundDecl = FoundDecl;
4401 Candidate.Function = MethodTmpl->getTemplatedDecl();
4402 Candidate.Viable = false;
4403 Candidate.FailureKind = ovl_fail_bad_deduction;
4404 Candidate.IsSurrogate = false;
4405 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004406 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004407 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004408 Info);
4409 return;
4410 }
Mike Stump11289f42009-09-09 15:08:12 +00004411
Douglas Gregor97628d62009-08-21 00:16:32 +00004412 // Add the function template specialization produced by template argument
4413 // deduction as a candidate.
4414 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004415 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004416 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004417 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004418 ActingContext, ObjectType, ObjectClassification,
4419 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004420}
4421
Douglas Gregor05155d82009-08-21 23:19:43 +00004422/// \brief Add a C++ function template specialization as a candidate
4423/// in the candidate set, using template argument deduction to produce
4424/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004425void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004426Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004427 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004428 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004429 Expr **Args, unsigned NumArgs,
4430 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004431 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004432 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4433 return;
4434
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004435 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004436 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004437 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004438 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004439 // candidate functions in the usual way.113) A given name can refer to one
4440 // or more function templates and also to a set of overloaded non-template
4441 // functions. In such a case, the candidate functions generated from each
4442 // function template are combined with the set of non-template candidate
4443 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004444 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004445 FunctionDecl *Specialization = 0;
4446 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004447 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004448 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004449 CandidateSet.push_back(OverloadCandidate());
4450 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004451 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004452 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4453 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004454 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004455 Candidate.IsSurrogate = false;
4456 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004457 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004458 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004459 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004460 return;
4461 }
Mike Stump11289f42009-09-09 15:08:12 +00004462
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004463 // Add the function template specialization produced by template argument
4464 // deduction as a candidate.
4465 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004466 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004467 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004468}
Mike Stump11289f42009-09-09 15:08:12 +00004469
Douglas Gregora1f013e2008-11-07 22:36:19 +00004470/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004471/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004472/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004473/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004474/// (which may or may not be the same type as the type that the
4475/// conversion function produces).
4476void
4477Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004478 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004479 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004480 Expr *From, QualType ToType,
4481 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004482 assert(!Conversion->getDescribedFunctionTemplate() &&
4483 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004484 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004485 if (!CandidateSet.isNewCandidate(Conversion))
4486 return;
4487
Douglas Gregor27381f32009-11-23 12:27:39 +00004488 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004489 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004490
Douglas Gregora1f013e2008-11-07 22:36:19 +00004491 // Add this candidate
4492 CandidateSet.push_back(OverloadCandidate());
4493 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004494 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004495 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004496 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004497 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004498 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004499 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004500 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004501 Candidate.Viable = true;
4502 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004503 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004504
Douglas Gregor6affc782010-08-19 15:37:02 +00004505 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004506 // For conversion functions, the function is considered to be a member of
4507 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004508 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004509 //
4510 // Determine the implicit conversion sequence for the implicit
4511 // object parameter.
4512 QualType ImplicitParamType = From->getType();
4513 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4514 ImplicitParamType = FromPtrType->getPointeeType();
4515 CXXRecordDecl *ConversionContext
4516 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004517
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004518 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004519 = TryObjectArgumentInitialization(*this, From->getType(),
4520 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004521 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004522
John McCall0d1da222010-01-12 00:44:57 +00004523 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004524 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004525 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004526 return;
4527 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004528
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004529 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004530 // derived to base as such conversions are given Conversion Rank. They only
4531 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4532 QualType FromCanon
4533 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4534 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4535 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4536 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004537 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004538 return;
4539 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004540
Douglas Gregora1f013e2008-11-07 22:36:19 +00004541 // To determine what the conversion from the result of calling the
4542 // conversion function to the type we're eventually trying to
4543 // convert to (ToType), we need to synthesize a call to the
4544 // conversion function and attempt copy initialization from it. This
4545 // makes sure that we get the right semantics with respect to
4546 // lvalues/rvalues and the type. Fortunately, we can allocate this
4547 // call on the stack and we don't need its arguments to be
4548 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004549 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004550 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004551 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4552 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004553 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004554 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004555
Richard Smith48d24642011-07-13 22:53:21 +00004556 QualType ConversionType = Conversion->getConversionType();
4557 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004558 Candidate.Viable = false;
4559 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4560 return;
4561 }
4562
Richard Smith48d24642011-07-13 22:53:21 +00004563 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00004564
Mike Stump11289f42009-09-09 15:08:12 +00004565 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004566 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4567 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00004568 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004569 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004570 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004571 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004572 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004573 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00004574 /*InOverloadResolution=*/false,
4575 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004576
John McCall0d1da222010-01-12 00:44:57 +00004577 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004578 case ImplicitConversionSequence::StandardConversion:
4579 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004580
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004581 // C++ [over.ics.user]p3:
4582 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004583 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004584 // shall have exact match rank.
4585 if (Conversion->getPrimaryTemplate() &&
4586 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4587 Candidate.Viable = false;
4588 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004590
Douglas Gregorcba72b12011-01-21 05:18:22 +00004591 // C++0x [dcl.init.ref]p5:
4592 // In the second case, if the reference is an rvalue reference and
4593 // the second standard conversion sequence of the user-defined
4594 // conversion sequence includes an lvalue-to-rvalue conversion, the
4595 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004596 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004597 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4598 Candidate.Viable = false;
4599 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4600 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004601 break;
4602
4603 case ImplicitConversionSequence::BadConversion:
4604 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004605 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004606 break;
4607
4608 default:
Mike Stump11289f42009-09-09 15:08:12 +00004609 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004610 "Can only end up with a standard conversion sequence or failure");
4611 }
4612}
4613
Douglas Gregor05155d82009-08-21 23:19:43 +00004614/// \brief Adds a conversion function template specialization
4615/// candidate to the overload set, using template argument deduction
4616/// to deduce the template arguments of the conversion function
4617/// template from the type that we are converting to (C++
4618/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004619void
Douglas Gregor05155d82009-08-21 23:19:43 +00004620Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004621 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004622 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004623 Expr *From, QualType ToType,
4624 OverloadCandidateSet &CandidateSet) {
4625 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4626 "Only conversion function templates permitted here");
4627
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004628 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4629 return;
4630
John McCallbc077cf2010-02-08 23:07:23 +00004631 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004632 CXXConversionDecl *Specialization = 0;
4633 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004634 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004635 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004636 CandidateSet.push_back(OverloadCandidate());
4637 OverloadCandidate &Candidate = CandidateSet.back();
4638 Candidate.FoundDecl = FoundDecl;
4639 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4640 Candidate.Viable = false;
4641 Candidate.FailureKind = ovl_fail_bad_deduction;
4642 Candidate.IsSurrogate = false;
4643 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004644 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004645 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004646 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004647 return;
4648 }
Mike Stump11289f42009-09-09 15:08:12 +00004649
Douglas Gregor05155d82009-08-21 23:19:43 +00004650 // Add the conversion function template specialization produced by
4651 // template argument deduction as a candidate.
4652 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004653 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004654 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004655}
4656
Douglas Gregorab7897a2008-11-19 22:57:39 +00004657/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4658/// converts the given @c Object to a function pointer via the
4659/// conversion function @c Conversion, and then attempts to call it
4660/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4661/// the type of function that we'll eventually be calling.
4662void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004663 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004664 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004665 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004666 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004667 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004668 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004669 if (!CandidateSet.isNewCandidate(Conversion))
4670 return;
4671
Douglas Gregor27381f32009-11-23 12:27:39 +00004672 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004673 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004674
Douglas Gregorab7897a2008-11-19 22:57:39 +00004675 CandidateSet.push_back(OverloadCandidate());
4676 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004677 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004678 Candidate.Function = 0;
4679 Candidate.Surrogate = Conversion;
4680 Candidate.Viable = true;
4681 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004682 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004683 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004684 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004685
4686 // Determine the implicit conversion sequence for the implicit
4687 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004688 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004689 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004690 Object->Classify(Context),
4691 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004692 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004693 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004694 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004695 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004696 return;
4697 }
4698
4699 // The first conversion is actually a user-defined conversion whose
4700 // first conversion is ObjectInit's standard conversion (which is
4701 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004702 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004703 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004704 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004705 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004706 Candidate.Conversions[0].UserDefined.FoundConversionFunction
Douglas Gregor2bbfba02011-01-20 01:32:05 +00004707 = FoundDecl.getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004708 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004709 = Candidate.Conversions[0].UserDefined.Before;
4710 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4711
Mike Stump11289f42009-09-09 15:08:12 +00004712 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004713 unsigned NumArgsInProto = Proto->getNumArgs();
4714
4715 // (C++ 13.3.2p2): A candidate function having fewer than m
4716 // parameters is viable only if it has an ellipsis in its parameter
4717 // list (8.3.5).
4718 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4719 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004720 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004721 return;
4722 }
4723
4724 // Function types don't have any default arguments, so just check if
4725 // we have enough arguments.
4726 if (NumArgs < NumArgsInProto) {
4727 // Not enough arguments.
4728 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004729 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004730 return;
4731 }
4732
4733 // Determine the implicit conversion sequences for each of the
4734 // arguments.
4735 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4736 if (ArgIdx < NumArgsInProto) {
4737 // (C++ 13.3.2p3): for F to be a viable function, there shall
4738 // exist for each argument an implicit conversion sequence
4739 // (13.3.3.1) that converts that argument to the corresponding
4740 // parameter of F.
4741 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004742 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004743 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004744 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00004745 /*InOverloadResolution=*/false,
4746 /*AllowObjCWritebackConversion=*/
4747 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004748 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004749 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004750 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004751 break;
4752 }
4753 } else {
4754 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4755 // argument for which there is no corresponding parameter is
4756 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004757 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004758 }
4759 }
4760}
4761
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004762/// \brief Add overload candidates for overloaded operators that are
4763/// member functions.
4764///
4765/// Add the overloaded operator candidates that are member functions
4766/// for the operator Op that was used in an operator expression such
4767/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4768/// CandidateSet will store the added overload candidates. (C++
4769/// [over.match.oper]).
4770void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4771 SourceLocation OpLoc,
4772 Expr **Args, unsigned NumArgs,
4773 OverloadCandidateSet& CandidateSet,
4774 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004775 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4776
4777 // C++ [over.match.oper]p3:
4778 // For a unary operator @ with an operand of a type whose
4779 // cv-unqualified version is T1, and for a binary operator @ with
4780 // a left operand of a type whose cv-unqualified version is T1 and
4781 // a right operand of a type whose cv-unqualified version is T2,
4782 // three sets of candidate functions, designated member
4783 // candidates, non-member candidates and built-in candidates, are
4784 // constructed as follows:
4785 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004786
4787 // -- If T1 is a class type, the set of member candidates is the
4788 // result of the qualified lookup of T1::operator@
4789 // (13.3.1.1.1); otherwise, the set of member candidates is
4790 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004791 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004792 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004793 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004794 return;
Mike Stump11289f42009-09-09 15:08:12 +00004795
John McCall27b18f82009-11-17 02:14:36 +00004796 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4797 LookupQualifiedName(Operators, T1Rec->getDecl());
4798 Operators.suppressDiagnostics();
4799
Mike Stump11289f42009-09-09 15:08:12 +00004800 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004801 OperEnd = Operators.end();
4802 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004803 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004804 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004805 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00004806 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004807 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004808 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004809}
4810
Douglas Gregora11693b2008-11-12 17:17:38 +00004811/// AddBuiltinCandidate - Add a candidate for a built-in
4812/// operator. ResultTy and ParamTys are the result and parameter types
4813/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004814/// arguments being passed to the candidate. IsAssignmentOperator
4815/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004816/// operator. NumContextualBoolArguments is the number of arguments
4817/// (at the beginning of the argument list) that will be contextually
4818/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004819void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004820 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004821 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004822 bool IsAssignmentOperator,
4823 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004824 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004825 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004826
Douglas Gregora11693b2008-11-12 17:17:38 +00004827 // Add this candidate
4828 CandidateSet.push_back(OverloadCandidate());
4829 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004830 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004831 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004832 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004833 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004834 Candidate.BuiltinTypes.ResultTy = ResultTy;
4835 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4836 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4837
4838 // Determine the implicit conversion sequences for each of the
4839 // arguments.
4840 Candidate.Viable = true;
4841 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004842 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004843 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004844 // C++ [over.match.oper]p4:
4845 // For the built-in assignment operators, conversions of the
4846 // left operand are restricted as follows:
4847 // -- no temporaries are introduced to hold the left operand, and
4848 // -- no user-defined conversions are applied to the left
4849 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004850 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004851 //
4852 // We block these conversions by turning off user-defined
4853 // conversions, since that is the only way that initialization of
4854 // a reference to a non-class type can occur from something that
4855 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004856 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004857 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004858 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004859 Candidate.Conversions[ArgIdx]
4860 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004861 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004862 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004863 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004864 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00004865 /*InOverloadResolution=*/false,
4866 /*AllowObjCWritebackConversion=*/
4867 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004868 }
John McCall0d1da222010-01-12 00:44:57 +00004869 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004870 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004871 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004872 break;
4873 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004874 }
4875}
4876
4877/// BuiltinCandidateTypeSet - A set of types that will be used for the
4878/// candidate operator functions for built-in operators (C++
4879/// [over.built]). The types are separated into pointer types and
4880/// enumeration types.
4881class BuiltinCandidateTypeSet {
4882 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004883 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004884
4885 /// PointerTypes - The set of pointer types that will be used in the
4886 /// built-in candidates.
4887 TypeSet PointerTypes;
4888
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004889 /// MemberPointerTypes - The set of member pointer types that will be
4890 /// used in the built-in candidates.
4891 TypeSet MemberPointerTypes;
4892
Douglas Gregora11693b2008-11-12 17:17:38 +00004893 /// EnumerationTypes - The set of enumeration types that will be
4894 /// used in the built-in candidates.
4895 TypeSet EnumerationTypes;
4896
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004897 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004898 /// candidates.
4899 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004900
4901 /// \brief A flag indicating non-record types are viable candidates
4902 bool HasNonRecordTypes;
4903
4904 /// \brief A flag indicating whether either arithmetic or enumeration types
4905 /// were present in the candidate set.
4906 bool HasArithmeticOrEnumeralTypes;
4907
Douglas Gregor80af3132011-05-21 23:15:46 +00004908 /// \brief A flag indicating whether the nullptr type was present in the
4909 /// candidate set.
4910 bool HasNullPtrType;
4911
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004912 /// Sema - The semantic analysis instance where we are building the
4913 /// candidate type set.
4914 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004915
Douglas Gregora11693b2008-11-12 17:17:38 +00004916 /// Context - The AST context in which we will build the type sets.
4917 ASTContext &Context;
4918
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004919 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4920 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004921 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004922
4923public:
4924 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004925 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004926
Mike Stump11289f42009-09-09 15:08:12 +00004927 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004928 : HasNonRecordTypes(false),
4929 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00004930 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00004931 SemaRef(SemaRef),
4932 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004933
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004934 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004935 SourceLocation Loc,
4936 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004937 bool AllowExplicitConversions,
4938 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004939
4940 /// pointer_begin - First pointer type found;
4941 iterator pointer_begin() { return PointerTypes.begin(); }
4942
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004943 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004944 iterator pointer_end() { return PointerTypes.end(); }
4945
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004946 /// member_pointer_begin - First member pointer type found;
4947 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4948
4949 /// member_pointer_end - Past the last member pointer type found;
4950 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4951
Douglas Gregora11693b2008-11-12 17:17:38 +00004952 /// enumeration_begin - First enumeration type found;
4953 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4954
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004955 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004956 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004957
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004958 iterator vector_begin() { return VectorTypes.begin(); }
4959 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00004960
4961 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4962 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00004963 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00004964};
4965
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004966/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004967/// the set of pointer types along with any more-qualified variants of
4968/// that type. For example, if @p Ty is "int const *", this routine
4969/// will add "int const *", "int const volatile *", "int const
4970/// restrict *", and "int const volatile restrict *" to the set of
4971/// pointer types. Returns true if the add of @p Ty itself succeeded,
4972/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004973///
4974/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004975bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004976BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4977 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004978
Douglas Gregora11693b2008-11-12 17:17:38 +00004979 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004980 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004981 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004982
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004983 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004984 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004985 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004986 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004987 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004988 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004989 buildObjCPtr = true;
4990 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004991 else
4992 assert(false && "type was not a pointer type!");
4993 }
4994 else
4995 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004996
Sebastian Redl4990a632009-11-18 20:39:26 +00004997 // Don't add qualified variants of arrays. For one, they're not allowed
4998 // (the qualifier would sink to the element type), and for another, the
4999 // only overload situation where it matters is subscript or pointer +- int,
5000 // and those shouldn't have qualifier variants anyway.
5001 if (PointeeTy->isArrayType())
5002 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005003 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005004 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005005 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005006 bool hasVolatile = VisibleQuals.hasVolatile();
5007 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005008
John McCall8ccfcb52009-09-24 19:53:00 +00005009 // Iterate through all strict supersets of BaseCVR.
5010 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5011 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005012 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5013 // in the types.
5014 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5015 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005016 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005017 if (!buildObjCPtr)
5018 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5019 else
5020 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005021 }
5022
5023 return true;
5024}
5025
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005026/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5027/// to the set of pointer types along with any more-qualified variants of
5028/// that type. For example, if @p Ty is "int const *", this routine
5029/// will add "int const *", "int const volatile *", "int const
5030/// restrict *", and "int const volatile restrict *" to the set of
5031/// pointer types. Returns true if the add of @p Ty itself succeeded,
5032/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005033///
5034/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005035bool
5036BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5037 QualType Ty) {
5038 // Insert this type.
5039 if (!MemberPointerTypes.insert(Ty))
5040 return false;
5041
John McCall8ccfcb52009-09-24 19:53:00 +00005042 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5043 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005044
John McCall8ccfcb52009-09-24 19:53:00 +00005045 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005046 // Don't add qualified variants of arrays. For one, they're not allowed
5047 // (the qualifier would sink to the element type), and for another, the
5048 // only overload situation where it matters is subscript or pointer +- int,
5049 // and those shouldn't have qualifier variants anyway.
5050 if (PointeeTy->isArrayType())
5051 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005052 const Type *ClassTy = PointerTy->getClass();
5053
5054 // Iterate through all strict supersets of the pointee type's CVR
5055 // qualifiers.
5056 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5057 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5058 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005059
John McCall8ccfcb52009-09-24 19:53:00 +00005060 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005061 MemberPointerTypes.insert(
5062 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005063 }
5064
5065 return true;
5066}
5067
Douglas Gregora11693b2008-11-12 17:17:38 +00005068/// AddTypesConvertedFrom - Add each of the types to which the type @p
5069/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005070/// primarily interested in pointer types and enumeration types. We also
5071/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005072/// AllowUserConversions is true if we should look at the conversion
5073/// functions of a class type, and AllowExplicitConversions if we
5074/// should also include the explicit conversion functions of a class
5075/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005076void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005077BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005078 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005079 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005080 bool AllowExplicitConversions,
5081 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005082 // Only deal with canonical types.
5083 Ty = Context.getCanonicalType(Ty);
5084
5085 // Look through reference types; they aren't part of the type of an
5086 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005087 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005088 Ty = RefTy->getPointeeType();
5089
John McCall33ddac02011-01-19 10:06:00 +00005090 // If we're dealing with an array type, decay to the pointer.
5091 if (Ty->isArrayType())
5092 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5093
5094 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005095 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005096
Chandler Carruth00a38332010-12-13 01:44:01 +00005097 // Flag if we ever add a non-record type.
5098 const RecordType *TyRec = Ty->getAs<RecordType>();
5099 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5100
Chandler Carruth00a38332010-12-13 01:44:01 +00005101 // Flag if we encounter an arithmetic type.
5102 HasArithmeticOrEnumeralTypes =
5103 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5104
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005105 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5106 PointerTypes.insert(Ty);
5107 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005108 // Insert our type, and its more-qualified variants, into the set
5109 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005110 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005111 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005112 } else if (Ty->isMemberPointerType()) {
5113 // Member pointers are far easier, since the pointee can't be converted.
5114 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5115 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005116 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005117 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005118 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005119 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005120 // We treat vector types as arithmetic types in many contexts as an
5121 // extension.
5122 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005123 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005124 } else if (Ty->isNullPtrType()) {
5125 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005126 } else if (AllowUserConversions && TyRec) {
5127 // No conversion functions in incomplete types.
5128 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5129 return;
Mike Stump11289f42009-09-09 15:08:12 +00005130
Chandler Carruth00a38332010-12-13 01:44:01 +00005131 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5132 const UnresolvedSetImpl *Conversions
5133 = ClassDecl->getVisibleConversionFunctions();
5134 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5135 E = Conversions->end(); I != E; ++I) {
5136 NamedDecl *D = I.getDecl();
5137 if (isa<UsingShadowDecl>(D))
5138 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005139
Chandler Carruth00a38332010-12-13 01:44:01 +00005140 // Skip conversion function templates; they don't tell us anything
5141 // about which builtin types we can convert to.
5142 if (isa<FunctionTemplateDecl>(D))
5143 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005144
Chandler Carruth00a38332010-12-13 01:44:01 +00005145 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5146 if (AllowExplicitConversions || !Conv->isExplicit()) {
5147 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5148 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005149 }
5150 }
5151 }
5152}
5153
Douglas Gregor84605ae2009-08-24 13:43:27 +00005154/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5155/// the volatile- and non-volatile-qualified assignment operators for the
5156/// given type to the candidate set.
5157static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5158 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005159 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005160 unsigned NumArgs,
5161 OverloadCandidateSet &CandidateSet) {
5162 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005163
Douglas Gregor84605ae2009-08-24 13:43:27 +00005164 // T& operator=(T&, T)
5165 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5166 ParamTypes[1] = T;
5167 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5168 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005169
Douglas Gregor84605ae2009-08-24 13:43:27 +00005170 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5171 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005172 ParamTypes[0]
5173 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005174 ParamTypes[1] = T;
5175 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005176 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005177 }
5178}
Mike Stump11289f42009-09-09 15:08:12 +00005179
Sebastian Redl1054fae2009-10-25 17:03:50 +00005180/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5181/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005182static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5183 Qualifiers VRQuals;
5184 const RecordType *TyRec;
5185 if (const MemberPointerType *RHSMPType =
5186 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005187 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005188 else
5189 TyRec = ArgExpr->getType()->getAs<RecordType>();
5190 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005191 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005192 VRQuals.addVolatile();
5193 VRQuals.addRestrict();
5194 return VRQuals;
5195 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005196
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005197 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005198 if (!ClassDecl->hasDefinition())
5199 return VRQuals;
5200
John McCallad371252010-01-20 00:46:10 +00005201 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005202 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005203
John McCallad371252010-01-20 00:46:10 +00005204 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005205 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005206 NamedDecl *D = I.getDecl();
5207 if (isa<UsingShadowDecl>(D))
5208 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5209 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005210 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5211 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5212 CanTy = ResTypeRef->getPointeeType();
5213 // Need to go down the pointer/mempointer chain and add qualifiers
5214 // as see them.
5215 bool done = false;
5216 while (!done) {
5217 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5218 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005219 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005220 CanTy->getAs<MemberPointerType>())
5221 CanTy = ResTypeMPtr->getPointeeType();
5222 else
5223 done = true;
5224 if (CanTy.isVolatileQualified())
5225 VRQuals.addVolatile();
5226 if (CanTy.isRestrictQualified())
5227 VRQuals.addRestrict();
5228 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5229 return VRQuals;
5230 }
5231 }
5232 }
5233 return VRQuals;
5234}
John McCall52872982010-11-13 05:51:15 +00005235
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005236namespace {
John McCall52872982010-11-13 05:51:15 +00005237
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005238/// \brief Helper class to manage the addition of builtin operator overload
5239/// candidates. It provides shared state and utility methods used throughout
5240/// the process, as well as a helper method to add each group of builtin
5241/// operator overloads from the standard to a candidate set.
5242class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005243 // Common instance state available to all overload candidate addition methods.
5244 Sema &S;
5245 Expr **Args;
5246 unsigned NumArgs;
5247 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005248 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005249 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005250 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005251
Chandler Carruthc6586e52010-12-12 10:35:00 +00005252 // Define some constants used to index and iterate over the arithemetic types
5253 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005254 // The "promoted arithmetic types" are the arithmetic
5255 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005256 static const unsigned FirstIntegralType = 3;
5257 static const unsigned LastIntegralType = 18;
5258 static const unsigned FirstPromotedIntegralType = 3,
5259 LastPromotedIntegralType = 9;
5260 static const unsigned FirstPromotedArithmeticType = 0,
5261 LastPromotedArithmeticType = 9;
5262 static const unsigned NumArithmeticTypes = 18;
5263
Chandler Carruthc6586e52010-12-12 10:35:00 +00005264 /// \brief Get the canonical type for a given arithmetic type index.
5265 CanQualType getArithmeticType(unsigned index) {
5266 assert(index < NumArithmeticTypes);
5267 static CanQualType ASTContext::* const
5268 ArithmeticTypes[NumArithmeticTypes] = {
5269 // Start of promoted types.
5270 &ASTContext::FloatTy,
5271 &ASTContext::DoubleTy,
5272 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005273
Chandler Carruthc6586e52010-12-12 10:35:00 +00005274 // Start of integral types.
5275 &ASTContext::IntTy,
5276 &ASTContext::LongTy,
5277 &ASTContext::LongLongTy,
5278 &ASTContext::UnsignedIntTy,
5279 &ASTContext::UnsignedLongTy,
5280 &ASTContext::UnsignedLongLongTy,
5281 // End of promoted types.
5282
5283 &ASTContext::BoolTy,
5284 &ASTContext::CharTy,
5285 &ASTContext::WCharTy,
5286 &ASTContext::Char16Ty,
5287 &ASTContext::Char32Ty,
5288 &ASTContext::SignedCharTy,
5289 &ASTContext::ShortTy,
5290 &ASTContext::UnsignedCharTy,
5291 &ASTContext::UnsignedShortTy,
5292 // End of integral types.
5293 // FIXME: What about complex?
5294 };
5295 return S.Context.*ArithmeticTypes[index];
5296 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005297
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005298 /// \brief Gets the canonical type resulting from the usual arithemetic
5299 /// converions for the given arithmetic types.
5300 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5301 // Accelerator table for performing the usual arithmetic conversions.
5302 // The rules are basically:
5303 // - if either is floating-point, use the wider floating-point
5304 // - if same signedness, use the higher rank
5305 // - if same size, use unsigned of the higher rank
5306 // - use the larger type
5307 // These rules, together with the axiom that higher ranks are
5308 // never smaller, are sufficient to precompute all of these results
5309 // *except* when dealing with signed types of higher rank.
5310 // (we could precompute SLL x UI for all known platforms, but it's
5311 // better not to make any assumptions).
5312 enum PromotedType {
5313 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5314 };
5315 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5316 [LastPromotedArithmeticType] = {
5317 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5318 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5319 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5320 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5321 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5322 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5323 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5324 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5325 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5326 };
5327
5328 assert(L < LastPromotedArithmeticType);
5329 assert(R < LastPromotedArithmeticType);
5330 int Idx = ConversionsTable[L][R];
5331
5332 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005333 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005334
5335 // Slow path: we need to compare widths.
5336 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005337 CanQualType LT = getArithmeticType(L),
5338 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005339 unsigned LW = S.Context.getIntWidth(LT),
5340 RW = S.Context.getIntWidth(RT);
5341
5342 // If they're different widths, use the signed type.
5343 if (LW > RW) return LT;
5344 else if (LW < RW) return RT;
5345
5346 // Otherwise, use the unsigned type of the signed type's rank.
5347 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5348 assert(L == SLL || R == SLL);
5349 return S.Context.UnsignedLongLongTy;
5350 }
5351
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005352 /// \brief Helper method to factor out the common pattern of adding overloads
5353 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005354 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5355 bool HasVolatile) {
5356 QualType ParamTypes[2] = {
5357 S.Context.getLValueReferenceType(CandidateTy),
5358 S.Context.IntTy
5359 };
5360
5361 // Non-volatile version.
5362 if (NumArgs == 1)
5363 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5364 else
5365 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5366
5367 // Use a heuristic to reduce number of builtin candidates in the set:
5368 // add volatile version only if there are conversions to a volatile type.
5369 if (HasVolatile) {
5370 ParamTypes[0] =
5371 S.Context.getLValueReferenceType(
5372 S.Context.getVolatileType(CandidateTy));
5373 if (NumArgs == 1)
5374 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5375 else
5376 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5377 }
5378 }
5379
5380public:
5381 BuiltinOperatorOverloadBuilder(
5382 Sema &S, Expr **Args, unsigned NumArgs,
5383 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005384 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005385 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005386 OverloadCandidateSet &CandidateSet)
5387 : S(S), Args(Args), NumArgs(NumArgs),
5388 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005389 HasArithmeticOrEnumeralCandidateType(
5390 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005391 CandidateTypes(CandidateTypes),
5392 CandidateSet(CandidateSet) {
5393 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005394 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005395 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005396 assert(getArithmeticType(LastPromotedIntegralType - 1)
5397 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005398 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005399 assert(getArithmeticType(FirstPromotedArithmeticType)
5400 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005401 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005402 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5403 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005404 "Invalid last promoted arithmetic type");
5405 }
5406
5407 // C++ [over.built]p3:
5408 //
5409 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5410 // is either volatile or empty, there exist candidate operator
5411 // functions of the form
5412 //
5413 // VQ T& operator++(VQ T&);
5414 // T operator++(VQ T&, int);
5415 //
5416 // C++ [over.built]p4:
5417 //
5418 // For every pair (T, VQ), where T is an arithmetic type other
5419 // than bool, and VQ is either volatile or empty, there exist
5420 // candidate operator functions of the form
5421 //
5422 // VQ T& operator--(VQ T&);
5423 // T operator--(VQ T&, int);
5424 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005425 if (!HasArithmeticOrEnumeralCandidateType)
5426 return;
5427
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005428 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5429 Arith < NumArithmeticTypes; ++Arith) {
5430 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005431 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005432 VisibleTypeConversionsQuals.hasVolatile());
5433 }
5434 }
5435
5436 // C++ [over.built]p5:
5437 //
5438 // For every pair (T, VQ), where T is a cv-qualified or
5439 // cv-unqualified object type, and VQ is either volatile or
5440 // empty, there exist candidate operator functions of the form
5441 //
5442 // T*VQ& operator++(T*VQ&);
5443 // T*VQ& operator--(T*VQ&);
5444 // T* operator++(T*VQ&, int);
5445 // T* operator--(T*VQ&, int);
5446 void addPlusPlusMinusMinusPointerOverloads() {
5447 for (BuiltinCandidateTypeSet::iterator
5448 Ptr = CandidateTypes[0].pointer_begin(),
5449 PtrEnd = CandidateTypes[0].pointer_end();
5450 Ptr != PtrEnd; ++Ptr) {
5451 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005452 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005453 continue;
5454
5455 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5456 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5457 VisibleTypeConversionsQuals.hasVolatile()));
5458 }
5459 }
5460
5461 // C++ [over.built]p6:
5462 // For every cv-qualified or cv-unqualified object type T, there
5463 // exist candidate operator functions of the form
5464 //
5465 // T& operator*(T*);
5466 //
5467 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005468 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005469 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005470 // T& operator*(T*);
5471 void addUnaryStarPointerOverloads() {
5472 for (BuiltinCandidateTypeSet::iterator
5473 Ptr = CandidateTypes[0].pointer_begin(),
5474 PtrEnd = CandidateTypes[0].pointer_end();
5475 Ptr != PtrEnd; ++Ptr) {
5476 QualType ParamTy = *Ptr;
5477 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005478 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5479 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005480
Douglas Gregor02824322011-01-26 19:30:28 +00005481 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5482 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5483 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005484
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005485 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5486 &ParamTy, Args, 1, CandidateSet);
5487 }
5488 }
5489
5490 // C++ [over.built]p9:
5491 // For every promoted arithmetic type T, there exist candidate
5492 // operator functions of the form
5493 //
5494 // T operator+(T);
5495 // T operator-(T);
5496 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005497 if (!HasArithmeticOrEnumeralCandidateType)
5498 return;
5499
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005500 for (unsigned Arith = FirstPromotedArithmeticType;
5501 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005502 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005503 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5504 }
5505
5506 // Extension: We also add these operators for vector types.
5507 for (BuiltinCandidateTypeSet::iterator
5508 Vec = CandidateTypes[0].vector_begin(),
5509 VecEnd = CandidateTypes[0].vector_end();
5510 Vec != VecEnd; ++Vec) {
5511 QualType VecTy = *Vec;
5512 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5513 }
5514 }
5515
5516 // C++ [over.built]p8:
5517 // For every type T, there exist candidate operator functions of
5518 // the form
5519 //
5520 // T* operator+(T*);
5521 void addUnaryPlusPointerOverloads() {
5522 for (BuiltinCandidateTypeSet::iterator
5523 Ptr = CandidateTypes[0].pointer_begin(),
5524 PtrEnd = CandidateTypes[0].pointer_end();
5525 Ptr != PtrEnd; ++Ptr) {
5526 QualType ParamTy = *Ptr;
5527 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5528 }
5529 }
5530
5531 // C++ [over.built]p10:
5532 // For every promoted integral type T, there exist candidate
5533 // operator functions of the form
5534 //
5535 // T operator~(T);
5536 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005537 if (!HasArithmeticOrEnumeralCandidateType)
5538 return;
5539
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005540 for (unsigned Int = FirstPromotedIntegralType;
5541 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005542 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005543 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5544 }
5545
5546 // Extension: We also add this operator for vector types.
5547 for (BuiltinCandidateTypeSet::iterator
5548 Vec = CandidateTypes[0].vector_begin(),
5549 VecEnd = CandidateTypes[0].vector_end();
5550 Vec != VecEnd; ++Vec) {
5551 QualType VecTy = *Vec;
5552 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5553 }
5554 }
5555
5556 // C++ [over.match.oper]p16:
5557 // For every pointer to member type T, there exist candidate operator
5558 // functions of the form
5559 //
5560 // bool operator==(T,T);
5561 // bool operator!=(T,T);
5562 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5563 /// Set of (canonical) types that we've already handled.
5564 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5565
5566 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5567 for (BuiltinCandidateTypeSet::iterator
5568 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5569 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5570 MemPtr != MemPtrEnd;
5571 ++MemPtr) {
5572 // Don't add the same builtin candidate twice.
5573 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5574 continue;
5575
5576 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5577 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5578 CandidateSet);
5579 }
5580 }
5581 }
5582
5583 // C++ [over.built]p15:
5584 //
Douglas Gregor80af3132011-05-21 23:15:46 +00005585 // For every T, where T is an enumeration type, a pointer type, or
5586 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005587 //
5588 // bool operator<(T, T);
5589 // bool operator>(T, T);
5590 // bool operator<=(T, T);
5591 // bool operator>=(T, T);
5592 // bool operator==(T, T);
5593 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005594 void addRelationalPointerOrEnumeralOverloads() {
5595 // C++ [over.built]p1:
5596 // If there is a user-written candidate with the same name and parameter
5597 // types as a built-in candidate operator function, the built-in operator
5598 // function is hidden and is not included in the set of candidate
5599 // functions.
5600 //
5601 // The text is actually in a note, but if we don't implement it then we end
5602 // up with ambiguities when the user provides an overloaded operator for
5603 // an enumeration type. Note that only enumeration types have this problem,
5604 // so we track which enumeration types we've seen operators for. Also, the
5605 // only other overloaded operator with enumeration argumenst, operator=,
5606 // cannot be overloaded for enumeration types, so this is the only place
5607 // where we must suppress candidates like this.
5608 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5609 UserDefinedBinaryOperators;
5610
5611 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5612 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5613 CandidateTypes[ArgIdx].enumeration_end()) {
5614 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5615 CEnd = CandidateSet.end();
5616 C != CEnd; ++C) {
5617 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5618 continue;
5619
5620 QualType FirstParamType =
5621 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5622 QualType SecondParamType =
5623 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5624
5625 // Skip if either parameter isn't of enumeral type.
5626 if (!FirstParamType->isEnumeralType() ||
5627 !SecondParamType->isEnumeralType())
5628 continue;
5629
5630 // Add this operator to the set of known user-defined operators.
5631 UserDefinedBinaryOperators.insert(
5632 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5633 S.Context.getCanonicalType(SecondParamType)));
5634 }
5635 }
5636 }
5637
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005638 /// Set of (canonical) types that we've already handled.
5639 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5640
5641 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5642 for (BuiltinCandidateTypeSet::iterator
5643 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5644 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5645 Ptr != PtrEnd; ++Ptr) {
5646 // Don't add the same builtin candidate twice.
5647 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5648 continue;
5649
5650 QualType ParamTypes[2] = { *Ptr, *Ptr };
5651 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5652 CandidateSet);
5653 }
5654 for (BuiltinCandidateTypeSet::iterator
5655 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5656 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5657 Enum != EnumEnd; ++Enum) {
5658 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5659
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005660 // Don't add the same builtin candidate twice, or if a user defined
5661 // candidate exists.
5662 if (!AddedTypes.insert(CanonType) ||
5663 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5664 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005665 continue;
5666
5667 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005668 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5669 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005670 }
Douglas Gregor80af3132011-05-21 23:15:46 +00005671
5672 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5673 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5674 if (AddedTypes.insert(NullPtrTy) &&
5675 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5676 NullPtrTy))) {
5677 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5678 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5679 CandidateSet);
5680 }
5681 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005682 }
5683 }
5684
5685 // C++ [over.built]p13:
5686 //
5687 // For every cv-qualified or cv-unqualified object type T
5688 // there exist candidate operator functions of the form
5689 //
5690 // T* operator+(T*, ptrdiff_t);
5691 // T& operator[](T*, ptrdiff_t); [BELOW]
5692 // T* operator-(T*, ptrdiff_t);
5693 // T* operator+(ptrdiff_t, T*);
5694 // T& operator[](ptrdiff_t, T*); [BELOW]
5695 //
5696 // C++ [over.built]p14:
5697 //
5698 // For every T, where T is a pointer to object type, there
5699 // exist candidate operator functions of the form
5700 //
5701 // ptrdiff_t operator-(T, T);
5702 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5703 /// Set of (canonical) types that we've already handled.
5704 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5705
5706 for (int Arg = 0; Arg < 2; ++Arg) {
5707 QualType AsymetricParamTypes[2] = {
5708 S.Context.getPointerDiffType(),
5709 S.Context.getPointerDiffType(),
5710 };
5711 for (BuiltinCandidateTypeSet::iterator
5712 Ptr = CandidateTypes[Arg].pointer_begin(),
5713 PtrEnd = CandidateTypes[Arg].pointer_end();
5714 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005715 QualType PointeeTy = (*Ptr)->getPointeeType();
5716 if (!PointeeTy->isObjectType())
5717 continue;
5718
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005719 AsymetricParamTypes[Arg] = *Ptr;
5720 if (Arg == 0 || Op == OO_Plus) {
5721 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5722 // T* operator+(ptrdiff_t, T*);
5723 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5724 CandidateSet);
5725 }
5726 if (Op == OO_Minus) {
5727 // ptrdiff_t operator-(T, T);
5728 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5729 continue;
5730
5731 QualType ParamTypes[2] = { *Ptr, *Ptr };
5732 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5733 Args, 2, CandidateSet);
5734 }
5735 }
5736 }
5737 }
5738
5739 // C++ [over.built]p12:
5740 //
5741 // For every pair of promoted arithmetic types L and R, there
5742 // exist candidate operator functions of the form
5743 //
5744 // LR operator*(L, R);
5745 // LR operator/(L, R);
5746 // LR operator+(L, R);
5747 // LR operator-(L, R);
5748 // bool operator<(L, R);
5749 // bool operator>(L, R);
5750 // bool operator<=(L, R);
5751 // bool operator>=(L, R);
5752 // bool operator==(L, R);
5753 // bool operator!=(L, R);
5754 //
5755 // where LR is the result of the usual arithmetic conversions
5756 // between types L and R.
5757 //
5758 // C++ [over.built]p24:
5759 //
5760 // For every pair of promoted arithmetic types L and R, there exist
5761 // candidate operator functions of the form
5762 //
5763 // LR operator?(bool, L, R);
5764 //
5765 // where LR is the result of the usual arithmetic conversions
5766 // between types L and R.
5767 // Our candidates ignore the first parameter.
5768 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005769 if (!HasArithmeticOrEnumeralCandidateType)
5770 return;
5771
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005772 for (unsigned Left = FirstPromotedArithmeticType;
5773 Left < LastPromotedArithmeticType; ++Left) {
5774 for (unsigned Right = FirstPromotedArithmeticType;
5775 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005776 QualType LandR[2] = { getArithmeticType(Left),
5777 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005778 QualType Result =
5779 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005780 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005781 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5782 }
5783 }
5784
5785 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5786 // conditional operator for vector types.
5787 for (BuiltinCandidateTypeSet::iterator
5788 Vec1 = CandidateTypes[0].vector_begin(),
5789 Vec1End = CandidateTypes[0].vector_end();
5790 Vec1 != Vec1End; ++Vec1) {
5791 for (BuiltinCandidateTypeSet::iterator
5792 Vec2 = CandidateTypes[1].vector_begin(),
5793 Vec2End = CandidateTypes[1].vector_end();
5794 Vec2 != Vec2End; ++Vec2) {
5795 QualType LandR[2] = { *Vec1, *Vec2 };
5796 QualType Result = S.Context.BoolTy;
5797 if (!isComparison) {
5798 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5799 Result = *Vec1;
5800 else
5801 Result = *Vec2;
5802 }
5803
5804 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5805 }
5806 }
5807 }
5808
5809 // C++ [over.built]p17:
5810 //
5811 // For every pair of promoted integral types L and R, there
5812 // exist candidate operator functions of the form
5813 //
5814 // LR operator%(L, R);
5815 // LR operator&(L, R);
5816 // LR operator^(L, R);
5817 // LR operator|(L, R);
5818 // L operator<<(L, R);
5819 // L operator>>(L, R);
5820 //
5821 // where LR is the result of the usual arithmetic conversions
5822 // between types L and R.
5823 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005824 if (!HasArithmeticOrEnumeralCandidateType)
5825 return;
5826
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005827 for (unsigned Left = FirstPromotedIntegralType;
5828 Left < LastPromotedIntegralType; ++Left) {
5829 for (unsigned Right = FirstPromotedIntegralType;
5830 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005831 QualType LandR[2] = { getArithmeticType(Left),
5832 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005833 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5834 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005835 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005836 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5837 }
5838 }
5839 }
5840
5841 // C++ [over.built]p20:
5842 //
5843 // For every pair (T, VQ), where T is an enumeration or
5844 // pointer to member type and VQ is either volatile or
5845 // empty, there exist candidate operator functions of the form
5846 //
5847 // VQ T& operator=(VQ T&, T);
5848 void addAssignmentMemberPointerOrEnumeralOverloads() {
5849 /// Set of (canonical) types that we've already handled.
5850 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5851
5852 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5853 for (BuiltinCandidateTypeSet::iterator
5854 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5855 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5856 Enum != EnumEnd; ++Enum) {
5857 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5858 continue;
5859
5860 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5861 CandidateSet);
5862 }
5863
5864 for (BuiltinCandidateTypeSet::iterator
5865 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5866 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5867 MemPtr != MemPtrEnd; ++MemPtr) {
5868 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5869 continue;
5870
5871 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5872 CandidateSet);
5873 }
5874 }
5875 }
5876
5877 // C++ [over.built]p19:
5878 //
5879 // For every pair (T, VQ), where T is any type and VQ is either
5880 // volatile or empty, there exist candidate operator functions
5881 // of the form
5882 //
5883 // T*VQ& operator=(T*VQ&, T*);
5884 //
5885 // C++ [over.built]p21:
5886 //
5887 // For every pair (T, VQ), where T is a cv-qualified or
5888 // cv-unqualified object type and VQ is either volatile or
5889 // empty, there exist candidate operator functions of the form
5890 //
5891 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5892 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5893 void addAssignmentPointerOverloads(bool isEqualOp) {
5894 /// Set of (canonical) types that we've already handled.
5895 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5896
5897 for (BuiltinCandidateTypeSet::iterator
5898 Ptr = CandidateTypes[0].pointer_begin(),
5899 PtrEnd = CandidateTypes[0].pointer_end();
5900 Ptr != PtrEnd; ++Ptr) {
5901 // If this is operator=, keep track of the builtin candidates we added.
5902 if (isEqualOp)
5903 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005904 else if (!(*Ptr)->getPointeeType()->isObjectType())
5905 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005906
5907 // non-volatile version
5908 QualType ParamTypes[2] = {
5909 S.Context.getLValueReferenceType(*Ptr),
5910 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5911 };
5912 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5913 /*IsAssigmentOperator=*/ isEqualOp);
5914
5915 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5916 VisibleTypeConversionsQuals.hasVolatile()) {
5917 // volatile version
5918 ParamTypes[0] =
5919 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5920 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5921 /*IsAssigmentOperator=*/isEqualOp);
5922 }
5923 }
5924
5925 if (isEqualOp) {
5926 for (BuiltinCandidateTypeSet::iterator
5927 Ptr = CandidateTypes[1].pointer_begin(),
5928 PtrEnd = CandidateTypes[1].pointer_end();
5929 Ptr != PtrEnd; ++Ptr) {
5930 // Make sure we don't add the same candidate twice.
5931 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5932 continue;
5933
Chandler Carruth8e543b32010-12-12 08:17:55 +00005934 QualType ParamTypes[2] = {
5935 S.Context.getLValueReferenceType(*Ptr),
5936 *Ptr,
5937 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005938
5939 // non-volatile version
5940 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5941 /*IsAssigmentOperator=*/true);
5942
5943 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5944 VisibleTypeConversionsQuals.hasVolatile()) {
5945 // volatile version
5946 ParamTypes[0] =
5947 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00005948 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5949 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005950 }
5951 }
5952 }
5953 }
5954
5955 // C++ [over.built]p18:
5956 //
5957 // For every triple (L, VQ, R), where L is an arithmetic type,
5958 // VQ is either volatile or empty, and R is a promoted
5959 // arithmetic type, there exist candidate operator functions of
5960 // the form
5961 //
5962 // VQ L& operator=(VQ L&, R);
5963 // VQ L& operator*=(VQ L&, R);
5964 // VQ L& operator/=(VQ L&, R);
5965 // VQ L& operator+=(VQ L&, R);
5966 // VQ L& operator-=(VQ L&, R);
5967 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005968 if (!HasArithmeticOrEnumeralCandidateType)
5969 return;
5970
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005971 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5972 for (unsigned Right = FirstPromotedArithmeticType;
5973 Right < LastPromotedArithmeticType; ++Right) {
5974 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005975 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005976
5977 // Add this built-in operator as a candidate (VQ is empty).
5978 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005979 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005980 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5981 /*IsAssigmentOperator=*/isEqualOp);
5982
5983 // Add this built-in operator as a candidate (VQ is 'volatile').
5984 if (VisibleTypeConversionsQuals.hasVolatile()) {
5985 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005986 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005987 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005988 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5989 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005990 /*IsAssigmentOperator=*/isEqualOp);
5991 }
5992 }
5993 }
5994
5995 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5996 for (BuiltinCandidateTypeSet::iterator
5997 Vec1 = CandidateTypes[0].vector_begin(),
5998 Vec1End = CandidateTypes[0].vector_end();
5999 Vec1 != Vec1End; ++Vec1) {
6000 for (BuiltinCandidateTypeSet::iterator
6001 Vec2 = CandidateTypes[1].vector_begin(),
6002 Vec2End = CandidateTypes[1].vector_end();
6003 Vec2 != Vec2End; ++Vec2) {
6004 QualType ParamTypes[2];
6005 ParamTypes[1] = *Vec2;
6006 // Add this built-in operator as a candidate (VQ is empty).
6007 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6008 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6009 /*IsAssigmentOperator=*/isEqualOp);
6010
6011 // Add this built-in operator as a candidate (VQ is 'volatile').
6012 if (VisibleTypeConversionsQuals.hasVolatile()) {
6013 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6014 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006015 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6016 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006017 /*IsAssigmentOperator=*/isEqualOp);
6018 }
6019 }
6020 }
6021 }
6022
6023 // C++ [over.built]p22:
6024 //
6025 // For every triple (L, VQ, R), where L is an integral type, VQ
6026 // is either volatile or empty, and R is a promoted integral
6027 // type, there exist candidate operator functions of the form
6028 //
6029 // VQ L& operator%=(VQ L&, R);
6030 // VQ L& operator<<=(VQ L&, R);
6031 // VQ L& operator>>=(VQ L&, R);
6032 // VQ L& operator&=(VQ L&, R);
6033 // VQ L& operator^=(VQ L&, R);
6034 // VQ L& operator|=(VQ L&, R);
6035 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006036 if (!HasArithmeticOrEnumeralCandidateType)
6037 return;
6038
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006039 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6040 for (unsigned Right = FirstPromotedIntegralType;
6041 Right < LastPromotedIntegralType; ++Right) {
6042 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006043 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006044
6045 // Add this built-in operator as a candidate (VQ is empty).
6046 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006047 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006048 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6049 if (VisibleTypeConversionsQuals.hasVolatile()) {
6050 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006051 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006052 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6053 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6054 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6055 CandidateSet);
6056 }
6057 }
6058 }
6059 }
6060
6061 // C++ [over.operator]p23:
6062 //
6063 // There also exist candidate operator functions of the form
6064 //
6065 // bool operator!(bool);
6066 // bool operator&&(bool, bool);
6067 // bool operator||(bool, bool);
6068 void addExclaimOverload() {
6069 QualType ParamTy = S.Context.BoolTy;
6070 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6071 /*IsAssignmentOperator=*/false,
6072 /*NumContextualBoolArguments=*/1);
6073 }
6074 void addAmpAmpOrPipePipeOverload() {
6075 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6076 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6077 /*IsAssignmentOperator=*/false,
6078 /*NumContextualBoolArguments=*/2);
6079 }
6080
6081 // C++ [over.built]p13:
6082 //
6083 // For every cv-qualified or cv-unqualified object type T there
6084 // exist candidate operator functions of the form
6085 //
6086 // T* operator+(T*, ptrdiff_t); [ABOVE]
6087 // T& operator[](T*, ptrdiff_t);
6088 // T* operator-(T*, ptrdiff_t); [ABOVE]
6089 // T* operator+(ptrdiff_t, T*); [ABOVE]
6090 // T& operator[](ptrdiff_t, T*);
6091 void addSubscriptOverloads() {
6092 for (BuiltinCandidateTypeSet::iterator
6093 Ptr = CandidateTypes[0].pointer_begin(),
6094 PtrEnd = CandidateTypes[0].pointer_end();
6095 Ptr != PtrEnd; ++Ptr) {
6096 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6097 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006098 if (!PointeeType->isObjectType())
6099 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006100
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006101 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6102
6103 // T& operator[](T*, ptrdiff_t)
6104 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6105 }
6106
6107 for (BuiltinCandidateTypeSet::iterator
6108 Ptr = CandidateTypes[1].pointer_begin(),
6109 PtrEnd = CandidateTypes[1].pointer_end();
6110 Ptr != PtrEnd; ++Ptr) {
6111 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6112 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006113 if (!PointeeType->isObjectType())
6114 continue;
6115
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006116 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6117
6118 // T& operator[](ptrdiff_t, T*)
6119 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6120 }
6121 }
6122
6123 // C++ [over.built]p11:
6124 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6125 // C1 is the same type as C2 or is a derived class of C2, T is an object
6126 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6127 // there exist candidate operator functions of the form
6128 //
6129 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6130 //
6131 // where CV12 is the union of CV1 and CV2.
6132 void addArrowStarOverloads() {
6133 for (BuiltinCandidateTypeSet::iterator
6134 Ptr = CandidateTypes[0].pointer_begin(),
6135 PtrEnd = CandidateTypes[0].pointer_end();
6136 Ptr != PtrEnd; ++Ptr) {
6137 QualType C1Ty = (*Ptr);
6138 QualType C1;
6139 QualifierCollector Q1;
6140 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6141 if (!isa<RecordType>(C1))
6142 continue;
6143 // heuristic to reduce number of builtin candidates in the set.
6144 // Add volatile/restrict version only if there are conversions to a
6145 // volatile/restrict type.
6146 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6147 continue;
6148 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6149 continue;
6150 for (BuiltinCandidateTypeSet::iterator
6151 MemPtr = CandidateTypes[1].member_pointer_begin(),
6152 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6153 MemPtr != MemPtrEnd; ++MemPtr) {
6154 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6155 QualType C2 = QualType(mptr->getClass(), 0);
6156 C2 = C2.getUnqualifiedType();
6157 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6158 break;
6159 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6160 // build CV12 T&
6161 QualType T = mptr->getPointeeType();
6162 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6163 T.isVolatileQualified())
6164 continue;
6165 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6166 T.isRestrictQualified())
6167 continue;
6168 T = Q1.apply(S.Context, T);
6169 QualType ResultTy = S.Context.getLValueReferenceType(T);
6170 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6171 }
6172 }
6173 }
6174
6175 // Note that we don't consider the first argument, since it has been
6176 // contextually converted to bool long ago. The candidates below are
6177 // therefore added as binary.
6178 //
6179 // C++ [over.built]p25:
6180 // For every type T, where T is a pointer, pointer-to-member, or scoped
6181 // enumeration type, there exist candidate operator functions of the form
6182 //
6183 // T operator?(bool, T, T);
6184 //
6185 void addConditionalOperatorOverloads() {
6186 /// Set of (canonical) types that we've already handled.
6187 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6188
6189 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6190 for (BuiltinCandidateTypeSet::iterator
6191 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6192 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6193 Ptr != PtrEnd; ++Ptr) {
6194 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6195 continue;
6196
6197 QualType ParamTypes[2] = { *Ptr, *Ptr };
6198 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6199 }
6200
6201 for (BuiltinCandidateTypeSet::iterator
6202 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6203 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6204 MemPtr != MemPtrEnd; ++MemPtr) {
6205 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6206 continue;
6207
6208 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6209 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6210 }
6211
6212 if (S.getLangOptions().CPlusPlus0x) {
6213 for (BuiltinCandidateTypeSet::iterator
6214 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6215 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6216 Enum != EnumEnd; ++Enum) {
6217 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6218 continue;
6219
6220 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6221 continue;
6222
6223 QualType ParamTypes[2] = { *Enum, *Enum };
6224 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6225 }
6226 }
6227 }
6228 }
6229};
6230
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006231} // end anonymous namespace
6232
6233/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6234/// operator overloads to the candidate set (C++ [over.built]), based
6235/// on the operator @p Op and the arguments given. For example, if the
6236/// operator is a binary '+', this routine might add "int
6237/// operator+(int, int)" to cover integer addition.
6238void
6239Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6240 SourceLocation OpLoc,
6241 Expr **Args, unsigned NumArgs,
6242 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006243 // Find all of the types that the arguments can convert to, but only
6244 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006245 // that make use of these types. Also record whether we encounter non-record
6246 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006247 Qualifiers VisibleTypeConversionsQuals;
6248 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006249 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6250 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006251
6252 bool HasNonRecordCandidateType = false;
6253 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006254 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006255 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6256 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6257 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6258 OpLoc,
6259 true,
6260 (Op == OO_Exclaim ||
6261 Op == OO_AmpAmp ||
6262 Op == OO_PipePipe),
6263 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006264 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6265 CandidateTypes[ArgIdx].hasNonRecordTypes();
6266 HasArithmeticOrEnumeralCandidateType =
6267 HasArithmeticOrEnumeralCandidateType ||
6268 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006269 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006270
Chandler Carruth00a38332010-12-13 01:44:01 +00006271 // Exit early when no non-record types have been added to the candidate set
6272 // for any of the arguments to the operator.
6273 if (!HasNonRecordCandidateType)
6274 return;
6275
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006276 // Setup an object to manage the common state for building overloads.
6277 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6278 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006279 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006280 CandidateTypes, CandidateSet);
6281
6282 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006283 switch (Op) {
6284 case OO_None:
6285 case NUM_OVERLOADED_OPERATORS:
6286 assert(false && "Expected an overloaded operator");
6287 break;
6288
Chandler Carruth5184de02010-12-12 08:51:33 +00006289 case OO_New:
6290 case OO_Delete:
6291 case OO_Array_New:
6292 case OO_Array_Delete:
6293 case OO_Call:
6294 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
6295 break;
6296
6297 case OO_Comma:
6298 case OO_Arrow:
6299 // C++ [over.match.oper]p3:
6300 // -- For the operator ',', the unary operator '&', or the
6301 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006302 break;
6303
6304 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006305 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006306 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006307 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006308
6309 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006310 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006311 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006312 } else {
6313 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6314 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6315 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006316 break;
6317
Chandler Carruth5184de02010-12-12 08:51:33 +00006318 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006319 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006320 OpBuilder.addUnaryStarPointerOverloads();
6321 else
6322 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6323 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006324
Chandler Carruth5184de02010-12-12 08:51:33 +00006325 case OO_Slash:
6326 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006327 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006328
6329 case OO_PlusPlus:
6330 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006331 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6332 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006333 break;
6334
Douglas Gregor84605ae2009-08-24 13:43:27 +00006335 case OO_EqualEqual:
6336 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006337 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006338 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006339
Douglas Gregora11693b2008-11-12 17:17:38 +00006340 case OO_Less:
6341 case OO_Greater:
6342 case OO_LessEqual:
6343 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006344 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006345 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6346 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006347
Douglas Gregora11693b2008-11-12 17:17:38 +00006348 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006349 case OO_Caret:
6350 case OO_Pipe:
6351 case OO_LessLess:
6352 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006353 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006354 break;
6355
Chandler Carruth5184de02010-12-12 08:51:33 +00006356 case OO_Amp: // '&' is either unary or binary
6357 if (NumArgs == 1)
6358 // C++ [over.match.oper]p3:
6359 // -- For the operator ',', the unary operator '&', or the
6360 // operator '->', the built-in candidates set is empty.
6361 break;
6362
6363 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6364 break;
6365
6366 case OO_Tilde:
6367 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6368 break;
6369
Douglas Gregora11693b2008-11-12 17:17:38 +00006370 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006371 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006372 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006373
6374 case OO_PlusEqual:
6375 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006376 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006377 // Fall through.
6378
6379 case OO_StarEqual:
6380 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006381 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006382 break;
6383
6384 case OO_PercentEqual:
6385 case OO_LessLessEqual:
6386 case OO_GreaterGreaterEqual:
6387 case OO_AmpEqual:
6388 case OO_CaretEqual:
6389 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006390 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006391 break;
6392
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006393 case OO_Exclaim:
6394 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006395 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006396
Douglas Gregora11693b2008-11-12 17:17:38 +00006397 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006398 case OO_PipePipe:
6399 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006400 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006401
6402 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006403 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006404 break;
6405
6406 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006407 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006408 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006409
6410 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006411 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006412 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6413 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006414 }
6415}
6416
Douglas Gregore254f902009-02-04 00:32:51 +00006417/// \brief Add function candidates found via argument-dependent lookup
6418/// to the set of overloading candidates.
6419///
6420/// This routine performs argument-dependent name lookup based on the
6421/// given function name (which may also be an operator name) and adds
6422/// all of the overload candidates found by ADL to the overload
6423/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006424void
Douglas Gregore254f902009-02-04 00:32:51 +00006425Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006426 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006427 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006428 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006429 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006430 bool PartialOverloading,
6431 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006432 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006433
John McCall91f61fc2010-01-26 06:04:06 +00006434 // FIXME: This approach for uniquing ADL results (and removing
6435 // redundant candidates from the set) relies on pointer-equality,
6436 // which means we need to key off the canonical decl. However,
6437 // always going back to the canonical decl might not get us the
6438 // right set of default arguments. What default arguments are
6439 // we supposed to consider on ADL candidates, anyway?
6440
Douglas Gregorcabea402009-09-22 15:41:20 +00006441 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006442 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6443 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006444
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006445 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006446 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6447 CandEnd = CandidateSet.end();
6448 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006449 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006450 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006451 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006452 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006453 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006454
6455 // For each of the ADL candidates we found, add it to the overload
6456 // set.
John McCall8fe68082010-01-26 07:16:45 +00006457 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006458 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006459 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006460 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006461 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006462
John McCalla0296f72010-03-19 07:35:19 +00006463 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006464 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006465 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006466 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006467 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006468 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006469 }
Douglas Gregore254f902009-02-04 00:32:51 +00006470}
6471
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006472/// isBetterOverloadCandidate - Determines whether the first overload
6473/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006474bool
John McCall5c32be02010-08-24 20:38:10 +00006475isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006476 const OverloadCandidate &Cand1,
6477 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006478 SourceLocation Loc,
6479 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006480 // Define viable functions to be better candidates than non-viable
6481 // functions.
6482 if (!Cand2.Viable)
6483 return Cand1.Viable;
6484 else if (!Cand1.Viable)
6485 return false;
6486
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006487 // C++ [over.match.best]p1:
6488 //
6489 // -- if F is a static member function, ICS1(F) is defined such
6490 // that ICS1(F) is neither better nor worse than ICS1(G) for
6491 // any function G, and, symmetrically, ICS1(G) is neither
6492 // better nor worse than ICS1(F).
6493 unsigned StartArg = 0;
6494 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6495 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006496
Douglas Gregord3cb3562009-07-07 23:38:56 +00006497 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006498 // A viable function F1 is defined to be a better function than another
6499 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006500 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006501 unsigned NumArgs = Cand1.Conversions.size();
6502 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6503 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006504 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006505 switch (CompareImplicitConversionSequences(S,
6506 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006507 Cand2.Conversions[ArgIdx])) {
6508 case ImplicitConversionSequence::Better:
6509 // Cand1 has a better conversion sequence.
6510 HasBetterConversion = true;
6511 break;
6512
6513 case ImplicitConversionSequence::Worse:
6514 // Cand1 can't be better than Cand2.
6515 return false;
6516
6517 case ImplicitConversionSequence::Indistinguishable:
6518 // Do nothing.
6519 break;
6520 }
6521 }
6522
Mike Stump11289f42009-09-09 15:08:12 +00006523 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006524 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006525 if (HasBetterConversion)
6526 return true;
6527
Mike Stump11289f42009-09-09 15:08:12 +00006528 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006529 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006530 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006531 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6532 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006533
6534 // -- F1 and F2 are function template specializations, and the function
6535 // template for F1 is more specialized than the template for F2
6536 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006537 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006538 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006539 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006540 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006541 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6542 Cand2.Function->getPrimaryTemplate(),
6543 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006544 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006545 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006546 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006547 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006548 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006549
Douglas Gregora1f013e2008-11-07 22:36:19 +00006550 // -- the context is an initialization by user-defined conversion
6551 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6552 // from the return type of F1 to the destination type (i.e.,
6553 // the type of the entity being initialized) is a better
6554 // conversion sequence than the standard conversion sequence
6555 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006556 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006557 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006558 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006559 switch (CompareStandardConversionSequences(S,
6560 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006561 Cand2.FinalConversion)) {
6562 case ImplicitConversionSequence::Better:
6563 // Cand1 has a better conversion sequence.
6564 return true;
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
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006576 return false;
6577}
6578
Mike Stump11289f42009-09-09 15:08:12 +00006579/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006580/// within an overload candidate set.
6581///
6582/// \param CandidateSet the set of candidate functions.
6583///
6584/// \param Loc the location of the function name (or operator symbol) for
6585/// which overload resolution occurs.
6586///
Mike Stump11289f42009-09-09 15:08:12 +00006587/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006588/// function, Best points to the candidate function found.
6589///
6590/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006591OverloadingResult
6592OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006593 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00006594 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006595 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006596 Best = end();
6597 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6598 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006599 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006600 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006601 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006602 }
6603
6604 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006605 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006606 return OR_No_Viable_Function;
6607
6608 // Make sure that this function is better than every other viable
6609 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006610 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006611 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006612 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006613 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006614 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006615 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006616 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006617 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006618 }
Mike Stump11289f42009-09-09 15:08:12 +00006619
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006620 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006621 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00006622 (Best->Function->isDeleted() ||
6623 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006624 return OR_Deleted;
6625
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006626 return OR_Success;
6627}
6628
John McCall53262c92010-01-12 02:15:36 +00006629namespace {
6630
6631enum OverloadCandidateKind {
6632 oc_function,
6633 oc_method,
6634 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006635 oc_function_template,
6636 oc_method_template,
6637 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006638 oc_implicit_default_constructor,
6639 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006640 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006641 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006642 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00006643 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006644};
6645
John McCalle1ac8d12010-01-13 00:25:19 +00006646OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6647 FunctionDecl *Fn,
6648 std::string &Description) {
6649 bool isTemplate = false;
6650
6651 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6652 isTemplate = true;
6653 Description = S.getTemplateArgumentBindingsText(
6654 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6655 }
John McCallfd0b2f82010-01-06 09:43:14 +00006656
6657 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006658 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006659 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006660
Sebastian Redl08905022011-02-05 19:23:19 +00006661 if (Ctor->getInheritedConstructor())
6662 return oc_implicit_inherited_constructor;
6663
Alexis Hunt119c10e2011-05-25 23:16:36 +00006664 if (Ctor->isDefaultConstructor())
6665 return oc_implicit_default_constructor;
6666
6667 if (Ctor->isMoveConstructor())
6668 return oc_implicit_move_constructor;
6669
6670 assert(Ctor->isCopyConstructor() &&
6671 "unexpected sort of implicit constructor");
6672 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006673 }
6674
6675 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6676 // This actually gets spelled 'candidate function' for now, but
6677 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006678 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006679 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006680
Alexis Hunt119c10e2011-05-25 23:16:36 +00006681 if (Meth->isMoveAssignmentOperator())
6682 return oc_implicit_move_assignment;
6683
Douglas Gregorec3bec02010-09-27 22:37:28 +00006684 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006685 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006686 return oc_implicit_copy_assignment;
6687 }
6688
John McCalle1ac8d12010-01-13 00:25:19 +00006689 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006690}
6691
Sebastian Redl08905022011-02-05 19:23:19 +00006692void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6693 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6694 if (!Ctor) return;
6695
6696 Ctor = Ctor->getInheritedConstructor();
6697 if (!Ctor) return;
6698
6699 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6700}
6701
John McCall53262c92010-01-12 02:15:36 +00006702} // end anonymous namespace
6703
6704// Notes the location of an overload candidate.
6705void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006706 std::string FnDesc;
6707 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6708 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6709 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00006710 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00006711}
6712
Douglas Gregorb491ed32011-02-19 21:32:49 +00006713//Notes the location of all overload candidates designated through
6714// OverloadedExpr
6715void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6716 assert(OverloadedExpr->getType() == Context.OverloadTy);
6717
6718 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6719 OverloadExpr *OvlExpr = Ovl.Expression;
6720
6721 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6722 IEnd = OvlExpr->decls_end();
6723 I != IEnd; ++I) {
6724 if (FunctionTemplateDecl *FunTmpl =
6725 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6726 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6727 } else if (FunctionDecl *Fun
6728 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6729 NoteOverloadCandidate(Fun);
6730 }
6731 }
6732}
6733
John McCall0d1da222010-01-12 00:44:57 +00006734/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6735/// "lead" diagnostic; it will be given two arguments, the source and
6736/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006737void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6738 Sema &S,
6739 SourceLocation CaretLoc,
6740 const PartialDiagnostic &PDiag) const {
6741 S.Diag(CaretLoc, PDiag)
6742 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006743 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006744 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6745 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006746 }
John McCall12f97bc2010-01-08 04:41:39 +00006747}
6748
John McCall0d1da222010-01-12 00:44:57 +00006749namespace {
6750
John McCall6a61b522010-01-13 09:16:55 +00006751void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6752 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6753 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006754 assert(Cand->Function && "for now, candidate must be a function");
6755 FunctionDecl *Fn = Cand->Function;
6756
6757 // There's a conversion slot for the object argument if this is a
6758 // non-constructor method. Note that 'I' corresponds the
6759 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006760 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006761 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006762 if (I == 0)
6763 isObjectArgument = true;
6764 else
6765 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006766 }
6767
John McCalle1ac8d12010-01-13 00:25:19 +00006768 std::string FnDesc;
6769 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6770
John McCall6a61b522010-01-13 09:16:55 +00006771 Expr *FromExpr = Conv.Bad.FromExpr;
6772 QualType FromTy = Conv.Bad.getFromType();
6773 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006774
John McCallfb7ad0f2010-02-02 02:42:52 +00006775 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006776 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006777 Expr *E = FromExpr->IgnoreParens();
6778 if (isa<UnaryOperator>(E))
6779 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006780 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006781
6782 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6783 << (unsigned) FnKind << FnDesc
6784 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6785 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006786 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00006787 return;
6788 }
6789
John McCall6d174642010-01-23 08:10:49 +00006790 // Do some hand-waving analysis to see if the non-viability is due
6791 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006792 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6793 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6794 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6795 CToTy = RT->getPointeeType();
6796 else {
6797 // TODO: detect and diagnose the full richness of const mismatches.
6798 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6799 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6800 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6801 }
6802
6803 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6804 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6805 // It is dumb that we have to do this here.
6806 while (isa<ArrayType>(CFromTy))
6807 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6808 while (isa<ArrayType>(CToTy))
6809 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6810
6811 Qualifiers FromQs = CFromTy.getQualifiers();
6812 Qualifiers ToQs = CToTy.getQualifiers();
6813
6814 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6815 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6816 << (unsigned) FnKind << FnDesc
6817 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6818 << FromTy
6819 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6820 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006821 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006822 return;
6823 }
6824
John McCall31168b02011-06-15 23:02:42 +00006825 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00006826 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00006827 << (unsigned) FnKind << FnDesc
6828 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6829 << FromTy
6830 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
6831 << (unsigned) isObjectArgument << I+1;
6832 MaybeEmitInheritedConstructorNote(S, Fn);
6833 return;
6834 }
6835
Douglas Gregoraec25842011-04-26 23:16:46 +00006836 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
6837 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
6838 << (unsigned) FnKind << FnDesc
6839 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6840 << FromTy
6841 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
6842 << (unsigned) isObjectArgument << I+1;
6843 MaybeEmitInheritedConstructorNote(S, Fn);
6844 return;
6845 }
6846
John McCall47000992010-01-14 03:28:57 +00006847 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6848 assert(CVR && "unexpected qualifiers mismatch");
6849
6850 if (isObjectArgument) {
6851 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6852 << (unsigned) FnKind << FnDesc
6853 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6854 << FromTy << (CVR - 1);
6855 } else {
6856 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6857 << (unsigned) FnKind << FnDesc
6858 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6859 << FromTy << (CVR - 1) << I+1;
6860 }
Sebastian Redl08905022011-02-05 19:23:19 +00006861 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006862 return;
6863 }
6864
John McCall6d174642010-01-23 08:10:49 +00006865 // Diagnose references or pointers to incomplete types differently,
6866 // since it's far from impossible that the incompleteness triggered
6867 // the failure.
6868 QualType TempFromTy = FromTy.getNonReferenceType();
6869 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6870 TempFromTy = PTy->getPointeeType();
6871 if (TempFromTy->isIncompleteType()) {
6872 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6873 << (unsigned) FnKind << FnDesc
6874 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6875 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006876 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00006877 return;
6878 }
6879
Douglas Gregor56f2e342010-06-30 23:01:39 +00006880 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006881 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006882 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6883 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6884 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6885 FromPtrTy->getPointeeType()) &&
6886 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6887 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006888 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00006889 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006890 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006891 }
6892 } else if (const ObjCObjectPointerType *FromPtrTy
6893 = FromTy->getAs<ObjCObjectPointerType>()) {
6894 if (const ObjCObjectPointerType *ToPtrTy
6895 = ToTy->getAs<ObjCObjectPointerType>())
6896 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6897 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6898 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6899 FromPtrTy->getPointeeType()) &&
6900 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006901 BaseToDerivedConversion = 2;
6902 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6903 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6904 !FromTy->isIncompleteType() &&
6905 !ToRefTy->getPointeeType()->isIncompleteType() &&
6906 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6907 BaseToDerivedConversion = 3;
6908 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006909
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006910 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006911 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006912 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006913 << (unsigned) FnKind << FnDesc
6914 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006915 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006916 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006917 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00006918 return;
6919 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006920
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00006921 if (isa<ObjCObjectPointerType>(CFromTy) &&
6922 isa<PointerType>(CToTy)) {
6923 Qualifiers FromQs = CFromTy.getQualifiers();
6924 Qualifiers ToQs = CToTy.getQualifiers();
6925 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
6926 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
6927 << (unsigned) FnKind << FnDesc
6928 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6929 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6930 MaybeEmitInheritedConstructorNote(S, Fn);
6931 return;
6932 }
6933 }
6934
Anna Zaksdf92ddf2011-07-19 19:49:12 +00006935 // Emit the generic diagnostic and, optionally, add the hints to it.
6936 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
6937 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006938 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00006939 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
6940 << (unsigned) (Cand->Fix.Kind);
6941
6942 // If we can fix the conversion, suggest the FixIts.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006943 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksdf92ddf2011-07-19 19:49:12 +00006944 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
6945 HI != HE; ++HI)
6946 FDiag << *HI;
6947 S.Diag(Fn->getLocation(), FDiag);
6948
Sebastian Redl08905022011-02-05 19:23:19 +00006949 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00006950}
6951
6952void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6953 unsigned NumFormalArgs) {
6954 // TODO: treat calls to a missing default constructor as a special case
6955
6956 FunctionDecl *Fn = Cand->Function;
6957 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6958
6959 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006960
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00006961 // With invalid overloaded operators, it's possible that we think we
6962 // have an arity mismatch when it fact it looks like we have the
6963 // right number of arguments, because only overloaded operators have
6964 // the weird behavior of overloading member and non-member functions.
6965 // Just don't report anything.
6966 if (Fn->isInvalidDecl() &&
6967 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
6968 return;
6969
John McCall6a61b522010-01-13 09:16:55 +00006970 // at least / at most / exactly
6971 unsigned mode, modeCount;
6972 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006973 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6974 (Cand->FailureKind == ovl_fail_bad_deduction &&
6975 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006976 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00006977 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00006978 mode = 0; // "at least"
6979 else
6980 mode = 2; // "exactly"
6981 modeCount = MinParams;
6982 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006983 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6984 (Cand->FailureKind == ovl_fail_bad_deduction &&
6985 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006986 if (MinParams != FnTy->getNumArgs())
6987 mode = 1; // "at most"
6988 else
6989 mode = 2; // "exactly"
6990 modeCount = FnTy->getNumArgs();
6991 }
6992
6993 std::string Description;
6994 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6995
6996 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006997 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00006998 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00006999 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007000}
7001
John McCall8b9ed552010-02-01 18:53:26 +00007002/// Diagnose a failed template-argument deduction.
7003void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7004 Expr **Args, unsigned NumArgs) {
7005 FunctionDecl *Fn = Cand->Function; // pattern
7006
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007007 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007008 NamedDecl *ParamD;
7009 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7010 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7011 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007012 switch (Cand->DeductionFailure.Result) {
7013 case Sema::TDK_Success:
7014 llvm_unreachable("TDK_success while diagnosing bad deduction");
7015
7016 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007017 assert(ParamD && "no parameter found for incomplete deduction result");
7018 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7019 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007020 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007021 return;
7022 }
7023
John McCall42d7d192010-08-05 09:05:08 +00007024 case Sema::TDK_Underqualified: {
7025 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7026 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7027
7028 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7029
7030 // Param will have been canonicalized, but it should just be a
7031 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007032 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007033 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007034 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007035 assert(S.Context.hasSameType(Param, NonCanonParam));
7036
7037 // Arg has also been canonicalized, but there's nothing we can do
7038 // about that. It also doesn't matter as much, because it won't
7039 // have any template parameters in it (because deduction isn't
7040 // done on dependent types).
7041 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7042
7043 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7044 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007045 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007046 return;
7047 }
7048
7049 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007050 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007051 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007052 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007053 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007054 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007055 which = 1;
7056 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007057 which = 2;
7058 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007059
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007060 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007061 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007062 << *Cand->DeductionFailure.getFirstArg()
7063 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007064 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007065 return;
7066 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007067
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007068 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007069 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007070 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007071 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007072 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7073 << ParamD->getDeclName();
7074 else {
7075 int index = 0;
7076 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7077 index = TTP->getIndex();
7078 else if (NonTypeTemplateParmDecl *NTTP
7079 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7080 index = NTTP->getIndex();
7081 else
7082 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007083 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007084 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7085 << (index + 1);
7086 }
Sebastian Redl08905022011-02-05 19:23:19 +00007087 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007088 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007089
Douglas Gregor02eb4832010-05-08 18:13:28 +00007090 case Sema::TDK_TooManyArguments:
7091 case Sema::TDK_TooFewArguments:
7092 DiagnoseArityMismatch(S, Cand, NumArgs);
7093 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007094
7095 case Sema::TDK_InstantiationDepth:
7096 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007097 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007098 return;
7099
7100 case Sema::TDK_SubstitutionFailure: {
7101 std::string ArgString;
7102 if (TemplateArgumentList *Args
7103 = Cand->DeductionFailure.getTemplateArgumentList())
7104 ArgString = S.getTemplateArgumentBindingsText(
7105 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7106 *Args);
7107 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7108 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007109 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007110 return;
7111 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007112
John McCall8b9ed552010-02-01 18:53:26 +00007113 // TODO: diagnose these individually, then kill off
7114 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007115 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007116 case Sema::TDK_FailedOverloadResolution:
7117 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007118 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007119 return;
7120 }
7121}
7122
7123/// Generates a 'note' diagnostic for an overload candidate. We've
7124/// already generated a primary error at the call site.
7125///
7126/// It really does need to be a single diagnostic with its caret
7127/// pointed at the candidate declaration. Yes, this creates some
7128/// major challenges of technical writing. Yes, this makes pointing
7129/// out problems with specific arguments quite awkward. It's still
7130/// better than generating twenty screens of text for every failed
7131/// overload.
7132///
7133/// It would be great to be able to express per-candidate problems
7134/// more richly for those diagnostic clients that cared, but we'd
7135/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007136void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7137 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007138 FunctionDecl *Fn = Cand->Function;
7139
John McCall12f97bc2010-01-08 04:41:39 +00007140 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007141 if (Cand->Viable && (Fn->isDeleted() ||
7142 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007143 std::string FnDesc;
7144 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007145
7146 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007147 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007148 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007149 return;
John McCall12f97bc2010-01-08 04:41:39 +00007150 }
7151
John McCalle1ac8d12010-01-13 00:25:19 +00007152 // We don't really have anything else to say about viable candidates.
7153 if (Cand->Viable) {
7154 S.NoteOverloadCandidate(Fn);
7155 return;
7156 }
John McCall0d1da222010-01-12 00:44:57 +00007157
John McCall6a61b522010-01-13 09:16:55 +00007158 switch (Cand->FailureKind) {
7159 case ovl_fail_too_many_arguments:
7160 case ovl_fail_too_few_arguments:
7161 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007162
John McCall6a61b522010-01-13 09:16:55 +00007163 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007164 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7165
John McCallfe796dd2010-01-23 05:17:32 +00007166 case ovl_fail_trivial_conversion:
7167 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007168 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007169 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007170
John McCall65eb8792010-02-25 01:37:24 +00007171 case ovl_fail_bad_conversion: {
7172 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7173 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007174 if (Cand->Conversions[I].isBad())
7175 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007176
John McCall6a61b522010-01-13 09:16:55 +00007177 // FIXME: this currently happens when we're called from SemaInit
7178 // when user-conversion overload fails. Figure out how to handle
7179 // those conditions and diagnose them well.
7180 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007181 }
John McCall65eb8792010-02-25 01:37:24 +00007182 }
John McCalld3224162010-01-08 00:58:21 +00007183}
7184
7185void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7186 // Desugar the type of the surrogate down to a function type,
7187 // retaining as many typedefs as possible while still showing
7188 // the function type (and, therefore, its parameter types).
7189 QualType FnType = Cand->Surrogate->getConversionType();
7190 bool isLValueReference = false;
7191 bool isRValueReference = false;
7192 bool isPointer = false;
7193 if (const LValueReferenceType *FnTypeRef =
7194 FnType->getAs<LValueReferenceType>()) {
7195 FnType = FnTypeRef->getPointeeType();
7196 isLValueReference = true;
7197 } else if (const RValueReferenceType *FnTypeRef =
7198 FnType->getAs<RValueReferenceType>()) {
7199 FnType = FnTypeRef->getPointeeType();
7200 isRValueReference = true;
7201 }
7202 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7203 FnType = FnTypePtr->getPointeeType();
7204 isPointer = true;
7205 }
7206 // Desugar down to a function type.
7207 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7208 // Reconstruct the pointer/reference as appropriate.
7209 if (isPointer) FnType = S.Context.getPointerType(FnType);
7210 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7211 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7212
7213 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7214 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007215 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007216}
7217
7218void NoteBuiltinOperatorCandidate(Sema &S,
7219 const char *Opc,
7220 SourceLocation OpLoc,
7221 OverloadCandidate *Cand) {
7222 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7223 std::string TypeStr("operator");
7224 TypeStr += Opc;
7225 TypeStr += "(";
7226 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7227 if (Cand->Conversions.size() == 1) {
7228 TypeStr += ")";
7229 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7230 } else {
7231 TypeStr += ", ";
7232 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7233 TypeStr += ")";
7234 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7235 }
7236}
7237
7238void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7239 OverloadCandidate *Cand) {
7240 unsigned NoOperands = Cand->Conversions.size();
7241 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7242 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007243 if (ICS.isBad()) break; // all meaningless after first invalid
7244 if (!ICS.isAmbiguous()) continue;
7245
John McCall5c32be02010-08-24 20:38:10 +00007246 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007247 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007248 }
7249}
7250
John McCall3712d9e2010-01-15 23:32:50 +00007251SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7252 if (Cand->Function)
7253 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007254 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007255 return Cand->Surrogate->getLocation();
7256 return SourceLocation();
7257}
7258
John McCallad2587a2010-01-12 00:48:53 +00007259struct CompareOverloadCandidatesForDisplay {
7260 Sema &S;
7261 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007262
7263 bool operator()(const OverloadCandidate *L,
7264 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007265 // Fast-path this check.
7266 if (L == R) return false;
7267
John McCall12f97bc2010-01-08 04:41:39 +00007268 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007269 if (L->Viable) {
7270 if (!R->Viable) return true;
7271
7272 // TODO: introduce a tri-valued comparison for overload
7273 // candidates. Would be more worthwhile if we had a sort
7274 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007275 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7276 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007277 } else if (R->Viable)
7278 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007279
John McCall3712d9e2010-01-15 23:32:50 +00007280 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007281
John McCall3712d9e2010-01-15 23:32:50 +00007282 // Criteria by which we can sort non-viable candidates:
7283 if (!L->Viable) {
7284 // 1. Arity mismatches come after other candidates.
7285 if (L->FailureKind == ovl_fail_too_many_arguments ||
7286 L->FailureKind == ovl_fail_too_few_arguments)
7287 return false;
7288 if (R->FailureKind == ovl_fail_too_many_arguments ||
7289 R->FailureKind == ovl_fail_too_few_arguments)
7290 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007291
John McCallfe796dd2010-01-23 05:17:32 +00007292 // 2. Bad conversions come first and are ordered by the number
7293 // of bad conversions and quality of good conversions.
7294 if (L->FailureKind == ovl_fail_bad_conversion) {
7295 if (R->FailureKind != ovl_fail_bad_conversion)
7296 return true;
7297
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007298 // The conversion that can be fixed with a smaller number of changes,
7299 // comes first.
7300 unsigned numLFixes = L->Fix.NumConversionsFixed;
7301 unsigned numRFixes = R->Fix.NumConversionsFixed;
7302 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7303 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007304 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007305 if (numLFixes < numRFixes)
7306 return true;
7307 else
7308 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007309 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007310
John McCallfe796dd2010-01-23 05:17:32 +00007311 // If there's any ordering between the defined conversions...
7312 // FIXME: this might not be transitive.
7313 assert(L->Conversions.size() == R->Conversions.size());
7314
7315 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007316 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7317 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007318 switch (CompareImplicitConversionSequences(S,
7319 L->Conversions[I],
7320 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007321 case ImplicitConversionSequence::Better:
7322 leftBetter++;
7323 break;
7324
7325 case ImplicitConversionSequence::Worse:
7326 leftBetter--;
7327 break;
7328
7329 case ImplicitConversionSequence::Indistinguishable:
7330 break;
7331 }
7332 }
7333 if (leftBetter > 0) return true;
7334 if (leftBetter < 0) return false;
7335
7336 } else if (R->FailureKind == ovl_fail_bad_conversion)
7337 return false;
7338
John McCall3712d9e2010-01-15 23:32:50 +00007339 // TODO: others?
7340 }
7341
7342 // Sort everything else by location.
7343 SourceLocation LLoc = GetLocationForCandidate(L);
7344 SourceLocation RLoc = GetLocationForCandidate(R);
7345
7346 // Put candidates without locations (e.g. builtins) at the end.
7347 if (LLoc.isInvalid()) return false;
7348 if (RLoc.isInvalid()) return true;
7349
7350 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007351 }
7352};
7353
John McCallfe796dd2010-01-23 05:17:32 +00007354/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007355/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00007356void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7357 Expr **Args, unsigned NumArgs) {
7358 assert(!Cand->Viable);
7359
7360 // Don't do anything on failures other than bad conversion.
7361 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7362
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007363 // We only want the FixIts if all the arguments can be corrected.
7364 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00007365 // Use a implicit copy initialization to check conversion fixes.
7366 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007367
John McCallfe796dd2010-01-23 05:17:32 +00007368 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007369 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007370 unsigned ConvCount = Cand->Conversions.size();
7371 while (true) {
7372 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7373 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007374 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00007375 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00007376 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007377 }
John McCallfe796dd2010-01-23 05:17:32 +00007378 }
7379
7380 if (ConvIdx == ConvCount)
7381 return;
7382
John McCall65eb8792010-02-25 01:37:24 +00007383 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7384 "remaining conversion is initialized?");
7385
Douglas Gregoradc7a702010-04-16 17:45:54 +00007386 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007387 // operation somehow.
7388 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007389
7390 const FunctionProtoType* Proto;
7391 unsigned ArgIdx = ConvIdx;
7392
7393 if (Cand->IsSurrogate) {
7394 QualType ConvType
7395 = Cand->Surrogate->getConversionType().getNonReferenceType();
7396 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7397 ConvType = ConvPtrType->getPointeeType();
7398 Proto = ConvType->getAs<FunctionProtoType>();
7399 ArgIdx--;
7400 } else if (Cand->Function) {
7401 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7402 if (isa<CXXMethodDecl>(Cand->Function) &&
7403 !isa<CXXConstructorDecl>(Cand->Function))
7404 ArgIdx--;
7405 } else {
7406 // Builtin binary operator with a bad first conversion.
7407 assert(ConvCount <= 3);
7408 for (; ConvIdx != ConvCount; ++ConvIdx)
7409 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007410 = TryCopyInitialization(S, Args[ConvIdx],
7411 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007412 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007413 /*InOverloadResolution*/ true,
7414 /*AllowObjCWritebackConversion=*/
7415 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00007416 return;
7417 }
7418
7419 // Fill in the rest of the conversions.
7420 unsigned NumArgsInProto = Proto->getNumArgs();
7421 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007422 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00007423 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007424 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007425 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007426 /*InOverloadResolution=*/true,
7427 /*AllowObjCWritebackConversion=*/
7428 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007429 // Store the FixIt in the candidate if it exists.
7430 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00007431 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007432 }
John McCallfe796dd2010-01-23 05:17:32 +00007433 else
7434 Cand->Conversions[ConvIdx].setEllipsis();
7435 }
7436}
7437
John McCalld3224162010-01-08 00:58:21 +00007438} // end anonymous namespace
7439
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007440/// PrintOverloadCandidates - When overload resolution fails, prints
7441/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007442/// set.
John McCall5c32be02010-08-24 20:38:10 +00007443void OverloadCandidateSet::NoteCandidates(Sema &S,
7444 OverloadCandidateDisplayKind OCD,
7445 Expr **Args, unsigned NumArgs,
7446 const char *Opc,
7447 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007448 // Sort the candidates by viability and position. Sorting directly would
7449 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007450 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007451 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7452 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007453 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007454 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007455 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007456 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007457 if (Cand->Function || Cand->IsSurrogate)
7458 Cands.push_back(Cand);
7459 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7460 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007461 }
7462 }
7463
John McCallad2587a2010-01-12 00:48:53 +00007464 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007465 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007466
John McCall0d1da222010-01-12 00:44:57 +00007467 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007468
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007469 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00007470 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007471 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007472 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7473 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007474
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007475 // Set an arbitrary limit on the number of candidate functions we'll spam
7476 // the user with. FIXME: This limit should depend on details of the
7477 // candidate list.
7478 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
7479 break;
7480 }
7481 ++CandsShown;
7482
John McCalld3224162010-01-08 00:58:21 +00007483 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007484 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007485 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007486 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007487 else {
7488 assert(Cand->Viable &&
7489 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007490 // Generally we only see ambiguities including viable builtin
7491 // operators if overload resolution got screwed up by an
7492 // ambiguous user-defined conversion.
7493 //
7494 // FIXME: It's quite possible for different conversions to see
7495 // different ambiguities, though.
7496 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007497 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007498 ReportedAmbiguousConversions = true;
7499 }
John McCalld3224162010-01-08 00:58:21 +00007500
John McCall0d1da222010-01-12 00:44:57 +00007501 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007502 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007503 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007504 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007505
7506 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007507 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007508}
7509
Douglas Gregorb491ed32011-02-19 21:32:49 +00007510// [PossiblyAFunctionType] --> [Return]
7511// NonFunctionType --> NonFunctionType
7512// R (A) --> R(A)
7513// R (*)(A) --> R (A)
7514// R (&)(A) --> R (A)
7515// R (S::*)(A) --> R (A)
7516QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7517 QualType Ret = PossiblyAFunctionType;
7518 if (const PointerType *ToTypePtr =
7519 PossiblyAFunctionType->getAs<PointerType>())
7520 Ret = ToTypePtr->getPointeeType();
7521 else if (const ReferenceType *ToTypeRef =
7522 PossiblyAFunctionType->getAs<ReferenceType>())
7523 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007524 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007525 PossiblyAFunctionType->getAs<MemberPointerType>())
7526 Ret = MemTypePtr->getPointeeType();
7527 Ret =
7528 Context.getCanonicalType(Ret).getUnqualifiedType();
7529 return Ret;
7530}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007531
Douglas Gregorb491ed32011-02-19 21:32:49 +00007532// A helper class to help with address of function resolution
7533// - allows us to avoid passing around all those ugly parameters
7534class AddressOfFunctionResolver
7535{
7536 Sema& S;
7537 Expr* SourceExpr;
7538 const QualType& TargetType;
7539 QualType TargetFunctionType; // Extracted function type from target type
7540
7541 bool Complain;
7542 //DeclAccessPair& ResultFunctionAccessPair;
7543 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007544
Douglas Gregorb491ed32011-02-19 21:32:49 +00007545 bool TargetTypeIsNonStaticMemberFunction;
7546 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007547
Douglas Gregorb491ed32011-02-19 21:32:49 +00007548 OverloadExpr::FindResult OvlExprInfo;
7549 OverloadExpr *OvlExpr;
7550 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007551 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007552
Douglas Gregorb491ed32011-02-19 21:32:49 +00007553public:
7554 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7555 const QualType& TargetType, bool Complain)
7556 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7557 Complain(Complain), Context(S.getASTContext()),
7558 TargetTypeIsNonStaticMemberFunction(
7559 !!TargetType->getAs<MemberPointerType>()),
7560 FoundNonTemplateFunction(false),
7561 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7562 OvlExpr(OvlExprInfo.Expression)
7563 {
7564 ExtractUnqualifiedFunctionTypeFromTargetType();
7565
7566 if (!TargetFunctionType->isFunctionType()) {
7567 if (OvlExpr->hasExplicitTemplateArgs()) {
7568 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00007569 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00007570 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00007571
7572 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7573 if (!Method->isStatic()) {
7574 // If the target type is a non-function type and the function
7575 // found is a non-static member function, pretend as if that was
7576 // the target, it's the only possible type to end up with.
7577 TargetTypeIsNonStaticMemberFunction = true;
7578
7579 // And skip adding the function if its not in the proper form.
7580 // We'll diagnose this due to an empty set of functions.
7581 if (!OvlExprInfo.HasFormOfMemberPointer)
7582 return;
7583 }
7584 }
7585
Douglas Gregorb491ed32011-02-19 21:32:49 +00007586 Matches.push_back(std::make_pair(dap,Fn));
7587 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007588 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007589 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007590 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007591
7592 if (OvlExpr->hasExplicitTemplateArgs())
7593 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007594
Douglas Gregorb491ed32011-02-19 21:32:49 +00007595 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7596 // C++ [over.over]p4:
7597 // If more than one function is selected, [...]
7598 if (Matches.size() > 1) {
7599 if (FoundNonTemplateFunction)
7600 EliminateAllTemplateMatches();
7601 else
7602 EliminateAllExceptMostSpecializedTemplate();
7603 }
7604 }
7605 }
7606
7607private:
7608 bool isTargetTypeAFunction() const {
7609 return TargetFunctionType->isFunctionType();
7610 }
7611
7612 // [ToType] [Return]
7613
7614 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7615 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7616 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7617 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7618 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7619 }
7620
7621 // return true if any matching specializations were found
7622 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7623 const DeclAccessPair& CurAccessFunPair) {
7624 if (CXXMethodDecl *Method
7625 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7626 // Skip non-static function templates when converting to pointer, and
7627 // static when converting to member pointer.
7628 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7629 return false;
7630 }
7631 else if (TargetTypeIsNonStaticMemberFunction)
7632 return false;
7633
7634 // C++ [over.over]p2:
7635 // If the name is a function template, template argument deduction is
7636 // done (14.8.2.2), and if the argument deduction succeeds, the
7637 // resulting template argument list is used to generate a single
7638 // function template specialization, which is added to the set of
7639 // overloaded functions considered.
7640 FunctionDecl *Specialization = 0;
7641 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7642 if (Sema::TemplateDeductionResult Result
7643 = S.DeduceTemplateArguments(FunctionTemplate,
7644 &OvlExplicitTemplateArgs,
7645 TargetFunctionType, Specialization,
7646 Info)) {
7647 // FIXME: make a note of the failed deduction for diagnostics.
7648 (void)Result;
7649 return false;
7650 }
7651
7652 // Template argument deduction ensures that we have an exact match.
7653 // This function template specicalization works.
7654 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7655 assert(TargetFunctionType
7656 == Context.getCanonicalType(Specialization->getType()));
7657 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7658 return true;
7659 }
7660
7661 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7662 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007663 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007664 // Skip non-static functions when converting to pointer, and static
7665 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007666 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7667 return false;
7668 }
7669 else if (TargetTypeIsNonStaticMemberFunction)
7670 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007671
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007672 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007673 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007674 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7675 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00007676 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
7677 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007678 Matches.push_back(std::make_pair(CurAccessFunPair,
7679 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007680 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007681 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007682 }
Mike Stump11289f42009-09-09 15:08:12 +00007683 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007684
7685 return false;
7686 }
7687
7688 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7689 bool Ret = false;
7690
7691 // If the overload expression doesn't have the form of a pointer to
7692 // member, don't try to convert it to a pointer-to-member type.
7693 if (IsInvalidFormOfPointerToMemberFunction())
7694 return false;
7695
7696 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7697 E = OvlExpr->decls_end();
7698 I != E; ++I) {
7699 // Look through any using declarations to find the underlying function.
7700 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7701
7702 // C++ [over.over]p3:
7703 // Non-member functions and static member functions match
7704 // targets of type "pointer-to-function" or "reference-to-function."
7705 // Nonstatic member functions match targets of
7706 // type "pointer-to-member-function."
7707 // Note that according to DR 247, the containing class does not matter.
7708 if (FunctionTemplateDecl *FunctionTemplate
7709 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7710 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7711 Ret = true;
7712 }
7713 // If we have explicit template arguments supplied, skip non-templates.
7714 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7715 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7716 Ret = true;
7717 }
7718 assert(Ret || Matches.empty());
7719 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007720 }
7721
Douglas Gregorb491ed32011-02-19 21:32:49 +00007722 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00007723 // [...] and any given function template specialization F1 is
7724 // eliminated if the set contains a second function template
7725 // specialization whose function template is more specialized
7726 // than the function template of F1 according to the partial
7727 // ordering rules of 14.5.5.2.
7728
7729 // The algorithm specified above is quadratic. We instead use a
7730 // two-pass algorithm (similar to the one used to identify the
7731 // best viable function in an overload set) that identifies the
7732 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007733
7734 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7735 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7736 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007737
John McCall58cc69d2010-01-27 01:50:18 +00007738 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007739 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7740 TPOC_Other, 0, SourceExpr->getLocStart(),
7741 S.PDiag(),
7742 S.PDiag(diag::err_addr_ovl_ambiguous)
7743 << Matches[0].second->getDeclName(),
7744 S.PDiag(diag::note_ovl_candidate)
7745 << (unsigned) oc_function_template,
7746 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007747
Douglas Gregorb491ed32011-02-19 21:32:49 +00007748 if (Result != MatchesCopy.end()) {
7749 // Make it the first and only element
7750 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7751 Matches[0].second = cast<FunctionDecl>(*Result);
7752 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00007753 }
7754 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007755
Douglas Gregorb491ed32011-02-19 21:32:49 +00007756 void EliminateAllTemplateMatches() {
7757 // [...] any function template specializations in the set are
7758 // eliminated if the set also contains a non-template function, [...]
7759 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7760 if (Matches[I].second->getPrimaryTemplate() == 0)
7761 ++I;
7762 else {
7763 Matches[I] = Matches[--N];
7764 Matches.set_size(N);
7765 }
7766 }
7767 }
7768
7769public:
7770 void ComplainNoMatchesFound() const {
7771 assert(Matches.empty());
7772 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7773 << OvlExpr->getName() << TargetFunctionType
7774 << OvlExpr->getSourceRange();
7775 S.NoteAllOverloadCandidates(OvlExpr);
7776 }
7777
7778 bool IsInvalidFormOfPointerToMemberFunction() const {
7779 return TargetTypeIsNonStaticMemberFunction &&
7780 !OvlExprInfo.HasFormOfMemberPointer;
7781 }
7782
7783 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7784 // TODO: Should we condition this on whether any functions might
7785 // have matched, or is it more appropriate to do that in callers?
7786 // TODO: a fixit wouldn't hurt.
7787 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7788 << TargetType << OvlExpr->getSourceRange();
7789 }
7790
7791 void ComplainOfInvalidConversion() const {
7792 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7793 << OvlExpr->getName() << TargetType;
7794 }
7795
7796 void ComplainMultipleMatchesFound() const {
7797 assert(Matches.size() > 1);
7798 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7799 << OvlExpr->getName()
7800 << OvlExpr->getSourceRange();
7801 S.NoteAllOverloadCandidates(OvlExpr);
7802 }
7803
7804 int getNumMatches() const { return Matches.size(); }
7805
7806 FunctionDecl* getMatchingFunctionDecl() const {
7807 if (Matches.size() != 1) return 0;
7808 return Matches[0].second;
7809 }
7810
7811 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7812 if (Matches.size() != 1) return 0;
7813 return &Matches[0].first;
7814 }
7815};
7816
7817/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7818/// an overloaded function (C++ [over.over]), where @p From is an
7819/// expression with overloaded function type and @p ToType is the type
7820/// we're trying to resolve to. For example:
7821///
7822/// @code
7823/// int f(double);
7824/// int f(int);
7825///
7826/// int (*pfd)(double) = f; // selects f(double)
7827/// @endcode
7828///
7829/// This routine returns the resulting FunctionDecl if it could be
7830/// resolved, and NULL otherwise. When @p Complain is true, this
7831/// routine will emit diagnostics if there is an error.
7832FunctionDecl *
7833Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7834 bool Complain,
7835 DeclAccessPair &FoundResult) {
7836
7837 assert(AddressOfExpr->getType() == Context.OverloadTy);
7838
7839 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
7840 int NumMatches = Resolver.getNumMatches();
7841 FunctionDecl* Fn = 0;
7842 if ( NumMatches == 0 && Complain) {
7843 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
7844 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
7845 else
7846 Resolver.ComplainNoMatchesFound();
7847 }
7848 else if (NumMatches > 1 && Complain)
7849 Resolver.ComplainMultipleMatchesFound();
7850 else if (NumMatches == 1) {
7851 Fn = Resolver.getMatchingFunctionDecl();
7852 assert(Fn);
7853 FoundResult = *Resolver.getMatchingFunctionAccessPair();
7854 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007855 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00007856 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00007857 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007858
7859 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007860}
7861
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007862/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007863/// resolve that overloaded function expression down to a single function.
7864///
7865/// This routine can only resolve template-ids that refer to a single function
7866/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007867/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007868/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00007869FunctionDecl *
7870Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
7871 bool Complain,
7872 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007873 // C++ [over.over]p1:
7874 // [...] [Note: any redundant set of parentheses surrounding the
7875 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007876 // C++ [over.over]p1:
7877 // [...] The overloaded function name can be preceded by the &
7878 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007879
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007880 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00007881 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007882 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007883
7884 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00007885 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007886
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007887 // Look through all of the overloaded functions, searching for one
7888 // whose type matches exactly.
7889 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00007890 for (UnresolvedSetIterator I = ovl->decls_begin(),
7891 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007892 // C++0x [temp.arg.explicit]p3:
7893 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007894 // where deduction is not done, if a template argument list is
7895 // specified and it, along with any default template arguments,
7896 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007897 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00007898 FunctionTemplateDecl *FunctionTemplate
7899 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007900
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007901 // C++ [over.over]p2:
7902 // If the name is a function template, template argument deduction is
7903 // done (14.8.2.2), and if the argument deduction succeeds, the
7904 // resulting template argument list is used to generate a single
7905 // function template specialization, which is added to the set of
7906 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007907 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00007908 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007909 if (TemplateDeductionResult Result
7910 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7911 Specialization, Info)) {
7912 // FIXME: make a note of the failed deduction for diagnostics.
7913 (void)Result;
7914 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007915 }
7916
John McCall0009fcc2011-04-26 20:42:42 +00007917 assert(Specialization && "no specialization and no error?");
7918
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007919 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007920 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007921 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00007922 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
7923 << ovl->getName();
7924 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007925 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007926 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00007927 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007928
John McCall0009fcc2011-04-26 20:42:42 +00007929 Matched = Specialization;
7930 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007931 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007932
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007933 return Matched;
7934}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007935
Douglas Gregor1beec452011-03-12 01:48:56 +00007936
7937
7938
7939// Resolve and fix an overloaded expression that
7940// can be resolved because it identifies a single function
7941// template specialization
7942// Last three arguments should only be supplied if Complain = true
7943ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
John McCall0009fcc2011-04-26 20:42:42 +00007944 Expr *SrcExpr, bool doFunctionPointerConverion, bool complain,
Douglas Gregor1beec452011-03-12 01:48:56 +00007945 const SourceRange& OpRangeForComplaining,
7946 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00007947 unsigned DiagIDForComplaining) {
7948 assert(SrcExpr->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00007949
John McCall0009fcc2011-04-26 20:42:42 +00007950 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr);
Douglas Gregor1beec452011-03-12 01:48:56 +00007951
John McCall0009fcc2011-04-26 20:42:42 +00007952 DeclAccessPair found;
7953 ExprResult SingleFunctionExpression;
7954 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
7955 ovl.Expression, /*complain*/ false, &found)) {
7956 if (DiagnoseUseOfDecl(fn, SrcExpr->getSourceRange().getBegin()))
7957 return ExprError();
7958
7959 // It is only correct to resolve to an instance method if we're
7960 // resolving a form that's permitted to be a pointer to member.
7961 // Otherwise we'll end up making a bound member expression, which
7962 // is illegal in all the contexts we resolve like this.
7963 if (!ovl.HasFormOfMemberPointer &&
7964 isa<CXXMethodDecl>(fn) &&
7965 cast<CXXMethodDecl>(fn)->isInstance()) {
7966 if (complain) {
7967 Diag(ovl.Expression->getExprLoc(),
7968 diag::err_invalid_use_of_bound_member_func)
7969 << ovl.Expression->getSourceRange();
7970 // TODO: I believe we only end up here if there's a mix of
7971 // static and non-static candidates (otherwise the expression
7972 // would have 'bound member' type, not 'overload' type).
7973 // Ideally we would note which candidate was chosen and why
7974 // the static candidates were rejected.
7975 }
7976
Douglas Gregor89f3cd52011-03-16 19:16:25 +00007977 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00007978 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00007979
John McCall0009fcc2011-04-26 20:42:42 +00007980 // Fix the expresion to refer to 'fn'.
7981 SingleFunctionExpression =
7982 Owned(FixOverloadedFunctionReference(SrcExpr, found, fn));
7983
7984 // If desired, do function-to-pointer decay.
7985 if (doFunctionPointerConverion)
7986 SingleFunctionExpression =
7987 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
7988 }
7989
7990 if (!SingleFunctionExpression.isUsable()) {
7991 if (complain) {
7992 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
7993 << ovl.Expression->getName()
7994 << DestTypeForComplaining
7995 << OpRangeForComplaining
7996 << ovl.Expression->getQualifierLoc().getSourceRange();
7997 NoteAllOverloadCandidates(SrcExpr);
7998 }
7999 return ExprError();
8000 }
8001
8002 return SingleFunctionExpression;
Douglas Gregor1beec452011-03-12 01:48:56 +00008003}
8004
Douglas Gregorcabea402009-09-22 15:41:20 +00008005/// \brief Add a single candidate to the overload set.
8006static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00008007 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008008 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008009 Expr **Args, unsigned NumArgs,
8010 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008011 bool PartialOverloading,
8012 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00008013 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00008014 if (isa<UsingShadowDecl>(Callee))
8015 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8016
Douglas Gregorcabea402009-09-22 15:41:20 +00008017 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00008018 if (ExplicitTemplateArgs) {
8019 assert(!KnownValid && "Explicit template arguments?");
8020 return;
8021 }
John McCalla0296f72010-03-19 07:35:19 +00008022 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00008023 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008024 return;
John McCalld14a8642009-11-21 08:51:07 +00008025 }
8026
8027 if (FunctionTemplateDecl *FuncTemplate
8028 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00008029 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8030 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00008031 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00008032 return;
8033 }
8034
Richard Smith95ce4f62011-06-26 22:19:54 +00008035 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00008036}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008037
Douglas Gregorcabea402009-09-22 15:41:20 +00008038/// \brief Add the overload candidates named by callee and/or found by argument
8039/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00008040void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00008041 Expr **Args, unsigned NumArgs,
8042 OverloadCandidateSet &CandidateSet,
8043 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00008044
8045#ifndef NDEBUG
8046 // Verify that ArgumentDependentLookup is consistent with the rules
8047 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00008048 //
Douglas Gregorcabea402009-09-22 15:41:20 +00008049 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8050 // and let Y be the lookup set produced by argument dependent
8051 // lookup (defined as follows). If X contains
8052 //
8053 // -- a declaration of a class member, or
8054 //
8055 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00008056 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00008057 //
8058 // -- a declaration that is neither a function or a function
8059 // template
8060 //
8061 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00008062
John McCall57500772009-12-16 12:17:52 +00008063 if (ULE->requiresADL()) {
8064 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8065 E = ULE->decls_end(); I != E; ++I) {
8066 assert(!(*I)->getDeclContext()->isRecord());
8067 assert(isa<UsingShadowDecl>(*I) ||
8068 !(*I)->getDeclContext()->isFunctionOrMethod());
8069 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008070 }
8071 }
8072#endif
8073
John McCall57500772009-12-16 12:17:52 +00008074 // It would be nice to avoid this copy.
8075 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008076 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008077 if (ULE->hasExplicitTemplateArgs()) {
8078 ULE->copyTemplateArgumentsInto(TABuffer);
8079 ExplicitTemplateArgs = &TABuffer;
8080 }
8081
8082 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8083 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008084 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008085 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008086 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008087
John McCall57500772009-12-16 12:17:52 +00008088 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008089 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8090 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008091 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008092 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008093 PartialOverloading,
8094 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008095}
John McCalld681c392009-12-16 08:11:27 +00008096
Richard Smith998a5912011-06-05 22:42:48 +00008097/// Attempt to recover from an ill-formed use of a non-dependent name in a
8098/// template, where the non-dependent name was declared after the template
8099/// was defined. This is common in code written for a compilers which do not
8100/// correctly implement two-stage name lookup.
8101///
8102/// Returns true if a viable candidate was found and a diagnostic was issued.
8103static bool
8104DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8105 const CXXScopeSpec &SS, LookupResult &R,
8106 TemplateArgumentListInfo *ExplicitTemplateArgs,
8107 Expr **Args, unsigned NumArgs) {
8108 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8109 return false;
8110
8111 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8112 SemaRef.LookupQualifiedName(R, DC);
8113
8114 if (!R.empty()) {
8115 R.suppressDiagnostics();
8116
8117 if (isa<CXXRecordDecl>(DC)) {
8118 // Don't diagnose names we find in classes; we get much better
8119 // diagnostics for these from DiagnoseEmptyLookup.
8120 R.clear();
8121 return false;
8122 }
8123
8124 OverloadCandidateSet Candidates(FnLoc);
8125 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8126 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8127 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008128 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008129
8130 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008131 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008132 // No viable functions. Don't bother the user with notes for functions
8133 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008134 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008135 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008136 }
Richard Smith998a5912011-06-05 22:42:48 +00008137
8138 // Find the namespaces where ADL would have looked, and suggest
8139 // declaring the function there instead.
8140 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8141 Sema::AssociatedClassSet AssociatedClasses;
8142 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8143 AssociatedNamespaces,
8144 AssociatedClasses);
8145 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008146 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008147 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008148 for (Sema::AssociatedNamespaceSet::iterator
8149 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008150 end = AssociatedNamespaces.end(); it != end; ++it) {
8151 if (!Std->Encloses(*it))
8152 SuggestedNamespaces.insert(*it);
8153 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008154 } else {
8155 // Lacking the 'std::' namespace, use all of the associated namespaces.
8156 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008157 }
8158
8159 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8160 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008161 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008162 SemaRef.Diag(Best->Function->getLocation(),
8163 diag::note_not_found_by_two_phase_lookup)
8164 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008165 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008166 SemaRef.Diag(Best->Function->getLocation(),
8167 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008168 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008169 } else {
8170 // FIXME: It would be useful to list the associated namespaces here,
8171 // but the diagnostics infrastructure doesn't provide a way to produce
8172 // a localized representation of a list of items.
8173 SemaRef.Diag(Best->Function->getLocation(),
8174 diag::note_not_found_by_two_phase_lookup)
8175 << R.getLookupName() << 2;
8176 }
8177
8178 // Try to recover by calling this function.
8179 return true;
8180 }
8181
8182 R.clear();
8183 }
8184
8185 return false;
8186}
8187
8188/// Attempt to recover from ill-formed use of a non-dependent operator in a
8189/// template, where the non-dependent operator was declared after the template
8190/// was defined.
8191///
8192/// Returns true if a viable candidate was found and a diagnostic was issued.
8193static bool
8194DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8195 SourceLocation OpLoc,
8196 Expr **Args, unsigned NumArgs) {
8197 DeclarationName OpName =
8198 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8199 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8200 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8201 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8202}
8203
John McCalld681c392009-12-16 08:11:27 +00008204/// Attempts to recover from a call where no functions were found.
8205///
8206/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008207static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008208BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008209 UnresolvedLookupExpr *ULE,
8210 SourceLocation LParenLoc,
8211 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008212 SourceLocation RParenLoc,
8213 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008214
8215 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008216 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008217
John McCall57500772009-12-16 12:17:52 +00008218 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008219 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008220 if (ULE->hasExplicitTemplateArgs()) {
8221 ULE->copyTemplateArgumentsInto(TABuffer);
8222 ExplicitTemplateArgs = &TABuffer;
8223 }
8224
John McCalld681c392009-12-16 08:11:27 +00008225 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8226 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008227 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8228 ExplicitTemplateArgs, Args, NumArgs) &&
8229 (!EmptyLookup ||
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00008230 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00008231 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00008232 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008233
John McCall57500772009-12-16 12:17:52 +00008234 assert(!R.empty() && "lookup results empty despite recovery");
8235
8236 // Build an implicit member call if appropriate. Just drop the
8237 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008238 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008239 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008240 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8241 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008242 else if (ExplicitTemplateArgs)
8243 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8244 else
8245 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8246
8247 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008248 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008249
8250 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008251 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008252 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008253 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008254 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008255}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008256
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008257/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008258/// (which eventually refers to the declaration Func) and the call
8259/// arguments Args/NumArgs, attempt to resolve the function call down
8260/// to a specific function. If overload resolution succeeds, returns
8261/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008262/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008263/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008264ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008265Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008266 SourceLocation LParenLoc,
8267 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008268 SourceLocation RParenLoc,
8269 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008270#ifndef NDEBUG
8271 if (ULE->requiresADL()) {
8272 // To do ADL, we must have found an unqualified name.
8273 assert(!ULE->getQualifier() && "qualified name with ADL");
8274
8275 // We don't perform ADL for implicit declarations of builtins.
8276 // Verify that this was correctly set up.
8277 FunctionDecl *F;
8278 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8279 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8280 F->getBuiltinID() && F->isImplicit())
8281 assert(0 && "performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008282
John McCall57500772009-12-16 12:17:52 +00008283 // We don't perform ADL in C.
8284 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008285 } else
8286 assert(!ULE->isStdAssociatedNamespace() &&
8287 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008288#endif
8289
John McCallbc077cf2010-02-08 23:07:23 +00008290 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008291
John McCall57500772009-12-16 12:17:52 +00008292 // Add the functions denoted by the callee to the set of candidate
8293 // functions, including those from argument-dependent lookup.
8294 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008295
8296 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008297 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8298 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00008299 if (CandidateSet.empty()) {
8300 // In Microsoft mode, if we are inside a template class member function then
8301 // create a type dependent CallExpr. The goal is to postpone name lookup
8302 // to instantiation time to be able to search into type dependent base
8303 // classes.
8304 if (getLangOptions().Microsoft && CurContext->isDependentContext() &&
8305 isa<CXXMethodDecl>(CurContext)) {
8306 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8307 Context.DependentTy, VK_RValue,
8308 RParenLoc);
8309 CE->setTypeDependent(true);
8310 return Owned(CE);
8311 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008312 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008313 RParenLoc, /*EmptyLookup=*/true);
Francois Pichetbcf64712011-09-07 00:14:57 +00008314 }
John McCalld681c392009-12-16 08:11:27 +00008315
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008316 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008317 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008318 case OR_Success: {
8319 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008320 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008321 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008322 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
8323 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008324 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008325 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8326 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008327 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008328
Richard Smith998a5912011-06-05 22:42:48 +00008329 case OR_No_Viable_Function: {
8330 // Try to recover by looking for viable functions which the user might
8331 // have meant to call.
8332 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8333 Args, NumArgs, RParenLoc,
8334 /*EmptyLookup=*/false);
8335 if (!Recovery.isInvalid())
8336 return Recovery;
8337
Chris Lattner45d9d602009-02-17 07:29:20 +00008338 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008339 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008340 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008341 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008342 break;
Richard Smith998a5912011-06-05 22:42:48 +00008343 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008344
8345 case OR_Ambiguous:
8346 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008347 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008348 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008349 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008350
8351 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008352 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008353 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8354 << Best->Function->isDeleted()
8355 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008356 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008357 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008358 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8359 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008360 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008361 }
8362
Douglas Gregorb412e172010-07-25 18:17:45 +00008363 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00008364 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008365}
8366
John McCall4c4c1df2010-01-26 03:27:55 +00008367static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00008368 return Functions.size() > 1 ||
8369 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8370}
8371
Douglas Gregor084d8552009-03-13 23:49:33 +00008372/// \brief Create a unary operation that may resolve to an overloaded
8373/// operator.
8374///
8375/// \param OpLoc The location of the operator itself (e.g., '*').
8376///
8377/// \param OpcIn The UnaryOperator::Opcode that describes this
8378/// operator.
8379///
8380/// \param Functions The set of non-member functions that will be
8381/// considered by overload resolution. The caller needs to build this
8382/// set based on the context using, e.g.,
8383/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8384/// set should not contain any member functions; those will be added
8385/// by CreateOverloadedUnaryOp().
8386///
8387/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00008388ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00008389Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8390 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00008391 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008392 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00008393
8394 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8395 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8396 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008397 // TODO: provide better source location info.
8398 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008399
John Wiegley01296292011-04-08 18:41:53 +00008400 if (Input->getObjectKind() == OK_ObjCProperty) {
8401 ExprResult Result = ConvertPropertyForRValue(Input);
8402 if (Result.isInvalid())
8403 return ExprError();
8404 Input = Result.take();
8405 }
John McCalle26a8722010-12-04 08:14:53 +00008406
Douglas Gregor084d8552009-03-13 23:49:33 +00008407 Expr *Args[2] = { Input, 0 };
8408 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00008409
Douglas Gregor084d8552009-03-13 23:49:33 +00008410 // For post-increment and post-decrement, add the implicit '0' as
8411 // the second argument, so that we know this is a post-increment or
8412 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00008413 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008414 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008415 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8416 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00008417 NumArgs = 2;
8418 }
8419
8420 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00008421 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00008422 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008423 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00008424 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008425 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00008426 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008427
John McCall58cc69d2010-01-27 01:50:18 +00008428 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00008429 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008430 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008431 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008432 /*ADL*/ true, IsOverloaded(Fns),
8433 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00008434 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008435 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00008436 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008437 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00008438 OpLoc));
8439 }
8440
8441 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008442 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008443
8444 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008445 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00008446
8447 // Add operator candidates that are member functions.
8448 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8449
John McCall4c4c1df2010-01-26 03:27:55 +00008450 // Add candidates from ADL.
8451 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00008452 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00008453 /*ExplicitTemplateArgs*/ 0,
8454 CandidateSet);
8455
Douglas Gregor084d8552009-03-13 23:49:33 +00008456 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008457 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00008458
8459 // Perform overload resolution.
8460 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008461 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008462 case OR_Success: {
8463 // We found a built-in operator or an overloaded operator.
8464 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00008465
Douglas Gregor084d8552009-03-13 23:49:33 +00008466 if (FnDecl) {
8467 // We matched an overloaded operator. Build a call to that
8468 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00008469
Chandler Carruth30141632011-02-25 19:41:05 +00008470 MarkDeclarationReferenced(OpLoc, FnDecl);
8471
Douglas Gregor084d8552009-03-13 23:49:33 +00008472 // Convert the arguments.
8473 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00008474 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008475
John Wiegley01296292011-04-08 18:41:53 +00008476 ExprResult InputRes =
8477 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8478 Best->FoundDecl, Method);
8479 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008480 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008481 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008482 } else {
8483 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008484 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00008485 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008486 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00008487 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008488 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00008489 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00008490 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008491 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008492 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008493 }
8494
John McCall4fa0d5f2010-05-06 18:15:07 +00008495 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8496
John McCall7decc9e2010-11-18 06:31:45 +00008497 // Determine the result type.
8498 QualType ResultTy = FnDecl->getResultType();
8499 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8500 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00008501
Douglas Gregor084d8552009-03-13 23:49:33 +00008502 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008503 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl);
8504 if (FnExpr.isInvalid())
8505 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00008506
Eli Friedman030eee42009-11-18 03:58:17 +00008507 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00008508 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008509 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008510 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00008511
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008512 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00008513 FnDecl))
8514 return ExprError();
8515
John McCallb268a282010-08-23 23:25:46 +00008516 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00008517 } else {
8518 // We matched a built-in operator. Convert the arguments, then
8519 // break out so that we will build the appropriate built-in
8520 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008521 ExprResult InputRes =
8522 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8523 Best->Conversions[0], AA_Passing);
8524 if (InputRes.isInvalid())
8525 return ExprError();
8526 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008527 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00008528 }
John Wiegley01296292011-04-08 18:41:53 +00008529 }
8530
8531 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00008532 // This is an erroneous use of an operator which can be overloaded by
8533 // a non-member function. Check for non-member operators which were
8534 // defined too late to be candidates.
8535 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8536 // FIXME: Recover by calling the found function.
8537 return ExprError();
8538
John Wiegley01296292011-04-08 18:41:53 +00008539 // No viable function; fall through to handling this as a
8540 // built-in operator, which will produce an error message for us.
8541 break;
8542
8543 case OR_Ambiguous:
8544 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8545 << UnaryOperator::getOpcodeStr(Opc)
8546 << Input->getType()
8547 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008548 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00008549 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8550 return ExprError();
8551
8552 case OR_Deleted:
8553 Diag(OpLoc, diag::err_ovl_deleted_oper)
8554 << Best->Function->isDeleted()
8555 << UnaryOperator::getOpcodeStr(Opc)
8556 << getDeletedOrUnavailableSuffix(Best->Function)
8557 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008558 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
8559 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00008560 return ExprError();
8561 }
Douglas Gregor084d8552009-03-13 23:49:33 +00008562
8563 // Either we found no viable overloaded operator or we matched a
8564 // built-in operator. In either case, fall through to trying to
8565 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00008566 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008567}
8568
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008569/// \brief Create a binary operation that may resolve to an overloaded
8570/// operator.
8571///
8572/// \param OpLoc The location of the operator itself (e.g., '+').
8573///
8574/// \param OpcIn The BinaryOperator::Opcode that describes this
8575/// operator.
8576///
8577/// \param Functions The set of non-member functions that will be
8578/// considered by overload resolution. The caller needs to build this
8579/// set based on the context using, e.g.,
8580/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8581/// set should not contain any member functions; those will be added
8582/// by CreateOverloadedBinOp().
8583///
8584/// \param LHS Left-hand argument.
8585/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00008586ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008587Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008588 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00008589 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008590 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008591 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00008592 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008593
8594 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8595 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8596 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8597
8598 // If either side is type-dependent, create an appropriate dependent
8599 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00008600 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00008601 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008602 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00008603 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00008604 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00008605 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00008606 Context.DependentTy,
8607 VK_RValue, OK_Ordinary,
8608 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008609
Douglas Gregor5287f092009-11-05 00:51:44 +00008610 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8611 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008612 VK_LValue,
8613 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00008614 Context.DependentTy,
8615 Context.DependentTy,
8616 OpLoc));
8617 }
John McCall4c4c1df2010-01-26 03:27:55 +00008618
8619 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00008620 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008621 // TODO: provide better source location info in DNLoc component.
8622 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00008623 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00008624 = UnresolvedLookupExpr::Create(Context, NamingClass,
8625 NestedNameSpecifierLoc(), OpNameInfo,
8626 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008627 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008628 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00008629 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008630 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008631 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008632 OpLoc));
8633 }
8634
John McCalle26a8722010-12-04 08:14:53 +00008635 // Always do property rvalue conversions on the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008636 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8637 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8638 if (Result.isInvalid())
8639 return ExprError();
8640 Args[1] = Result.take();
8641 }
John McCalle26a8722010-12-04 08:14:53 +00008642
8643 // The LHS is more complicated.
8644 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8645
8646 // There's a tension for assignment operators between primitive
8647 // property assignment and the overloaded operators.
8648 if (BinaryOperator::isAssignmentOp(Opc)) {
8649 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8650
8651 // Is the property "logically" settable?
8652 bool Settable = (PRE->isExplicitProperty() ||
8653 PRE->getImplicitPropertySetter());
8654
8655 // To avoid gratuitously inventing semantics, use the primitive
8656 // unless it isn't. Thoughts in case we ever really care:
8657 // - If the property isn't logically settable, we have to
8658 // load and hope.
8659 // - If the property is settable and this is simple assignment,
8660 // we really should use the primitive.
8661 // - If the property is settable, then we could try overloading
8662 // on a generic lvalue of the appropriate type; if it works
8663 // out to a builtin candidate, we would do that same operation
8664 // on the property, and otherwise just error.
8665 if (Settable)
8666 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8667 }
8668
John Wiegley01296292011-04-08 18:41:53 +00008669 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8670 if (Result.isInvalid())
8671 return ExprError();
8672 Args[0] = Result.take();
John McCalle26a8722010-12-04 08:14:53 +00008673 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008674
Sebastian Redl6a96bf72009-11-18 23:10:33 +00008675 // If this is the assignment operator, we only perform overload resolution
8676 // if the left-hand side is a class or enumeration type. This is actually
8677 // a hack. The standard requires that we do overload resolution between the
8678 // various built-in candidates, but as DR507 points out, this can lead to
8679 // problems. So we do it this way, which pretty much follows what GCC does.
8680 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00008681 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00008682 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008683
John McCalle26a8722010-12-04 08:14:53 +00008684 // If this is the .* operator, which is not overloadable, just
8685 // create a built-in binary operator.
8686 if (Opc == BO_PtrMemD)
8687 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8688
Douglas Gregor084d8552009-03-13 23:49:33 +00008689 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008690 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008691
8692 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008693 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008694
8695 // Add operator candidates that are member functions.
8696 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8697
John McCall4c4c1df2010-01-26 03:27:55 +00008698 // Add candidates from ADL.
8699 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8700 Args, 2,
8701 /*ExplicitTemplateArgs*/ 0,
8702 CandidateSet);
8703
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008704 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008705 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008706
8707 // Perform overload resolution.
8708 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008709 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00008710 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008711 // We found a built-in operator or an overloaded operator.
8712 FunctionDecl *FnDecl = Best->Function;
8713
8714 if (FnDecl) {
8715 // We matched an overloaded operator. Build a call to that
8716 // operator.
8717
Chandler Carruth30141632011-02-25 19:41:05 +00008718 MarkDeclarationReferenced(OpLoc, FnDecl);
8719
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008720 // Convert the arguments.
8721 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00008722 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00008723 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008724
Chandler Carruth8e543b32010-12-12 08:17:55 +00008725 ExprResult Arg1 =
8726 PerformCopyInitialization(
8727 InitializedEntity::InitializeParameter(Context,
8728 FnDecl->getParamDecl(0)),
8729 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008730 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008731 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008732
John Wiegley01296292011-04-08 18:41:53 +00008733 ExprResult Arg0 =
8734 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8735 Best->FoundDecl, Method);
8736 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008737 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008738 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008739 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008740 } else {
8741 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00008742 ExprResult Arg0 = PerformCopyInitialization(
8743 InitializedEntity::InitializeParameter(Context,
8744 FnDecl->getParamDecl(0)),
8745 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008746 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008747 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008748
Chandler Carruth8e543b32010-12-12 08:17:55 +00008749 ExprResult Arg1 =
8750 PerformCopyInitialization(
8751 InitializedEntity::InitializeParameter(Context,
8752 FnDecl->getParamDecl(1)),
8753 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008754 if (Arg1.isInvalid())
8755 return ExprError();
8756 Args[0] = LHS = Arg0.takeAs<Expr>();
8757 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008758 }
8759
John McCall4fa0d5f2010-05-06 18:15:07 +00008760 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8761
John McCall7decc9e2010-11-18 06:31:45 +00008762 // Determine the result type.
8763 QualType ResultTy = FnDecl->getResultType();
8764 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8765 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008766
8767 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008768 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
8769 if (FnExpr.isInvalid())
8770 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008771
John McCallb268a282010-08-23 23:25:46 +00008772 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008773 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008774 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008775
8776 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008777 FnDecl))
8778 return ExprError();
8779
John McCallb268a282010-08-23 23:25:46 +00008780 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008781 } else {
8782 // We matched a built-in operator. Convert the arguments, then
8783 // break out so that we will build the appropriate built-in
8784 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008785 ExprResult ArgsRes0 =
8786 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8787 Best->Conversions[0], AA_Passing);
8788 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008789 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008790 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008791
John Wiegley01296292011-04-08 18:41:53 +00008792 ExprResult ArgsRes1 =
8793 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8794 Best->Conversions[1], AA_Passing);
8795 if (ArgsRes1.isInvalid())
8796 return ExprError();
8797 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008798 break;
8799 }
8800 }
8801
Douglas Gregor66950a32009-09-30 21:46:01 +00008802 case OR_No_Viable_Function: {
8803 // C++ [over.match.oper]p9:
8804 // If the operator is the operator , [...] and there are no
8805 // viable functions, then the operator is assumed to be the
8806 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00008807 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00008808 break;
8809
Chandler Carruth8e543b32010-12-12 08:17:55 +00008810 // For class as left operand for assignment or compound assigment
8811 // operator do not fall through to handling in built-in, but report that
8812 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00008813 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008814 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00008815 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00008816 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8817 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00008818 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00008819 } else {
Richard Smith998a5912011-06-05 22:42:48 +00008820 // This is an erroneous use of an operator which can be overloaded by
8821 // a non-member function. Check for non-member operators which were
8822 // defined too late to be candidates.
8823 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
8824 // FIXME: Recover by calling the found function.
8825 return ExprError();
8826
Douglas Gregor66950a32009-09-30 21:46:01 +00008827 // No viable function; try to create a built-in operation, which will
8828 // produce an error. Then, show the non-viable candidates.
8829 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00008830 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008831 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00008832 "C++ binary operator overloading is missing candidates!");
8833 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00008834 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8835 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00008836 return move(Result);
8837 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008838
8839 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008840 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008841 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00008842 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00008843 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008844 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
8845 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008846 return ExprError();
8847
8848 case OR_Deleted:
8849 Diag(OpLoc, diag::err_ovl_deleted_oper)
8850 << Best->Function->isDeleted()
8851 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008852 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00008853 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008854 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
8855 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008856 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00008857 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008858
Douglas Gregor66950a32009-09-30 21:46:01 +00008859 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00008860 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008861}
8862
John McCalldadc5752010-08-24 06:29:42 +00008863ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00008864Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
8865 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00008866 Expr *Base, Expr *Idx) {
8867 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00008868 DeclarationName OpName =
8869 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
8870
8871 // If either side is type-dependent, create an appropriate dependent
8872 // expression.
8873 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
8874
John McCall58cc69d2010-01-27 01:50:18 +00008875 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008876 // CHECKME: no 'operator' keyword?
8877 DeclarationNameInfo OpNameInfo(OpName, LLoc);
8878 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00008879 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008880 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008881 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008882 /*ADL*/ true, /*Overloaded*/ false,
8883 UnresolvedSetIterator(),
8884 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00008885 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00008886
Sebastian Redladba46e2009-10-29 20:17:01 +00008887 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
8888 Args, 2,
8889 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008890 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00008891 RLoc));
8892 }
8893
John Wiegley01296292011-04-08 18:41:53 +00008894 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8895 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8896 if (Result.isInvalid())
8897 return ExprError();
8898 Args[0] = Result.take();
8899 }
8900 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8901 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8902 if (Result.isInvalid())
8903 return ExprError();
8904 Args[1] = Result.take();
8905 }
John McCalle26a8722010-12-04 08:14:53 +00008906
Sebastian Redladba46e2009-10-29 20:17:01 +00008907 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008908 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008909
8910 // Subscript can only be overloaded as a member function.
8911
8912 // Add operator candidates that are member functions.
8913 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8914
8915 // Add builtin operator candidates.
8916 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
8917
8918 // Perform overload resolution.
8919 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008920 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00008921 case OR_Success: {
8922 // We found a built-in operator or an overloaded operator.
8923 FunctionDecl *FnDecl = Best->Function;
8924
8925 if (FnDecl) {
8926 // We matched an overloaded operator. Build a call to that
8927 // operator.
8928
Chandler Carruth30141632011-02-25 19:41:05 +00008929 MarkDeclarationReferenced(LLoc, FnDecl);
8930
John McCalla0296f72010-03-19 07:35:19 +00008931 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008932 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00008933
Sebastian Redladba46e2009-10-29 20:17:01 +00008934 // Convert the arguments.
8935 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00008936 ExprResult Arg0 =
8937 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8938 Best->FoundDecl, Method);
8939 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00008940 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008941 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00008942
Anders Carlssona68e51e2010-01-29 18:37:50 +00008943 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008944 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00008945 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008946 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00008947 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008948 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00008949 Owned(Args[1]));
8950 if (InputInit.isInvalid())
8951 return ExprError();
8952
8953 Args[1] = InputInit.takeAs<Expr>();
8954
Sebastian Redladba46e2009-10-29 20:17:01 +00008955 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00008956 QualType ResultTy = FnDecl->getResultType();
8957 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8958 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00008959
8960 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00008961 DeclarationNameLoc LocInfo;
8962 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
8963 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
8964 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00008965 if (FnExpr.isInvalid())
8966 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00008967
John McCallb268a282010-08-23 23:25:46 +00008968 CXXOperatorCallExpr *TheCall =
8969 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00008970 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00008971 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00008972
John McCallb268a282010-08-23 23:25:46 +00008973 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00008974 FnDecl))
8975 return ExprError();
8976
John McCallb268a282010-08-23 23:25:46 +00008977 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00008978 } else {
8979 // We matched a built-in operator. Convert the arguments, then
8980 // break out so that we will build the appropriate built-in
8981 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008982 ExprResult ArgsRes0 =
8983 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8984 Best->Conversions[0], AA_Passing);
8985 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00008986 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008987 Args[0] = ArgsRes0.take();
8988
8989 ExprResult ArgsRes1 =
8990 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8991 Best->Conversions[1], AA_Passing);
8992 if (ArgsRes1.isInvalid())
8993 return ExprError();
8994 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00008995
8996 break;
8997 }
8998 }
8999
9000 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00009001 if (CandidateSet.empty())
9002 Diag(LLoc, diag::err_ovl_no_oper)
9003 << Args[0]->getType() << /*subscript*/ 0
9004 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9005 else
9006 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9007 << Args[0]->getType()
9008 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009009 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9010 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00009011 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009012 }
9013
9014 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009015 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009016 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00009017 << Args[0]->getType() << Args[1]->getType()
9018 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009019 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9020 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009021 return ExprError();
9022
9023 case OR_Deleted:
9024 Diag(LLoc, diag::err_ovl_deleted_oper)
9025 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009026 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00009027 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009028 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9029 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009030 return ExprError();
9031 }
9032
9033 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00009034 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009035}
9036
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009037/// BuildCallToMemberFunction - Build a call to a member
9038/// function. MemExpr is the expression that refers to the member
9039/// function (and includes the object parameter), Args/NumArgs are the
9040/// arguments to the function call (not including the object
9041/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00009042/// expression refers to a non-static member function or an overloaded
9043/// member function.
John McCalldadc5752010-08-24 06:29:42 +00009044ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00009045Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9046 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009047 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00009048 assert(MemExprE->getType() == Context.BoundMemberTy ||
9049 MemExprE->getType() == Context.OverloadTy);
9050
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009051 // Dig out the member expression. This holds both the object
9052 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00009053 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009054
John McCall0009fcc2011-04-26 20:42:42 +00009055 // Determine whether this is a call to a pointer-to-member function.
9056 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9057 assert(op->getType() == Context.BoundMemberTy);
9058 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9059
9060 QualType fnType =
9061 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9062
9063 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9064 QualType resultType = proto->getCallResultType(Context);
9065 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9066
9067 // Check that the object type isn't more qualified than the
9068 // member function we're calling.
9069 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9070
9071 QualType objectType = op->getLHS()->getType();
9072 if (op->getOpcode() == BO_PtrMemI)
9073 objectType = objectType->castAs<PointerType>()->getPointeeType();
9074 Qualifiers objectQuals = objectType.getQualifiers();
9075
9076 Qualifiers difference = objectQuals - funcQuals;
9077 difference.removeObjCGCAttr();
9078 difference.removeAddressSpace();
9079 if (difference) {
9080 std::string qualsString = difference.getAsString();
9081 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9082 << fnType.getUnqualifiedType()
9083 << qualsString
9084 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9085 }
9086
9087 CXXMemberCallExpr *call
9088 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9089 resultType, valueKind, RParenLoc);
9090
9091 if (CheckCallReturnType(proto->getResultType(),
9092 op->getRHS()->getSourceRange().getBegin(),
9093 call, 0))
9094 return ExprError();
9095
9096 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9097 return ExprError();
9098
9099 return MaybeBindToTemporary(call);
9100 }
9101
John McCall10eae182009-11-30 22:42:35 +00009102 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009103 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009104 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009105 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009106 if (isa<MemberExpr>(NakedMemExpr)) {
9107 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009108 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009109 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009110 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00009111 } else {
9112 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009113 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009114
John McCall6e9f8f62009-12-03 04:06:58 +00009115 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009116 Expr::Classification ObjectClassification
9117 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9118 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009119
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009120 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009121 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009122
John McCall2d74de92009-12-01 22:10:20 +00009123 // FIXME: avoid copy.
9124 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9125 if (UnresExpr->hasExplicitTemplateArgs()) {
9126 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9127 TemplateArgs = &TemplateArgsBuffer;
9128 }
9129
John McCall10eae182009-11-30 22:42:35 +00009130 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9131 E = UnresExpr->decls_end(); I != E; ++I) {
9132
John McCall6e9f8f62009-12-03 04:06:58 +00009133 NamedDecl *Func = *I;
9134 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9135 if (isa<UsingShadowDecl>(Func))
9136 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9137
Douglas Gregor02824322011-01-26 19:30:28 +00009138
Francois Pichet64225792011-01-18 05:04:39 +00009139 // Microsoft supports direct constructor calls.
9140 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
9141 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9142 CandidateSet);
9143 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009144 // If explicit template arguments were provided, we can't call a
9145 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009146 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009147 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009148
John McCalla0296f72010-03-19 07:35:19 +00009149 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009150 ObjectClassification,
9151 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009152 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009153 } else {
John McCall10eae182009-11-30 22:42:35 +00009154 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009155 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009156 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009157 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009158 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009159 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009160 }
Mike Stump11289f42009-09-09 15:08:12 +00009161
John McCall10eae182009-11-30 22:42:35 +00009162 DeclarationName DeclName = UnresExpr->getMemberName();
9163
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009164 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009165 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009166 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009167 case OR_Success:
9168 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009169 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009170 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009171 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009172 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009173 break;
9174
9175 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009176 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009177 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009178 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009179 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009180 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009181 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009182
9183 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009184 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009185 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009186 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009187 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009188 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009189
9190 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009191 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009192 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009193 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009194 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009195 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009196 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009197 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009198 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009199 }
9200
John McCall16df1e52010-03-30 21:47:33 +00009201 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009202
John McCall2d74de92009-12-01 22:10:20 +00009203 // If overload resolution picked a static member, build a
9204 // non-member call based on that function.
9205 if (Method->isStatic()) {
9206 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9207 Args, NumArgs, RParenLoc);
9208 }
9209
John McCall10eae182009-11-30 22:42:35 +00009210 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009211 }
9212
John McCall7decc9e2010-11-18 06:31:45 +00009213 QualType ResultType = Method->getResultType();
9214 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9215 ResultType = ResultType.getNonLValueExprType(Context);
9216
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009217 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009218 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009219 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009220 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009221
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009222 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009223 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009224 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009225 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009226
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009227 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009228 // We only need to do this if there was actually an overload; otherwise
9229 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009230 if (!Method->isStatic()) {
9231 ExprResult ObjectArg =
9232 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9233 FoundDecl, Method);
9234 if (ObjectArg.isInvalid())
9235 return ExprError();
9236 MemExpr->setBase(ObjectArg.take());
9237 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009238
9239 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009240 const FunctionProtoType *Proto =
9241 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009242 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009243 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009244 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009245
John McCallb268a282010-08-23 23:25:46 +00009246 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009247 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009248
Anders Carlsson47061ee2011-05-06 14:25:31 +00009249 if ((isa<CXXConstructorDecl>(CurContext) ||
9250 isa<CXXDestructorDecl>(CurContext)) &&
9251 TheCall->getMethodDecl()->isPure()) {
9252 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9253
Chandler Carruth59259262011-06-27 08:31:58 +00009254 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009255 Diag(MemExpr->getLocStart(),
9256 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9257 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9258 << MD->getParent()->getDeclName();
9259
9260 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009261 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009262 }
John McCallb268a282010-08-23 23:25:46 +00009263 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009264}
9265
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009266/// BuildCallToObjectOfClassType - Build a call to an object of class
9267/// type (C++ [over.call.object]), which can end up invoking an
9268/// overloaded function call operator (@c operator()) or performing a
9269/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009270ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009271Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009272 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009273 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009274 SourceLocation RParenLoc) {
John Wiegley01296292011-04-08 18:41:53 +00009275 ExprResult Object = Owned(Obj);
9276 if (Object.get()->getObjectKind() == OK_ObjCProperty) {
9277 Object = ConvertPropertyForRValue(Object.take());
9278 if (Object.isInvalid())
9279 return ExprError();
9280 }
John McCalle26a8722010-12-04 08:14:53 +00009281
John Wiegley01296292011-04-08 18:41:53 +00009282 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9283 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009284
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009285 // C++ [over.call.object]p1:
9286 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009287 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009288 // candidate functions includes at least the function call
9289 // operators of T. The function call operators of T are obtained by
9290 // ordinary lookup of the name operator() in the context of
9291 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009292 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009293 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009294
John Wiegley01296292011-04-08 18:41:53 +00009295 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009296 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009297 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009298 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009299
John McCall27b18f82009-11-17 02:14:36 +00009300 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9301 LookupQualifiedName(R, Record->getDecl());
9302 R.suppressDiagnostics();
9303
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009304 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009305 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009306 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9307 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009308 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009309 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009310
Douglas Gregorab7897a2008-11-19 22:57:39 +00009311 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009312 // In addition, for each (non-explicit in C++0x) conversion function
9313 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +00009314 //
9315 // operator conversion-type-id () cv-qualifier;
9316 //
9317 // where cv-qualifier is the same cv-qualification as, or a
9318 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009319 // denotes the type "pointer to function of (P1,...,Pn) returning
9320 // R", or the type "reference to pointer to function of
9321 // (P1,...,Pn) returning R", or the type "reference to function
9322 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009323 // is also considered as a candidate function. Similarly,
9324 // surrogate call functions are added to the set of candidate
9325 // functions for each conversion function declared in an
9326 // accessible base class provided the function is not hidden
9327 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009328 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009329 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009330 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009331 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009332 NamedDecl *D = *I;
9333 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9334 if (isa<UsingShadowDecl>(D))
9335 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009336
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009337 // Skip over templated conversion functions; they aren't
9338 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009339 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009340 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009341
John McCall6e9f8f62009-12-03 04:06:58 +00009342 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009343 if (!Conv->isExplicit()) {
9344 // Strip the reference type (if any) and then the pointer type (if
9345 // any) to get down to what might be a function type.
9346 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9347 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9348 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +00009349
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009350 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9351 {
9352 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9353 Object.get(), Args, NumArgs, CandidateSet);
9354 }
9355 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00009356 }
Mike Stump11289f42009-09-09 15:08:12 +00009357
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009358 // Perform overload resolution.
9359 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009360 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009361 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009362 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009363 // Overload resolution succeeded; we'll build the appropriate call
9364 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009365 break;
9366
9367 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009368 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009369 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9370 << Object.get()->getType() << /*call*/ 1
9371 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009372 else
John Wiegley01296292011-04-08 18:41:53 +00009373 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009374 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009375 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009376 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009377 break;
9378
9379 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009380 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009381 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009382 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009383 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009384 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009385
9386 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00009387 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00009388 diag::err_ovl_deleted_object_call)
9389 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +00009390 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009391 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +00009392 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009393 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009394 break;
Mike Stump11289f42009-09-09 15:08:12 +00009395 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009396
Douglas Gregorb412e172010-07-25 18:17:45 +00009397 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009398 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009399
Douglas Gregorab7897a2008-11-19 22:57:39 +00009400 if (Best->Function == 0) {
9401 // Since there is no function declaration, this is one of the
9402 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00009403 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00009404 = cast<CXXConversionDecl>(
9405 Best->Conversions[0].UserDefined.ConversionFunction);
9406
John Wiegley01296292011-04-08 18:41:53 +00009407 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009408 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009409
Douglas Gregorab7897a2008-11-19 22:57:39 +00009410 // We selected one of the surrogate functions that converts the
9411 // object parameter to a function pointer. Perform the conversion
9412 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009413
Fariborz Jahanian774cf792009-09-28 18:35:46 +00009414 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00009415 // and then call it.
John Wiegley01296292011-04-08 18:41:53 +00009416 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv);
Douglas Gregor668443e2011-01-20 00:18:04 +00009417 if (Call.isInvalid())
9418 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009419
Douglas Gregor668443e2011-01-20 00:18:04 +00009420 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00009421 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00009422 }
9423
Chandler Carruth30141632011-02-25 19:41:05 +00009424 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009425 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009426 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009427
Douglas Gregorab7897a2008-11-19 22:57:39 +00009428 // We found an overloaded operator(). Build a CXXOperatorCallExpr
9429 // that calls this method, using Object for the implicit object
9430 // parameter and passing along the remaining arguments.
9431 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00009432 const FunctionProtoType *Proto =
9433 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009434
9435 unsigned NumArgsInProto = Proto->getNumArgs();
9436 unsigned NumArgsToCheck = NumArgs;
9437
9438 // Build the full argument list for the method call (the
9439 // implicit object parameter is placed at the beginning of the
9440 // list).
9441 Expr **MethodArgs;
9442 if (NumArgs < NumArgsInProto) {
9443 NumArgsToCheck = NumArgsInProto;
9444 MethodArgs = new Expr*[NumArgsInProto + 1];
9445 } else {
9446 MethodArgs = new Expr*[NumArgs + 1];
9447 }
John Wiegley01296292011-04-08 18:41:53 +00009448 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009449 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9450 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00009451
John Wiegley01296292011-04-08 18:41:53 +00009452 ExprResult NewFn = CreateFunctionRefExpr(*this, Method);
9453 if (NewFn.isInvalid())
9454 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009455
9456 // Once we've built TheCall, all of the expressions are properly
9457 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00009458 QualType ResultTy = Method->getResultType();
9459 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9460 ResultTy = ResultTy.getNonLValueExprType(Context);
9461
John McCallb268a282010-08-23 23:25:46 +00009462 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009463 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +00009464 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00009465 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009466 delete [] MethodArgs;
9467
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009468 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00009469 Method))
9470 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009471
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009472 // We may have default arguments. If so, we need to allocate more
9473 // slots in the call for them.
9474 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00009475 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009476 else if (NumArgs > NumArgsInProto)
9477 NumArgsToCheck = NumArgsInProto;
9478
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009479 bool IsError = false;
9480
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009481 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +00009482 ExprResult ObjRes =
9483 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9484 Best->FoundDecl, Method);
9485 if (ObjRes.isInvalid())
9486 IsError = true;
9487 else
9488 Object = move(ObjRes);
9489 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009490
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009491 // Check the argument types.
9492 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009493 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009494 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009495 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00009496
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009497 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009498
John McCalldadc5752010-08-24 06:29:42 +00009499 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009500 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009501 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009502 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00009503 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009504
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009505 IsError |= InputInit.isInvalid();
9506 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009507 } else {
John McCalldadc5752010-08-24 06:29:42 +00009508 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009509 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9510 if (DefArg.isInvalid()) {
9511 IsError = true;
9512 break;
9513 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009514
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009515 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009516 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009517
9518 TheCall->setArg(i + 1, Arg);
9519 }
9520
9521 // If this is a variadic call, handle args passed through "...".
9522 if (Proto->isVariadic()) {
9523 // Promote the arguments (C99 6.5.2.2p7).
9524 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +00009525 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9526 IsError |= Arg.isInvalid();
9527 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009528 }
9529 }
9530
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009531 if (IsError) return true;
9532
John McCallb268a282010-08-23 23:25:46 +00009533 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00009534 return true;
9535
John McCalle172be52010-08-24 06:09:16 +00009536 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009537}
9538
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009539/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00009540/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009541/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00009542ExprResult
John McCallb268a282010-08-23 23:25:46 +00009543Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009544 assert(Base->getType()->isRecordType() &&
9545 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00009546
John Wiegley01296292011-04-08 18:41:53 +00009547 if (Base->getObjectKind() == OK_ObjCProperty) {
9548 ExprResult Result = ConvertPropertyForRValue(Base);
9549 if (Result.isInvalid())
9550 return ExprError();
9551 Base = Result.take();
9552 }
John McCalle26a8722010-12-04 08:14:53 +00009553
John McCallbc077cf2010-02-08 23:07:23 +00009554 SourceLocation Loc = Base->getExprLoc();
9555
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009556 // C++ [over.ref]p1:
9557 //
9558 // [...] An expression x->m is interpreted as (x.operator->())->m
9559 // for a class object x of type T if T::operator->() exists and if
9560 // the operator is selected as the best match function by the
9561 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00009562 DeclarationName OpName =
9563 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00009564 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009565 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00009566
John McCallbc077cf2010-02-08 23:07:23 +00009567 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00009568 PDiag(diag::err_typecheck_incomplete_tag)
9569 << Base->getSourceRange()))
9570 return ExprError();
9571
John McCall27b18f82009-11-17 02:14:36 +00009572 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9573 LookupQualifiedName(R, BaseRecord->getDecl());
9574 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00009575
9576 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00009577 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00009578 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9579 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00009580 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009581
9582 // Perform overload resolution.
9583 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009584 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009585 case OR_Success:
9586 // Overload resolution succeeded; we'll build the call below.
9587 break;
9588
9589 case OR_No_Viable_Function:
9590 if (CandidateSet.empty())
9591 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00009592 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009593 else
9594 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00009595 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009596 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009597 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009598
9599 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009600 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9601 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009602 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009603 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009604
9605 case OR_Deleted:
9606 Diag(OpLoc, diag::err_ovl_deleted_oper)
9607 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009608 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009609 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009610 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009611 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009612 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009613 }
9614
Chandler Carruth30141632011-02-25 19:41:05 +00009615 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00009616 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009617 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00009618
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009619 // Convert the object parameter.
9620 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009621 ExprResult BaseResult =
9622 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9623 Best->FoundDecl, Method);
9624 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +00009625 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009626 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +00009627
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009628 // Build the operator call.
John Wiegley01296292011-04-08 18:41:53 +00009629 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method);
9630 if (FnExpr.isInvalid())
9631 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009632
John McCall7decc9e2010-11-18 06:31:45 +00009633 QualType ResultTy = Method->getResultType();
9634 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9635 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00009636 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009637 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009638 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009639
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009640 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009641 Method))
9642 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +00009643
9644 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009645}
9646
Douglas Gregorcd695e52008-11-10 20:40:00 +00009647/// FixOverloadedFunctionReference - E is an expression that refers to
9648/// a C++ overloaded function (possibly with some parentheses and
9649/// perhaps a '&' around it). We have resolved the overloaded function
9650/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00009651/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00009652Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00009653 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00009654 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009655 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9656 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009657 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009658 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009659
Douglas Gregor51c538b2009-11-20 19:42:02 +00009660 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009661 }
9662
Douglas Gregor51c538b2009-11-20 19:42:02 +00009663 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009664 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9665 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009666 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00009667 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00009668 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00009669 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00009670 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009671 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009672
9673 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +00009674 ICE->getCastKind(),
9675 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00009676 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009677 }
9678
Douglas Gregor51c538b2009-11-20 19:42:02 +00009679 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00009680 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00009681 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009682 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9683 if (Method->isStatic()) {
9684 // Do nothing: static member functions aren't any different
9685 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00009686 } else {
John McCalle66edc12009-11-24 19:00:30 +00009687 // Fix the sub expression, which really has to be an
9688 // UnresolvedLookupExpr holding an overloaded member function
9689 // or template.
John McCall16df1e52010-03-30 21:47:33 +00009690 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9691 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00009692 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009693 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00009694
John McCalld14a8642009-11-21 08:51:07 +00009695 assert(isa<DeclRefExpr>(SubExpr)
9696 && "fixed to something other than a decl ref");
9697 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9698 && "fixed to a member ref with no nested name qualifier");
9699
9700 // We have taken the address of a pointer to member
9701 // function. Perform the computation here so that we get the
9702 // appropriate pointer to member type.
9703 QualType ClassType
9704 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9705 QualType MemPtrType
9706 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9707
John McCall7decc9e2010-11-18 06:31:45 +00009708 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9709 VK_RValue, OK_Ordinary,
9710 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009711 }
9712 }
John McCall16df1e52010-03-30 21:47:33 +00009713 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9714 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009715 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009716 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009717
John McCalle3027922010-08-25 11:45:40 +00009718 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009719 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00009720 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009721 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009722 }
John McCalld14a8642009-11-21 08:51:07 +00009723
9724 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00009725 // FIXME: avoid copy.
9726 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00009727 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00009728 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9729 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00009730 }
9731
John McCalld14a8642009-11-21 08:51:07 +00009732 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009733 ULE->getQualifierLoc(),
John McCalld14a8642009-11-21 08:51:07 +00009734 Fn,
9735 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009736 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009737 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009738 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009739 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00009740 }
9741
John McCall10eae182009-11-30 22:42:35 +00009742 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00009743 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00009744 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9745 if (MemExpr->hasExplicitTemplateArgs()) {
9746 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9747 TemplateArgs = &TemplateArgsBuffer;
9748 }
John McCall6b51f282009-11-23 01:53:49 +00009749
John McCall2d74de92009-12-01 22:10:20 +00009750 Expr *Base;
9751
John McCall7decc9e2010-11-18 06:31:45 +00009752 // If we're filling in a static method where we used to have an
9753 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00009754 if (MemExpr->isImplicitAccess()) {
9755 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9756 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009757 MemExpr->getQualifierLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009758 Fn,
9759 MemExpr->getMemberLoc(),
9760 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009761 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009762 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009763 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00009764 } else {
9765 SourceLocation Loc = MemExpr->getMemberLoc();
9766 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +00009767 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +00009768 Base = new (Context) CXXThisExpr(Loc,
9769 MemExpr->getBaseType(),
9770 /*isImplicit=*/true);
9771 }
John McCall2d74de92009-12-01 22:10:20 +00009772 } else
John McCallc3007a22010-10-26 07:05:15 +00009773 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00009774
John McCall4adb38c2011-04-27 00:36:17 +00009775 ExprValueKind valueKind;
9776 QualType type;
9777 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9778 valueKind = VK_LValue;
9779 type = Fn->getType();
9780 } else {
9781 valueKind = VK_RValue;
9782 type = Context.BoundMemberTy;
9783 }
9784
John McCall2d74de92009-12-01 22:10:20 +00009785 return MemberExpr::Create(Context, Base,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009786 MemExpr->isArrow(),
Douglas Gregorea972d32011-02-28 21:54:11 +00009787 MemExpr->getQualifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009788 Fn,
John McCall16df1e52010-03-30 21:47:33 +00009789 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009790 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00009791 TemplateArgs,
John McCall4adb38c2011-04-27 00:36:17 +00009792 type, valueKind, OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009793 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009794
John McCallc3007a22010-10-26 07:05:15 +00009795 llvm_unreachable("Invalid reference to overloaded function");
9796 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009797}
9798
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009799ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +00009800 DeclAccessPair Found,
9801 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00009802 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00009803}
9804
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009805} // end namespace clang