blob: 6174bbac73c5eec0aebb73c6f0828cbe5ca4aad0 [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036
John McCall7decc9e2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
John Wiegley01296292011-04-08 18:41:53 +000039static ExprResult
John McCall7decc9e2010-11-18 06:31:45 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
Douglas Gregore9d62932011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
43 ExprResult E = S.Owned(new (S.Context) DeclRefExpr(Fn, Fn->getType(),
44 VK_LValue, Loc, LocInfo));
John Wiegley01296292011-04-08 18:41:53 +000045 E = S.DefaultFunctionArrayConversion(E.take());
46 if (E.isInvalid())
47 return ExprError();
48 return move(E);
John McCall7decc9e2010-11-18 06:31:45 +000049}
50
John McCall5c32be02010-08-24 20:38:10 +000051static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
52 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000053 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000054 bool CStyle,
55 bool AllowObjCWritebackConversion);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000056
57static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
58 QualType &ToType,
59 bool InOverloadResolution,
60 StandardConversionSequence &SCS,
61 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000062static OverloadingResult
63IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
64 UserDefinedConversionSequence& User,
65 OverloadCandidateSet& Conversions,
66 bool AllowExplicit);
67
68
69static ImplicitConversionSequence::CompareKind
70CompareStandardConversionSequences(Sema &S,
71 const StandardConversionSequence& SCS1,
72 const StandardConversionSequence& SCS2);
73
74static ImplicitConversionSequence::CompareKind
75CompareQualificationConversions(Sema &S,
76 const StandardConversionSequence& SCS1,
77 const StandardConversionSequence& SCS2);
78
79static ImplicitConversionSequence::CompareKind
80CompareDerivedToBaseConversions(Sema &S,
81 const StandardConversionSequence& SCS1,
82 const StandardConversionSequence& SCS2);
83
84
85
Douglas Gregor5251f1b2008-10-21 16:13:35 +000086/// GetConversionCategory - Retrieve the implicit conversion
87/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000088ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000089GetConversionCategory(ImplicitConversionKind Kind) {
90 static const ImplicitConversionCategory
91 Category[(int)ICK_Num_Conversion_Kinds] = {
92 ICC_Identity,
93 ICC_Lvalue_Transformation,
94 ICC_Lvalue_Transformation,
95 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000096 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000097 ICC_Qualification_Adjustment,
98 ICC_Promotion,
99 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000100 ICC_Promotion,
101 ICC_Conversion,
102 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000103 ICC_Conversion,
104 ICC_Conversion,
105 ICC_Conversion,
106 ICC_Conversion,
107 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000108 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000109 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000110 ICC_Conversion,
111 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000112 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000113 ICC_Conversion
114 };
115 return Category[(int)Kind];
116}
117
118/// GetConversionRank - Retrieve the implicit conversion rank
119/// corresponding to the given implicit conversion kind.
120ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
121 static const ImplicitConversionRank
122 Rank[(int)ICK_Num_Conversion_Kinds] = {
123 ICR_Exact_Match,
124 ICR_Exact_Match,
125 ICR_Exact_Match,
126 ICR_Exact_Match,
127 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000128 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000129 ICR_Promotion,
130 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000131 ICR_Promotion,
132 ICR_Conversion,
133 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000134 ICR_Conversion,
135 ICR_Conversion,
136 ICR_Conversion,
137 ICR_Conversion,
138 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000139 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000140 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000141 ICR_Conversion,
142 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000143 ICR_Complex_Real_Conversion,
144 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000145 ICR_Conversion,
146 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000147 };
148 return Rank[(int)Kind];
149}
150
151/// GetImplicitConversionName - Return the name of this kind of
152/// implicit conversion.
153const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000154 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000155 "No conversion",
156 "Lvalue-to-rvalue",
157 "Array-to-pointer",
158 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000159 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000160 "Qualification",
161 "Integral promotion",
162 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000163 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000164 "Integral conversion",
165 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000166 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000167 "Floating-integral conversion",
168 "Pointer conversion",
169 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000170 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000171 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000172 "Derived-to-base conversion",
173 "Vector conversion",
174 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000175 "Complex-real conversion",
176 "Block Pointer conversion",
177 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000178 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000179 };
180 return Name[Kind];
181}
182
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000183/// StandardConversionSequence - Set the standard conversion
184/// sequence to the identity conversion.
185void StandardConversionSequence::setAsIdentityConversion() {
186 First = ICK_Identity;
187 Second = ICK_Identity;
188 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000189 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000190 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000191 ReferenceBinding = false;
192 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000193 IsLvalueReference = true;
194 BindsToFunctionLvalue = false;
195 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000196 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000197 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000198 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000199}
200
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000201/// getRank - Retrieve the rank of this standard conversion sequence
202/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
203/// implicit conversions.
204ImplicitConversionRank StandardConversionSequence::getRank() const {
205 ImplicitConversionRank Rank = ICR_Exact_Match;
206 if (GetConversionRank(First) > Rank)
207 Rank = GetConversionRank(First);
208 if (GetConversionRank(Second) > Rank)
209 Rank = GetConversionRank(Second);
210 if (GetConversionRank(Third) > Rank)
211 Rank = GetConversionRank(Third);
212 return Rank;
213}
214
215/// isPointerConversionToBool - Determines whether this conversion is
216/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000217/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000218/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000219bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000220 // Note that FromType has not necessarily been transformed by the
221 // array-to-pointer or function-to-pointer implicit conversions, so
222 // check for their presence as well as checking whether FromType is
223 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000224 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000225 (getFromType()->isPointerType() ||
226 getFromType()->isObjCObjectPointerType() ||
227 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000228 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000229 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
230 return true;
231
232 return false;
233}
234
Douglas Gregor5c407d92008-10-23 00:40:37 +0000235/// isPointerConversionToVoidPointer - Determines whether this
236/// conversion is a conversion of a pointer to a void pointer. This is
237/// used as part of the ranking of standard conversion sequences (C++
238/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000239bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000240StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000241isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000242 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000243 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000244
245 // Note that FromType has not necessarily been transformed by the
246 // array-to-pointer implicit conversion, so check for its presence
247 // and redo the conversion to get a pointer.
248 if (First == ICK_Array_To_Pointer)
249 FromType = Context.getArrayDecayedType(FromType);
250
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000251 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000252 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000253 return ToPtrType->getPointeeType()->isVoidType();
254
255 return false;
256}
257
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000258/// DebugPrint - Print this standard conversion sequence to standard
259/// error. Useful for debugging overloading issues.
260void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000261 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000262 bool PrintedSomething = false;
263 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000264 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 PrintedSomething = true;
266 }
267
268 if (Second != ICK_Identity) {
269 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000270 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000271 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000272 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000273
274 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000275 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000276 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000277 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000278 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000279 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000280 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000281 PrintedSomething = true;
282 }
283
284 if (Third != ICK_Identity) {
285 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000286 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000287 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000288 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000289 PrintedSomething = true;
290 }
291
292 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000293 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000294 }
295}
296
297/// DebugPrint - Print this user-defined conversion sequence to standard
298/// error. Useful for debugging overloading issues.
299void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000300 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000301 if (Before.First || Before.Second || Before.Third) {
302 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000303 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000304 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000305 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000306 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000307 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000308 After.DebugPrint();
309 }
310}
311
312/// DebugPrint - Print this implicit conversion sequence to standard
313/// error. Useful for debugging overloading issues.
314void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000315 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000316 switch (ConversionKind) {
317 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000318 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000319 Standard.DebugPrint();
320 break;
321 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000322 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000323 UserDefined.DebugPrint();
324 break;
325 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000326 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000327 break;
John McCall0d1da222010-01-12 00:44:57 +0000328 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000329 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000330 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000331 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000332 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000333 break;
334 }
335
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000336 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000337}
338
John McCall0d1da222010-01-12 00:44:57 +0000339void AmbiguousConversionSequence::construct() {
340 new (&conversions()) ConversionSet();
341}
342
343void AmbiguousConversionSequence::destruct() {
344 conversions().~ConversionSet();
345}
346
347void
348AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
349 FromTypePtr = O.FromTypePtr;
350 ToTypePtr = O.ToTypePtr;
351 new (&conversions()) ConversionSet(O.conversions());
352}
353
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000354namespace {
355 // Structure used by OverloadCandidate::DeductionFailureInfo to store
356 // template parameter and template argument information.
357 struct DFIParamWithArguments {
358 TemplateParameter Param;
359 TemplateArgument FirstArg;
360 TemplateArgument SecondArg;
361 };
362}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000363
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000364/// \brief Convert from Sema's representation of template deduction information
365/// to the form used in overload-candidate information.
366OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000367static MakeDeductionFailureInfo(ASTContext &Context,
368 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000369 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000370 OverloadCandidate::DeductionFailureInfo Result;
371 Result.Result = static_cast<unsigned>(TDK);
372 Result.Data = 0;
373 switch (TDK) {
374 case Sema::TDK_Success:
375 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000376 case Sema::TDK_TooManyArguments:
377 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000378 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000379
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000380 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000381 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000382 Result.Data = Info.Param.getOpaqueValue();
383 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000384
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000385 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000386 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000387 // FIXME: Should allocate from normal heap so that we can free this later.
388 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000389 Saved->Param = Info.Param;
390 Saved->FirstArg = Info.FirstArg;
391 Saved->SecondArg = Info.SecondArg;
392 Result.Data = Saved;
393 break;
394 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000395
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000396 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000397 Result.Data = Info.take();
398 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000399
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000400 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000401 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000402 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000403 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000404
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000405 return Result;
406}
John McCall0d1da222010-01-12 00:44:57 +0000407
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000408void OverloadCandidate::DeductionFailureInfo::Destroy() {
409 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
410 case Sema::TDK_Success:
411 case Sema::TDK_InstantiationDepth:
412 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000413 case Sema::TDK_TooManyArguments:
414 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000415 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000416 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000417
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000418 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000419 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000420 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000421 Data = 0;
422 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000423
424 case Sema::TDK_SubstitutionFailure:
425 // FIXME: Destroy the template arugment list?
426 Data = 0;
427 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000428
Douglas Gregor461761d2010-05-08 18:20:53 +0000429 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000430 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000431 case Sema::TDK_FailedOverloadResolution:
432 break;
433 }
434}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000435
436TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000437OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
438 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
439 case Sema::TDK_Success:
440 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000441 case Sema::TDK_TooManyArguments:
442 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000443 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000444 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000445
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000446 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000447 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000448 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000449
450 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000451 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000452 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000453
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000454 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000455 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000456 case Sema::TDK_FailedOverloadResolution:
457 break;
458 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000459
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000460 return TemplateParameter();
461}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000462
Douglas Gregord09efd42010-05-08 20:07:26 +0000463TemplateArgumentList *
464OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
465 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
466 case Sema::TDK_Success:
467 case Sema::TDK_InstantiationDepth:
468 case Sema::TDK_TooManyArguments:
469 case Sema::TDK_TooFewArguments:
470 case Sema::TDK_Incomplete:
471 case Sema::TDK_InvalidExplicitArguments:
472 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000473 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000474 return 0;
475
476 case Sema::TDK_SubstitutionFailure:
477 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000478
Douglas Gregord09efd42010-05-08 20:07:26 +0000479 // Unhandled
480 case Sema::TDK_NonDeducedMismatch:
481 case Sema::TDK_FailedOverloadResolution:
482 break;
483 }
484
485 return 0;
486}
487
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000488const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
489 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
490 case Sema::TDK_Success:
491 case Sema::TDK_InstantiationDepth:
492 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000493 case Sema::TDK_TooManyArguments:
494 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000495 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000496 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000497 return 0;
498
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000499 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000500 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000501 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000502
Douglas Gregor461761d2010-05-08 18:20:53 +0000503 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000504 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000505 case Sema::TDK_FailedOverloadResolution:
506 break;
507 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000508
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000509 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000510}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000511
512const TemplateArgument *
513OverloadCandidate::DeductionFailureInfo::getSecondArg() {
514 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
515 case Sema::TDK_Success:
516 case Sema::TDK_InstantiationDepth:
517 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000518 case Sema::TDK_TooManyArguments:
519 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000520 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000521 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000522 return 0;
523
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000524 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000525 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000526 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
527
Douglas Gregor461761d2010-05-08 18:20:53 +0000528 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000529 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000530 case Sema::TDK_FailedOverloadResolution:
531 break;
532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000533
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000534 return 0;
535}
536
537void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000538 inherited::clear();
539 Functions.clear();
540}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000541
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000542// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000543// overload of the declarations in Old. This routine returns false if
544// New and Old cannot be overloaded, e.g., if New has the same
545// signature as some function in Old (C++ 1.3.10) or if the Old
546// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000547// it does return false, MatchedDecl will point to the decl that New
548// cannot be overloaded with. This decl may be a UsingShadowDecl on
549// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000550//
551// Example: Given the following input:
552//
553// void f(int, float); // #1
554// void f(int, int); // #2
555// int f(int, int); // #3
556//
557// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000558// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000559//
John McCall3d988d92009-12-02 08:47:38 +0000560// When we process #2, Old contains only the FunctionDecl for #1. By
561// comparing the parameter types, we see that #1 and #2 are overloaded
562// (since they have different signatures), so this routine returns
563// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000564//
John McCall3d988d92009-12-02 08:47:38 +0000565// When we process #3, Old is an overload set containing #1 and #2. We
566// compare the signatures of #3 to #1 (they're overloaded, so we do
567// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
568// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000569// signature), IsOverload returns false and MatchedDecl will be set to
570// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000571//
572// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
573// into a class by a using declaration. The rules for whether to hide
574// shadow declarations ignore some properties which otherwise figure
575// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000576Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000577Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
578 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000579 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000580 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000581 NamedDecl *OldD = *I;
582
583 bool OldIsUsingDecl = false;
584 if (isa<UsingShadowDecl>(OldD)) {
585 OldIsUsingDecl = true;
586
587 // We can always introduce two using declarations into the same
588 // context, even if they have identical signatures.
589 if (NewIsUsingDecl) continue;
590
591 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
592 }
593
594 // If either declaration was introduced by a using declaration,
595 // we'll need to use slightly different rules for matching.
596 // Essentially, these rules are the normal rules, except that
597 // function templates hide function templates with different
598 // return types or template parameter lists.
599 bool UseMemberUsingDeclRules =
600 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
601
John McCall3d988d92009-12-02 08:47:38 +0000602 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000603 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
604 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
605 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
606 continue;
607 }
608
John McCalldaa3d6b2009-12-09 03:35:25 +0000609 Match = *I;
610 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000611 }
John McCall3d988d92009-12-02 08:47:38 +0000612 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000613 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
614 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
615 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
616 continue;
617 }
618
John McCalldaa3d6b2009-12-09 03:35:25 +0000619 Match = *I;
620 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000621 }
John McCalla8987a2942010-11-10 03:01:53 +0000622 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000623 // We can overload with these, which can show up when doing
624 // redeclaration checks for UsingDecls.
625 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000626 } else if (isa<TagDecl>(OldD)) {
627 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000628 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
629 // Optimistically assume that an unresolved using decl will
630 // overload; if it doesn't, we'll have to diagnose during
631 // template instantiation.
632 } else {
John McCall1f82f242009-11-18 22:49:29 +0000633 // (C++ 13p1):
634 // Only function declarations can be overloaded; object and type
635 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000636 Match = *I;
637 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000638 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000639 }
John McCall1f82f242009-11-18 22:49:29 +0000640
John McCalldaa3d6b2009-12-09 03:35:25 +0000641 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000642}
643
John McCalle9cccd82010-06-16 08:42:20 +0000644bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
645 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000646 // If both of the functions are extern "C", then they are not
647 // overloads.
648 if (Old->isExternC() && New->isExternC())
649 return false;
650
John McCall1f82f242009-11-18 22:49:29 +0000651 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
652 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
653
654 // C++ [temp.fct]p2:
655 // A function template can be overloaded with other function templates
656 // and with normal (non-template) functions.
657 if ((OldTemplate == 0) != (NewTemplate == 0))
658 return true;
659
660 // Is the function New an overload of the function Old?
661 QualType OldQType = Context.getCanonicalType(Old->getType());
662 QualType NewQType = Context.getCanonicalType(New->getType());
663
664 // Compare the signatures (C++ 1.3.10) of the two functions to
665 // determine whether they are overloads. If we find any mismatch
666 // in the signature, they are overloads.
667
668 // If either of these functions is a K&R-style function (no
669 // prototype), then we consider them to have matching signatures.
670 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
671 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
672 return false;
673
John McCall424cec92011-01-19 06:33:43 +0000674 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
675 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000676
677 // The signature of a function includes the types of its
678 // parameters (C++ 1.3.10), which includes the presence or absence
679 // of the ellipsis; see C++ DR 357).
680 if (OldQType != NewQType &&
681 (OldType->getNumArgs() != NewType->getNumArgs() ||
682 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000683 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000684 return true;
685
686 // C++ [temp.over.link]p4:
687 // The signature of a function template consists of its function
688 // signature, its return type and its template parameter list. The names
689 // of the template parameters are significant only for establishing the
690 // relationship between the template parameters and the rest of the
691 // signature.
692 //
693 // We check the return type and template parameter lists for function
694 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000695 //
696 // However, we don't consider either of these when deciding whether
697 // a member introduced by a shadow declaration is hidden.
698 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000699 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
700 OldTemplate->getTemplateParameters(),
701 false, TPL_TemplateMatch) ||
702 OldType->getResultType() != NewType->getResultType()))
703 return true;
704
705 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000706 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000707 //
708 // As part of this, also check whether one of the member functions
709 // is static, in which case they are not overloads (C++
710 // 13.1p2). While not part of the definition of the signature,
711 // this check is important to determine whether these functions
712 // can be overloaded.
713 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
714 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
715 if (OldMethod && NewMethod &&
716 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000717 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000718 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
719 if (!UseUsingDeclRules &&
720 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
721 (OldMethod->getRefQualifier() == RQ_None ||
722 NewMethod->getRefQualifier() == RQ_None)) {
723 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000724 // - Member function declarations with the same name and the same
725 // parameter-type-list as well as member function template
726 // declarations with the same name, the same parameter-type-list, and
727 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000728 // them, but not all, have a ref-qualifier (8.3.5).
729 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
730 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
731 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
732 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000733
John McCall1f82f242009-11-18 22:49:29 +0000734 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000736
John McCall1f82f242009-11-18 22:49:29 +0000737 // The signatures match; this is not an overload.
738 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000739}
740
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000741/// \brief Checks availability of the function depending on the current
742/// function context. Inside an unavailable function, unavailability is ignored.
743///
744/// \returns true if \arg FD is unavailable and current context is inside
745/// an available function, false otherwise.
746bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
747 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
748}
749
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000750/// TryImplicitConversion - Attempt to perform an implicit conversion
751/// from the given expression (Expr) to the given type (ToType). This
752/// function returns an implicit conversion sequence that can be used
753/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000754///
755/// void f(float f);
756/// void g(int i) { f(i); }
757///
758/// this routine would produce an implicit conversion sequence to
759/// describe the initialization of f from i, which will be a standard
760/// conversion sequence containing an lvalue-to-rvalue conversion (C++
761/// 4.1) followed by a floating-integral conversion (C++ 4.9).
762//
763/// Note that this routine only determines how the conversion can be
764/// performed; it does not actually perform the conversion. As such,
765/// it will not produce any diagnostics if no conversion is available,
766/// but will instead return an implicit conversion sequence of kind
767/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000768///
769/// If @p SuppressUserConversions, then user-defined conversions are
770/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000771/// If @p AllowExplicit, then explicit user-defined conversions are
772/// permitted.
John McCall31168b02011-06-15 23:02:42 +0000773///
774/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
775/// writeback conversion, which allows __autoreleasing id* parameters to
776/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +0000777static ImplicitConversionSequence
778TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
779 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000780 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000781 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000782 bool CStyle,
783 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000784 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000785 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000786 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +0000787 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000788 return ICS;
789 }
790
John McCall5c32be02010-08-24 20:38:10 +0000791 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000792 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000793 return ICS;
794 }
795
Douglas Gregor836a7e82010-08-11 02:15:33 +0000796 // C++ [over.ics.user]p4:
797 // A conversion of an expression of class type to the same class
798 // type is given Exact Match rank, and a conversion of an
799 // expression of class type to a base class of that type is
800 // given Conversion rank, in spite of the fact that a copy/move
801 // constructor (i.e., a user-defined conversion function) is
802 // called for those cases.
803 QualType FromType = From->getType();
804 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000805 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
806 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000807 ICS.setStandard();
808 ICS.Standard.setAsIdentityConversion();
809 ICS.Standard.setFromType(FromType);
810 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000811
Douglas Gregor5ab11652010-04-17 22:01:05 +0000812 // We don't actually check at this point whether there is a valid
813 // copy/move constructor, since overloading just assumes that it
814 // exists. When we actually perform initialization, we'll find the
815 // appropriate constructor to copy the returned object, if needed.
816 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000817
Douglas Gregor5ab11652010-04-17 22:01:05 +0000818 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000819 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000820 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000821
Douglas Gregor836a7e82010-08-11 02:15:33 +0000822 return ICS;
823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824
Douglas Gregor836a7e82010-08-11 02:15:33 +0000825 if (SuppressUserConversions) {
826 // We're not in the case above, so there is no conversion that
827 // we can perform.
828 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000829 return ICS;
830 }
831
832 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000833 OverloadCandidateSet Conversions(From->getExprLoc());
834 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000835 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000836 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000837
838 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000839 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000840 // C++ [over.ics.user]p4:
841 // A conversion of an expression of class type to the same class
842 // type is given Exact Match rank, and a conversion of an
843 // expression of class type to a base class of that type is
844 // given Conversion rank, in spite of the fact that a copy
845 // constructor (i.e., a user-defined conversion function) is
846 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000847 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000848 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000849 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000850 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
851 QualType ToCanon
852 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000853 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000854 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000855 // Turn this into a "standard" conversion sequence, so that it
856 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000857 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000858 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000859 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000860 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000861 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000862 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000863 ICS.Standard.Second = ICK_Derived_To_Base;
864 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000865 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000866
867 // C++ [over.best.ics]p4:
868 // However, when considering the argument of a user-defined
869 // conversion function that is a candidate by 13.3.1.3 when
870 // invoked for the copying of the temporary in the second step
871 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
872 // 13.3.1.6 in all cases, only standard conversion sequences and
873 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000874 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000875 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000876 }
John McCalle8c8cd22010-01-13 22:30:33 +0000877 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000878 ICS.setAmbiguous();
879 ICS.Ambiguous.setFromType(From->getType());
880 ICS.Ambiguous.setToType(ToType);
881 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
882 Cand != Conversions.end(); ++Cand)
883 if (Cand->Viable)
884 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000885 } else {
John McCall65eb8792010-02-25 01:37:24 +0000886 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000887 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000888
889 return ICS;
890}
891
John McCall31168b02011-06-15 23:02:42 +0000892ImplicitConversionSequence
893Sema::TryImplicitConversion(Expr *From, QualType ToType,
894 bool SuppressUserConversions,
895 bool AllowExplicit,
896 bool InOverloadResolution,
897 bool CStyle,
898 bool AllowObjCWritebackConversion) {
899 return clang::TryImplicitConversion(*this, From, ToType,
900 SuppressUserConversions, AllowExplicit,
901 InOverloadResolution, CStyle,
902 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +0000903}
904
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000905/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +0000906/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000907/// converted expression. Flavor is the kind of conversion we're
908/// performing, used in the error message. If @p AllowExplicit,
909/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +0000910ExprResult
911Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000912 AssignmentAction Action, bool AllowExplicit,
913 bool Diagnose) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000914 ImplicitConversionSequence ICS;
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000915 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS,
916 Diagnose);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000917}
918
John Wiegley01296292011-04-08 18:41:53 +0000919ExprResult
920Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000921 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000922 ImplicitConversionSequence& ICS,
923 bool Diagnose) {
John McCall31168b02011-06-15 23:02:42 +0000924 // Objective-C ARC: Determine whether we will allow the writeback conversion.
925 bool AllowObjCWritebackConversion
926 = getLangOptions().ObjCAutoRefCount &&
927 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +0000928
John McCall5c32be02010-08-24 20:38:10 +0000929 ICS = clang::TryImplicitConversion(*this, From, ToType,
930 /*SuppressUserConversions=*/false,
931 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000932 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +0000933 /*CStyle=*/false,
934 AllowObjCWritebackConversion);
Sebastian Redlb49c46c2011-09-24 17:48:00 +0000935 if (!Diagnose && ICS.isFailure())
936 return ExprError();
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000937 return PerformImplicitConversion(From, ToType, ICS, Action);
938}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000939
940/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000941/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +0000942bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
943 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000944 if (Context.hasSameUnqualifiedType(FromType, ToType))
945 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000946
John McCall991eb4b2010-12-21 00:44:39 +0000947 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
948 // where F adds one of the following at most once:
949 // - a pointer
950 // - a member pointer
951 // - a block pointer
952 CanQualType CanTo = Context.getCanonicalType(ToType);
953 CanQualType CanFrom = Context.getCanonicalType(FromType);
954 Type::TypeClass TyClass = CanTo->getTypeClass();
955 if (TyClass != CanFrom->getTypeClass()) return false;
956 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
957 if (TyClass == Type::Pointer) {
958 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
959 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
960 } else if (TyClass == Type::BlockPointer) {
961 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
962 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
963 } else if (TyClass == Type::MemberPointer) {
964 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
965 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
966 } else {
967 return false;
968 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000969
John McCall991eb4b2010-12-21 00:44:39 +0000970 TyClass = CanTo->getTypeClass();
971 if (TyClass != CanFrom->getTypeClass()) return false;
972 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
973 return false;
974 }
975
976 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
977 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
978 if (!EInfo.getNoReturn()) return false;
979
980 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
981 assert(QualType(FromFn, 0).isCanonical());
982 if (QualType(FromFn, 0) != CanTo) return false;
983
984 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000985 return true;
986}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000987
Douglas Gregor46188682010-05-18 22:42:18 +0000988/// \brief Determine whether the conversion from FromType to ToType is a valid
989/// vector conversion.
990///
991/// \param ICK Will be set to the vector conversion kind, if this is a vector
992/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000993static bool IsVectorConversion(ASTContext &Context, QualType FromType,
994 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +0000995 // We need at least one of these types to be a vector type to have a vector
996 // conversion.
997 if (!ToType->isVectorType() && !FromType->isVectorType())
998 return false;
999
1000 // Identical types require no conversions.
1001 if (Context.hasSameUnqualifiedType(FromType, ToType))
1002 return false;
1003
1004 // There are no conversions between extended vector types, only identity.
1005 if (ToType->isExtVectorType()) {
1006 // There are no conversions between extended vector types other than the
1007 // identity conversion.
1008 if (FromType->isExtVectorType())
1009 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001010
Douglas Gregor46188682010-05-18 22:42:18 +00001011 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001012 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001013 ICK = ICK_Vector_Splat;
1014 return true;
1015 }
1016 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001017
1018 // We can perform the conversion between vector types in the following cases:
1019 // 1)vector types are equivalent AltiVec and GCC vector types
1020 // 2)lax vector conversions are permitted and the vector types are of the
1021 // same size
1022 if (ToType->isVectorType() && FromType->isVectorType()) {
1023 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001024 (Context.getLangOptions().LaxVectorConversions &&
1025 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001026 ICK = ICK_Vector_Conversion;
1027 return true;
1028 }
Douglas Gregor46188682010-05-18 22:42:18 +00001029 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001030
Douglas Gregor46188682010-05-18 22:42:18 +00001031 return false;
1032}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001033
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001034/// IsStandardConversion - Determines whether there is a standard
1035/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1036/// expression From to the type ToType. Standard conversion sequences
1037/// only consider non-class types; for conversions that involve class
1038/// types, use TryImplicitConversion. If a conversion exists, SCS will
1039/// contain the standard conversion sequence required to perform this
1040/// conversion and this routine will return true. Otherwise, this
1041/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001042static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1043 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001044 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001045 bool CStyle,
1046 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001047 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001048
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001049 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001050 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001051 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001052 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001053 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001054 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001055
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001056 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001057 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001058 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001059 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001060 return false;
1061
Mike Stump11289f42009-09-09 15:08:12 +00001062 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001063 }
1064
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001065 // The first conversion can be an lvalue-to-rvalue conversion,
1066 // array-to-pointer conversion, or function-to-pointer conversion
1067 // (C++ 4p1).
1068
John McCall5c32be02010-08-24 20:38:10 +00001069 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001070 DeclAccessPair AccessPair;
1071 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001072 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001073 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001074 // We were able to resolve the address of the overloaded function,
1075 // so we can convert to the type of that function.
1076 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001077
1078 // we can sometimes resolve &foo<int> regardless of ToType, so check
1079 // if the type matches (identity) or we are converting to bool
1080 if (!S.Context.hasSameUnqualifiedType(
1081 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1082 QualType resultTy;
1083 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001084 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001085 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1086 // otherwise, only a boolean conversion is standard
1087 if (!ToType->isBooleanType())
1088 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001089 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001090
Chandler Carruthffce2452011-03-29 08:08:18 +00001091 // Check if the "from" expression is taking the address of an overloaded
1092 // function and recompute the FromType accordingly. Take advantage of the
1093 // fact that non-static member functions *must* have such an address-of
1094 // expression.
1095 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1096 if (Method && !Method->isStatic()) {
1097 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1098 "Non-unary operator on non-static member address");
1099 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1100 == UO_AddrOf &&
1101 "Non-address-of operator on non-static member address");
1102 const Type *ClassType
1103 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1104 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001105 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1106 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1107 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001108 "Non-address-of operator for overloaded function expression");
1109 FromType = S.Context.getPointerType(FromType);
1110 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001111
Douglas Gregor980fb162010-04-29 18:24:40 +00001112 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001113 assert(S.Context.hasSameType(
1114 FromType,
1115 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001116 } else {
1117 return false;
1118 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001119 }
John McCall154a2fd2011-08-30 00:57:29 +00001120 // Lvalue-to-rvalue conversion (C++11 4.1):
1121 // A glvalue (3.10) of a non-function, non-array type T can
1122 // be converted to a prvalue.
1123 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001124 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001125 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001126 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001127 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001128
1129 // If T is a non-class type, the type of the rvalue is the
1130 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001131 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1132 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001133 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001134 } else if (FromType->isArrayType()) {
1135 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001136 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001137
1138 // An lvalue or rvalue of type "array of N T" or "array of unknown
1139 // bound of T" can be converted to an rvalue of type "pointer to
1140 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001141 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001142
John McCall5c32be02010-08-24 20:38:10 +00001143 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001144 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001145 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001146
1147 // For the purpose of ranking in overload resolution
1148 // (13.3.3.1.1), this conversion is considered an
1149 // array-to-pointer conversion followed by a qualification
1150 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001151 SCS.Second = ICK_Identity;
1152 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001153 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001154 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001155 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001156 }
John McCall086a4642010-11-24 05:12:34 +00001157 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001158 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001159 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001160
1161 // An lvalue of function type T can be converted to an rvalue of
1162 // type "pointer to T." The result is a pointer to the
1163 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001164 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001165 } else {
1166 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001167 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001168 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001169 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001170
1171 // The second conversion can be an integral promotion, floating
1172 // point promotion, integral conversion, floating point conversion,
1173 // floating-integral conversion, pointer conversion,
1174 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001175 // For overloading in C, this can also be a "compatible-type"
1176 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001177 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001178 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001179 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001180 // The unqualified versions of the types are the same: there's no
1181 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001182 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001183 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001184 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001185 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001186 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001187 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001188 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001189 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001190 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001191 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001192 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001193 SCS.Second = ICK_Complex_Promotion;
1194 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001195 } else if (ToType->isBooleanType() &&
1196 (FromType->isArithmeticType() ||
1197 FromType->isAnyPointerType() ||
1198 FromType->isBlockPointerType() ||
1199 FromType->isMemberPointerType() ||
1200 FromType->isNullPtrType())) {
1201 // Boolean conversions (C++ 4.12).
1202 SCS.Second = ICK_Boolean_Conversion;
1203 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001204 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001205 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001206 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001207 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001208 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001209 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001210 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001211 SCS.Second = ICK_Complex_Conversion;
1212 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001213 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1214 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001215 // Complex-real conversions (C99 6.3.1.7)
1216 SCS.Second = ICK_Complex_Real;
1217 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001218 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001219 // Floating point conversions (C++ 4.8).
1220 SCS.Second = ICK_Floating_Conversion;
1221 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001222 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001223 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001224 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001225 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001226 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001227 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001228 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001229 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001230 SCS.Second = ICK_Block_Pointer_Conversion;
1231 } else if (AllowObjCWritebackConversion &&
1232 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1233 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001234 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1235 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001236 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001237 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001238 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001239 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001240 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001241 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001242 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001243 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001244 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001245 SCS.Second = SecondICK;
1246 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001247 } else if (!S.getLangOptions().CPlusPlus &&
1248 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001249 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001250 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001251 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001252 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001253 // Treat a conversion that strips "noreturn" as an identity conversion.
1254 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001255 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1256 InOverloadResolution,
1257 SCS, CStyle)) {
1258 SCS.Second = ICK_TransparentUnionConversion;
1259 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001260 } else {
1261 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001262 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001263 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001264 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001265
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001266 QualType CanonFrom;
1267 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001268 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001269 bool ObjCLifetimeConversion;
1270 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1271 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001272 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001273 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001274 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001275 CanonFrom = S.Context.getCanonicalType(FromType);
1276 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001277 } else {
1278 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001279 SCS.Third = ICK_Identity;
1280
Mike Stump11289f42009-09-09 15:08:12 +00001281 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001282 // [...] Any difference in top-level cv-qualification is
1283 // subsumed by the initialization itself and does not constitute
1284 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001285 CanonFrom = S.Context.getCanonicalType(FromType);
1286 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001287 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001288 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001289 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001290 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1291 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001292 FromType = ToType;
1293 CanonFrom = CanonTo;
1294 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001295 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001296 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001297
1298 // If we have not converted the argument type to the parameter type,
1299 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001300 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001301 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001302
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001303 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001304}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001305
1306static bool
1307IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1308 QualType &ToType,
1309 bool InOverloadResolution,
1310 StandardConversionSequence &SCS,
1311 bool CStyle) {
1312
1313 const RecordType *UT = ToType->getAsUnionType();
1314 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1315 return false;
1316 // The field to initialize within the transparent union.
1317 RecordDecl *UD = UT->getDecl();
1318 // It's compatible if the expression matches any of the fields.
1319 for (RecordDecl::field_iterator it = UD->field_begin(),
1320 itend = UD->field_end();
1321 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001322 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1323 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001324 ToType = it->getType();
1325 return true;
1326 }
1327 }
1328 return false;
1329}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001330
1331/// IsIntegralPromotion - Determines whether the conversion from the
1332/// expression From (whose potentially-adjusted type is FromType) to
1333/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1334/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001335bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001336 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001337 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001338 if (!To) {
1339 return false;
1340 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001341
1342 // An rvalue of type char, signed char, unsigned char, short int, or
1343 // unsigned short int can be converted to an rvalue of type int if
1344 // int can represent all the values of the source type; otherwise,
1345 // the source rvalue can be converted to an rvalue of type unsigned
1346 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001347 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1348 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001349 if (// We can promote any signed, promotable integer type to an int
1350 (FromType->isSignedIntegerType() ||
1351 // We can promote any unsigned integer type whose size is
1352 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001353 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001354 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001355 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001356 }
1357
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001358 return To->getKind() == BuiltinType::UInt;
1359 }
1360
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001361 // C++0x [conv.prom]p3:
1362 // A prvalue of an unscoped enumeration type whose underlying type is not
1363 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1364 // following types that can represent all the values of the enumeration
1365 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1366 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001367 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001368 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001369 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001370 // with lowest integer conversion rank (4.13) greater than the rank of long
1371 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001372 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001373 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1374 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1375 // provided for a scoped enumeration.
1376 if (FromEnumType->getDecl()->isScoped())
1377 return false;
1378
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001379 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001380 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001381 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001382 return Context.hasSameUnqualifiedType(ToType,
1383 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001384 }
John McCall56774992009-12-09 09:09:27 +00001385
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001386 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001387 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1388 // to an rvalue a prvalue of the first of the following types that can
1389 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001390 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001391 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001392 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001393 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001394 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001395 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001396 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001397 // Determine whether the type we're converting from is signed or
1398 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001399 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001400 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001401
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001402 // The types we'll try to promote to, in the appropriate
1403 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001404 QualType PromoteTypes[6] = {
1405 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001406 Context.LongTy, Context.UnsignedLongTy ,
1407 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001408 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001409 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001410 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1411 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001412 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001413 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1414 // We found the type that we can promote to. If this is the
1415 // type we wanted, we have a promotion. Otherwise, no
1416 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001417 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001418 }
1419 }
1420 }
1421
1422 // An rvalue for an integral bit-field (9.6) can be converted to an
1423 // rvalue of type int if int can represent all the values of the
1424 // bit-field; otherwise, it can be converted to unsigned int if
1425 // unsigned int can represent all the values of the bit-field. If
1426 // the bit-field is larger yet, no integral promotion applies to
1427 // it. If the bit-field has an enumerated type, it is treated as any
1428 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001429 // FIXME: We should delay checking of bit-fields until we actually perform the
1430 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001431 using llvm::APSInt;
1432 if (From)
1433 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001434 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001435 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001436 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1437 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1438 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001439
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001440 // Are we promoting to an int from a bitfield that fits in an int?
1441 if (BitWidth < ToSize ||
1442 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1443 return To->getKind() == BuiltinType::Int;
1444 }
Mike Stump11289f42009-09-09 15:08:12 +00001445
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001446 // Are we promoting to an unsigned int from an unsigned bitfield
1447 // that fits into an unsigned int?
1448 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1449 return To->getKind() == BuiltinType::UInt;
1450 }
Mike Stump11289f42009-09-09 15:08:12 +00001451
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001452 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001453 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001454 }
Mike Stump11289f42009-09-09 15:08:12 +00001455
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001456 // An rvalue of type bool can be converted to an rvalue of type int,
1457 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001458 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001459 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001460 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001461
1462 return false;
1463}
1464
1465/// IsFloatingPointPromotion - Determines whether the conversion from
1466/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1467/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001468bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001469 /// An rvalue of type float can be converted to an rvalue of type
1470 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001471 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1472 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001473 if (FromBuiltin->getKind() == BuiltinType::Float &&
1474 ToBuiltin->getKind() == BuiltinType::Double)
1475 return true;
1476
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001477 // C99 6.3.1.5p1:
1478 // When a float is promoted to double or long double, or a
1479 // double is promoted to long double [...].
1480 if (!getLangOptions().CPlusPlus &&
1481 (FromBuiltin->getKind() == BuiltinType::Float ||
1482 FromBuiltin->getKind() == BuiltinType::Double) &&
1483 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1484 return true;
1485 }
1486
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001487 return false;
1488}
1489
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001490/// \brief Determine if a conversion is a complex promotion.
1491///
1492/// A complex promotion is defined as a complex -> complex conversion
1493/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001494/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001495bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001496 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001497 if (!FromComplex)
1498 return false;
1499
John McCall9dd450b2009-09-21 23:43:11 +00001500 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001501 if (!ToComplex)
1502 return false;
1503
1504 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001505 ToComplex->getElementType()) ||
1506 IsIntegralPromotion(0, FromComplex->getElementType(),
1507 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001508}
1509
Douglas Gregor237f96c2008-11-26 23:31:11 +00001510/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1511/// the pointer type FromPtr to a pointer to type ToPointee, with the
1512/// same type qualifiers as FromPtr has on its pointee type. ToType,
1513/// if non-empty, will be a pointer to ToType that may or may not have
1514/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001515///
Mike Stump11289f42009-09-09 15:08:12 +00001516static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001517BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001518 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001519 ASTContext &Context,
1520 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001521 assert((FromPtr->getTypeClass() == Type::Pointer ||
1522 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1523 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001524
John McCall31168b02011-06-15 23:02:42 +00001525 /// Conversions to 'id' subsume cv-qualifier conversions.
1526 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001527 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001528
1529 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001530 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001531 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001532 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001533
John McCall31168b02011-06-15 23:02:42 +00001534 if (StripObjCLifetime)
1535 Quals.removeObjCLifetime();
1536
Mike Stump11289f42009-09-09 15:08:12 +00001537 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001538 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001539 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001540 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001541 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001542
1543 // Build a pointer to ToPointee. It has the right qualifiers
1544 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001545 if (isa<ObjCObjectPointerType>(ToType))
1546 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001547 return Context.getPointerType(ToPointee);
1548 }
1549
1550 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001551 QualType QualifiedCanonToPointee
1552 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001553
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001554 if (isa<ObjCObjectPointerType>(ToType))
1555 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1556 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001557}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001558
Mike Stump11289f42009-09-09 15:08:12 +00001559static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001560 bool InOverloadResolution,
1561 ASTContext &Context) {
1562 // Handle value-dependent integral null pointer constants correctly.
1563 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1564 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001565 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001566 return !InOverloadResolution;
1567
Douglas Gregor56751b52009-09-25 04:25:58 +00001568 return Expr->isNullPointerConstant(Context,
1569 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1570 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001571}
Mike Stump11289f42009-09-09 15:08:12 +00001572
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001573/// IsPointerConversion - Determines whether the conversion of the
1574/// expression From, which has the (possibly adjusted) type FromType,
1575/// can be converted to the type ToType via a pointer conversion (C++
1576/// 4.10). If so, returns true and places the converted type (that
1577/// might differ from ToType in its cv-qualifiers at some level) into
1578/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001579///
Douglas Gregora29dc052008-11-27 01:19:21 +00001580/// This routine also supports conversions to and from block pointers
1581/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1582/// pointers to interfaces. FIXME: Once we've determined the
1583/// appropriate overloading rules for Objective-C, we may want to
1584/// split the Objective-C checks into a different routine; however,
1585/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001586/// conversions, so for now they live here. IncompatibleObjC will be
1587/// set if the conversion is an allowed Objective-C conversion that
1588/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001589bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001590 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001591 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001592 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001593 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001594 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1595 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001596 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001597
Mike Stump11289f42009-09-09 15:08:12 +00001598 // Conversion from a null pointer constant to any Objective-C pointer type.
1599 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001600 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001601 ConvertedType = ToType;
1602 return true;
1603 }
1604
Douglas Gregor231d1c62008-11-27 00:15:41 +00001605 // Blocks: Block pointers can be converted to void*.
1606 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001607 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001608 ConvertedType = ToType;
1609 return true;
1610 }
1611 // Blocks: A null pointer constant can be converted to a block
1612 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001613 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001614 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001615 ConvertedType = ToType;
1616 return true;
1617 }
1618
Sebastian Redl576fd422009-05-10 18:38:11 +00001619 // If the left-hand-side is nullptr_t, the right side can be a null
1620 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001621 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001622 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001623 ConvertedType = ToType;
1624 return true;
1625 }
1626
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001627 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001628 if (!ToTypePtr)
1629 return false;
1630
1631 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001632 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001633 ConvertedType = ToType;
1634 return true;
1635 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001636
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001637 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001638 // , including objective-c pointers.
1639 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001640 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1641 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001642 ConvertedType = BuildSimilarlyQualifiedPointerType(
1643 FromType->getAs<ObjCObjectPointerType>(),
1644 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001645 ToType, Context);
1646 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001647 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001648 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001649 if (!FromTypePtr)
1650 return false;
1651
1652 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001653
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001654 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001655 // pointer conversion, so don't do all of the work below.
1656 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1657 return false;
1658
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001659 // An rvalue of type "pointer to cv T," where T is an object type,
1660 // can be converted to an rvalue of type "pointer to cv void" (C++
1661 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001662 if (FromPointeeType->isIncompleteOrObjectType() &&
1663 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001664 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001665 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001666 ToType, Context,
1667 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001668 return true;
1669 }
1670
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001671 // MSVC allows implicit function to void* type conversion.
Francois Pichet0706d202011-09-17 17:15:52 +00001672 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001673 ToPointeeType->isVoidType()) {
1674 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1675 ToPointeeType,
1676 ToType, Context);
1677 return true;
1678 }
1679
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001680 // When we're overloading in C, we allow a special kind of pointer
1681 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001682 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001683 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001684 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001685 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001686 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001687 return true;
1688 }
1689
Douglas Gregor5c407d92008-10-23 00:40:37 +00001690 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001691 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001692 // An rvalue of type "pointer to cv D," where D is a class type,
1693 // can be converted to an rvalue of type "pointer to cv B," where
1694 // B is a base class (clause 10) of D. If B is an inaccessible
1695 // (clause 11) or ambiguous (10.2) base class of D, a program that
1696 // necessitates this conversion is ill-formed. The result of the
1697 // conversion is a pointer to the base class sub-object of the
1698 // derived class object. The null pointer value is converted to
1699 // the null pointer value of the destination type.
1700 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001701 // Note that we do not check for ambiguity or inaccessibility
1702 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001703 if (getLangOptions().CPlusPlus &&
1704 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001705 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001706 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001707 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001708 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001709 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001710 ToType, Context);
1711 return true;
1712 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001713
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001714 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1715 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1716 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1717 ToPointeeType,
1718 ToType, Context);
1719 return true;
1720 }
1721
Douglas Gregora119f102008-12-19 19:13:09 +00001722 return false;
1723}
Douglas Gregoraec25842011-04-26 23:16:46 +00001724
1725/// \brief Adopt the given qualifiers for the given type.
1726static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1727 Qualifiers TQs = T.getQualifiers();
1728
1729 // Check whether qualifiers already match.
1730 if (TQs == Qs)
1731 return T;
1732
1733 if (Qs.compatiblyIncludes(TQs))
1734 return Context.getQualifiedType(T, Qs);
1735
1736 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1737}
Douglas Gregora119f102008-12-19 19:13:09 +00001738
1739/// isObjCPointerConversion - Determines whether this is an
1740/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1741/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001742bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001743 QualType& ConvertedType,
1744 bool &IncompatibleObjC) {
1745 if (!getLangOptions().ObjC1)
1746 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001747
Douglas Gregoraec25842011-04-26 23:16:46 +00001748 // The set of qualifiers on the type we're converting from.
1749 Qualifiers FromQualifiers = FromType.getQualifiers();
1750
Steve Naroff7cae42b2009-07-10 23:34:53 +00001751 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001752 const ObjCObjectPointerType* ToObjCPtr =
1753 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001754 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001755 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001756
Steve Naroff7cae42b2009-07-10 23:34:53 +00001757 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001758 // If the pointee types are the same (ignoring qualifications),
1759 // then this is not a pointer conversion.
1760 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1761 FromObjCPtr->getPointeeType()))
1762 return false;
1763
Douglas Gregoraec25842011-04-26 23:16:46 +00001764 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00001765 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001766 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001767 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001768 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001769 return true;
1770 }
1771 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001772 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001773 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001774 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001775 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001776 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001777 return true;
1778 }
1779 // Objective C++: We're able to convert from a pointer to an
1780 // interface to a pointer to a different interface.
1781 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001782 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1783 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1784 if (getLangOptions().CPlusPlus && LHS && RHS &&
1785 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1786 FromObjCPtr->getPointeeType()))
1787 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001788 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001789 ToObjCPtr->getPointeeType(),
1790 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001791 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001792 return true;
1793 }
1794
1795 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1796 // Okay: this is some kind of implicit downcast of Objective-C
1797 // interfaces, which is permitted. However, we're going to
1798 // complain about it.
1799 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001800 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001801 ToObjCPtr->getPointeeType(),
1802 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001803 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001804 return true;
1805 }
Mike Stump11289f42009-09-09 15:08:12 +00001806 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001807 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001808 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001809 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001810 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001811 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001812 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001813 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001814 // to a block pointer type.
1815 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001816 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001817 return true;
1818 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001819 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001821 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001822 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001823 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001824 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00001825 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001826 return true;
1827 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001828 else
Douglas Gregora119f102008-12-19 19:13:09 +00001829 return false;
1830
Douglas Gregor033f56d2008-12-23 00:53:59 +00001831 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001832 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001833 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001834 else if (const BlockPointerType *FromBlockPtr =
1835 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001836 FromPointeeType = FromBlockPtr->getPointeeType();
1837 else
Douglas Gregora119f102008-12-19 19:13:09 +00001838 return false;
1839
Douglas Gregora119f102008-12-19 19:13:09 +00001840 // If we have pointers to pointers, recursively check whether this
1841 // is an Objective-C conversion.
1842 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1843 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1844 IncompatibleObjC)) {
1845 // We always complain about this conversion.
1846 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001847 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001848 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001849 return true;
1850 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001851 // Allow conversion of pointee being objective-c pointer to another one;
1852 // as in I* to id.
1853 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1854 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1855 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1856 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00001857
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001858 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001859 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001860 return true;
1861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001862
Douglas Gregor033f56d2008-12-23 00:53:59 +00001863 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001864 // differences in the argument and result types are in Objective-C
1865 // pointer conversions. If so, we permit the conversion (but
1866 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001867 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001868 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001869 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001870 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001871 if (FromFunctionType && ToFunctionType) {
1872 // If the function types are exactly the same, this isn't an
1873 // Objective-C pointer conversion.
1874 if (Context.getCanonicalType(FromPointeeType)
1875 == Context.getCanonicalType(ToPointeeType))
1876 return false;
1877
1878 // Perform the quick checks that will tell us whether these
1879 // function types are obviously different.
1880 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1881 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1882 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1883 return false;
1884
1885 bool HasObjCConversion = false;
1886 if (Context.getCanonicalType(FromFunctionType->getResultType())
1887 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1888 // Okay, the types match exactly. Nothing to do.
1889 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1890 ToFunctionType->getResultType(),
1891 ConvertedType, IncompatibleObjC)) {
1892 // Okay, we have an Objective-C pointer conversion.
1893 HasObjCConversion = true;
1894 } else {
1895 // Function types are too different. Abort.
1896 return false;
1897 }
Mike Stump11289f42009-09-09 15:08:12 +00001898
Douglas Gregora119f102008-12-19 19:13:09 +00001899 // Check argument types.
1900 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1901 ArgIdx != NumArgs; ++ArgIdx) {
1902 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1903 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1904 if (Context.getCanonicalType(FromArgType)
1905 == Context.getCanonicalType(ToArgType)) {
1906 // Okay, the types match exactly. Nothing to do.
1907 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1908 ConvertedType, IncompatibleObjC)) {
1909 // Okay, we have an Objective-C pointer conversion.
1910 HasObjCConversion = true;
1911 } else {
1912 // Argument types are too different. Abort.
1913 return false;
1914 }
1915 }
1916
1917 if (HasObjCConversion) {
1918 // We had an Objective-C conversion. Allow this pointer
1919 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00001920 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001921 IncompatibleObjC = true;
1922 return true;
1923 }
1924 }
1925
Sebastian Redl72b597d2009-01-25 19:43:20 +00001926 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001927}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001928
John McCall31168b02011-06-15 23:02:42 +00001929/// \brief Determine whether this is an Objective-C writeback conversion,
1930/// used for parameter passing when performing automatic reference counting.
1931///
1932/// \param FromType The type we're converting form.
1933///
1934/// \param ToType The type we're converting to.
1935///
1936/// \param ConvertedType The type that will be produced after applying
1937/// this conversion.
1938bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
1939 QualType &ConvertedType) {
1940 if (!getLangOptions().ObjCAutoRefCount ||
1941 Context.hasSameUnqualifiedType(FromType, ToType))
1942 return false;
1943
1944 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
1945 QualType ToPointee;
1946 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
1947 ToPointee = ToPointer->getPointeeType();
1948 else
1949 return false;
1950
1951 Qualifiers ToQuals = ToPointee.getQualifiers();
1952 if (!ToPointee->isObjCLifetimeType() ||
1953 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
1954 !ToQuals.withoutObjCGLifetime().empty())
1955 return false;
1956
1957 // Argument must be a pointer to __strong to __weak.
1958 QualType FromPointee;
1959 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
1960 FromPointee = FromPointer->getPointeeType();
1961 else
1962 return false;
1963
1964 Qualifiers FromQuals = FromPointee.getQualifiers();
1965 if (!FromPointee->isObjCLifetimeType() ||
1966 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
1967 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
1968 return false;
1969
1970 // Make sure that we have compatible qualifiers.
1971 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
1972 if (!ToQuals.compatiblyIncludes(FromQuals))
1973 return false;
1974
1975 // Remove qualifiers from the pointee type we're converting from; they
1976 // aren't used in the compatibility check belong, and we'll be adding back
1977 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
1978 FromPointee = FromPointee.getUnqualifiedType();
1979
1980 // The unqualified form of the pointee types must be compatible.
1981 ToPointee = ToPointee.getUnqualifiedType();
1982 bool IncompatibleObjC;
1983 if (Context.typesAreCompatible(FromPointee, ToPointee))
1984 FromPointee = ToPointee;
1985 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
1986 IncompatibleObjC))
1987 return false;
1988
1989 /// \brief Construct the type we're converting to, which is a pointer to
1990 /// __autoreleasing pointee.
1991 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
1992 ConvertedType = Context.getPointerType(FromPointee);
1993 return true;
1994}
1995
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001996bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
1997 QualType& ConvertedType) {
1998 QualType ToPointeeType;
1999 if (const BlockPointerType *ToBlockPtr =
2000 ToType->getAs<BlockPointerType>())
2001 ToPointeeType = ToBlockPtr->getPointeeType();
2002 else
2003 return false;
2004
2005 QualType FromPointeeType;
2006 if (const BlockPointerType *FromBlockPtr =
2007 FromType->getAs<BlockPointerType>())
2008 FromPointeeType = FromBlockPtr->getPointeeType();
2009 else
2010 return false;
2011 // We have pointer to blocks, check whether the only
2012 // differences in the argument and result types are in Objective-C
2013 // pointer conversions. If so, we permit the conversion.
2014
2015 const FunctionProtoType *FromFunctionType
2016 = FromPointeeType->getAs<FunctionProtoType>();
2017 const FunctionProtoType *ToFunctionType
2018 = ToPointeeType->getAs<FunctionProtoType>();
2019
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002020 if (!FromFunctionType || !ToFunctionType)
2021 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002022
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002023 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002024 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002025
2026 // Perform the quick checks that will tell us whether these
2027 // function types are obviously different.
2028 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2029 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2030 return false;
2031
2032 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2033 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2034 if (FromEInfo != ToEInfo)
2035 return false;
2036
2037 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002038 if (Context.hasSameType(FromFunctionType->getResultType(),
2039 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002040 // Okay, the types match exactly. Nothing to do.
2041 } else {
2042 QualType RHS = FromFunctionType->getResultType();
2043 QualType LHS = ToFunctionType->getResultType();
2044 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2045 !RHS.hasQualifiers() && LHS.hasQualifiers())
2046 LHS = LHS.getUnqualifiedType();
2047
2048 if (Context.hasSameType(RHS,LHS)) {
2049 // OK exact match.
2050 } else if (isObjCPointerConversion(RHS, LHS,
2051 ConvertedType, IncompatibleObjC)) {
2052 if (IncompatibleObjC)
2053 return false;
2054 // Okay, we have an Objective-C pointer conversion.
2055 }
2056 else
2057 return false;
2058 }
2059
2060 // Check argument types.
2061 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2062 ArgIdx != NumArgs; ++ArgIdx) {
2063 IncompatibleObjC = false;
2064 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2065 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2066 if (Context.hasSameType(FromArgType, ToArgType)) {
2067 // Okay, the types match exactly. Nothing to do.
2068 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2069 ConvertedType, IncompatibleObjC)) {
2070 if (IncompatibleObjC)
2071 return false;
2072 // Okay, we have an Objective-C pointer conversion.
2073 } else
2074 // Argument types are too different. Abort.
2075 return false;
2076 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002077 if (LangOpts.ObjCAutoRefCount &&
2078 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2079 ToFunctionType))
2080 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002081
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002082 ConvertedType = ToType;
2083 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002084}
2085
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002086/// FunctionArgTypesAreEqual - This routine checks two function proto types
2087/// for equlity of their argument types. Caller has already checked that
2088/// they have same number of arguments. This routine assumes that Objective-C
2089/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002090bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00002091 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002092 if (!getLangOptions().ObjC1)
2093 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2094 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002095
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002096 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2097 N = NewType->arg_type_begin(),
2098 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2099 QualType ToType = (*O);
2100 QualType FromType = (*N);
2101 if (ToType != FromType) {
2102 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2103 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002104 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2105 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2106 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2107 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002108 continue;
2109 }
John McCall8b07ec22010-05-15 11:32:37 +00002110 else if (const ObjCObjectPointerType *PTTo =
2111 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002112 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002113 FromType->getAs<ObjCObjectPointerType>())
2114 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2115 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002116 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002117 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002118 }
2119 }
2120 return true;
2121}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002122
Douglas Gregor39c16d42008-10-24 04:54:22 +00002123/// CheckPointerConversion - Check the pointer conversion from the
2124/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002125/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002126/// conversions for which IsPointerConversion has already returned
2127/// true. It returns true and produces a diagnostic if there was an
2128/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002129bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002130 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002131 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002132 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002133 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002134 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002135
John McCall8cb679e2010-11-15 09:13:47 +00002136 Kind = CK_BitCast;
2137
Chandler Carruthffab8732011-04-09 07:32:05 +00002138 if (!IsCStyleOrFunctionalCast &&
2139 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2140 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2141 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002142 PDiag(diag::warn_impcast_bool_to_null_pointer)
2143 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002144
John McCall9320b872011-09-09 05:25:32 +00002145 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2146 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002147 QualType FromPointeeType = FromPtrType->getPointeeType(),
2148 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002149
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002150 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2151 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002152 // We must have a derived-to-base conversion. Check an
2153 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002154 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2155 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002156 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002157 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002158 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002159
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002160 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002161 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002162 }
2163 }
John McCall9320b872011-09-09 05:25:32 +00002164 } else if (const ObjCObjectPointerType *ToPtrType =
2165 ToType->getAs<ObjCObjectPointerType>()) {
2166 if (const ObjCObjectPointerType *FromPtrType =
2167 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002168 // Objective-C++ conversions are always okay.
2169 // FIXME: We should have a different class of conversions for the
2170 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002171 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002172 return false;
John McCall9320b872011-09-09 05:25:32 +00002173 } else if (FromType->isBlockPointerType()) {
2174 Kind = CK_BlockPointerToObjCPointerCast;
2175 } else {
2176 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002177 }
John McCall9320b872011-09-09 05:25:32 +00002178 } else if (ToType->isBlockPointerType()) {
2179 if (!FromType->isBlockPointerType())
2180 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002181 }
John McCall8cb679e2010-11-15 09:13:47 +00002182
2183 // We shouldn't fall into this case unless it's valid for other
2184 // reasons.
2185 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2186 Kind = CK_NullToPointer;
2187
Douglas Gregor39c16d42008-10-24 04:54:22 +00002188 return false;
2189}
2190
Sebastian Redl72b597d2009-01-25 19:43:20 +00002191/// IsMemberPointerConversion - Determines whether the conversion of the
2192/// expression From, which has the (possibly adjusted) type FromType, can be
2193/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2194/// If so, returns true and places the converted type (that might differ from
2195/// ToType in its cv-qualifiers at some level) into ConvertedType.
2196bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002197 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002198 bool InOverloadResolution,
2199 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002200 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002201 if (!ToTypePtr)
2202 return false;
2203
2204 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002205 if (From->isNullPointerConstant(Context,
2206 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2207 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002208 ConvertedType = ToType;
2209 return true;
2210 }
2211
2212 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002213 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002214 if (!FromTypePtr)
2215 return false;
2216
2217 // A pointer to member of B can be converted to a pointer to member of D,
2218 // where D is derived from B (C++ 4.11p2).
2219 QualType FromClass(FromTypePtr->getClass(), 0);
2220 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002221
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002222 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2223 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2224 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002225 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2226 ToClass.getTypePtr());
2227 return true;
2228 }
2229
2230 return false;
2231}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002232
Sebastian Redl72b597d2009-01-25 19:43:20 +00002233/// CheckMemberPointerConversion - Check the member pointer conversion from the
2234/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002235/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002236/// for which IsMemberPointerConversion has already returned true. It returns
2237/// true and produces a diagnostic if there was an error, or returns false
2238/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002239bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002240 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002241 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002242 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002243 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002244 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002245 if (!FromPtrType) {
2246 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002247 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002248 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002249 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002250 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002251 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002252 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002253
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002254 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002255 assert(ToPtrType && "No member pointer cast has a target type "
2256 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002257
Sebastian Redled8f2002009-01-28 18:33:18 +00002258 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2259 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002260
Sebastian Redled8f2002009-01-28 18:33:18 +00002261 // FIXME: What about dependent types?
2262 assert(FromClass->isRecordType() && "Pointer into non-class.");
2263 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002264
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002265 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002266 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002267 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2268 assert(DerivationOkay &&
2269 "Should not have been called if derivation isn't OK.");
2270 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002271
Sebastian Redled8f2002009-01-28 18:33:18 +00002272 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2273 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002274 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2275 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2276 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2277 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002278 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002279
Douglas Gregor89ee6822009-02-28 01:32:25 +00002280 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002281 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2282 << FromClass << ToClass << QualType(VBase, 0)
2283 << From->getSourceRange();
2284 return true;
2285 }
2286
John McCall5b0829a2010-02-10 09:31:12 +00002287 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002288 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2289 Paths.front(),
2290 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002291
Anders Carlssond7923c62009-08-22 23:33:40 +00002292 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002293 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002294 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002295 return false;
2296}
2297
Douglas Gregor9a657932008-10-21 23:43:52 +00002298/// IsQualificationConversion - Determines whether the conversion from
2299/// an rvalue of type FromType to ToType is a qualification conversion
2300/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002301///
2302/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2303/// when the qualification conversion involves a change in the Objective-C
2304/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002305bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002306Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002307 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002308 FromType = Context.getCanonicalType(FromType);
2309 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002310 ObjCLifetimeConversion = false;
2311
Douglas Gregor9a657932008-10-21 23:43:52 +00002312 // If FromType and ToType are the same type, this is not a
2313 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002314 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002315 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002316
Douglas Gregor9a657932008-10-21 23:43:52 +00002317 // (C++ 4.4p4):
2318 // A conversion can add cv-qualifiers at levels other than the first
2319 // in multi-level pointers, subject to the following rules: [...]
2320 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002321 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002322 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002323 // Within each iteration of the loop, we check the qualifiers to
2324 // determine if this still looks like a qualification
2325 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002326 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002327 // until there are no more pointers or pointers-to-members left to
2328 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002329 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002330
Douglas Gregor90609aa2011-04-25 18:40:17 +00002331 Qualifiers FromQuals = FromType.getQualifiers();
2332 Qualifiers ToQuals = ToType.getQualifiers();
2333
John McCall31168b02011-06-15 23:02:42 +00002334 // Objective-C ARC:
2335 // Check Objective-C lifetime conversions.
2336 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2337 UnwrappedAnyPointer) {
2338 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2339 ObjCLifetimeConversion = true;
2340 FromQuals.removeObjCLifetime();
2341 ToQuals.removeObjCLifetime();
2342 } else {
2343 // Qualification conversions cannot cast between different
2344 // Objective-C lifetime qualifiers.
2345 return false;
2346 }
2347 }
2348
Douglas Gregorf30053d2011-05-08 06:09:53 +00002349 // Allow addition/removal of GC attributes but not changing GC attributes.
2350 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2351 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2352 FromQuals.removeObjCGCAttr();
2353 ToQuals.removeObjCGCAttr();
2354 }
2355
Douglas Gregor9a657932008-10-21 23:43:52 +00002356 // -- for every j > 0, if const is in cv 1,j then const is in cv
2357 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002358 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002359 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002360
Douglas Gregor9a657932008-10-21 23:43:52 +00002361 // -- if the cv 1,j and cv 2,j are different, then const is in
2362 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002363 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002364 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002365 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002366
Douglas Gregor9a657932008-10-21 23:43:52 +00002367 // Keep track of whether all prior cv-qualifiers in the "to" type
2368 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002369 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002370 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002371 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002372
2373 // We are left with FromType and ToType being the pointee types
2374 // after unwrapping the original FromType and ToType the same number
2375 // of types. If we unwrapped any pointers, and if FromType and
2376 // ToType have the same unqualified type (since we checked
2377 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002378 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002379}
2380
Douglas Gregor576e98c2009-01-30 23:27:23 +00002381/// Determines whether there is a user-defined conversion sequence
2382/// (C++ [over.ics.user]) that converts expression From to the type
2383/// ToType. If such a conversion exists, User will contain the
2384/// user-defined conversion sequence that performs such a conversion
2385/// and this routine will return true. Otherwise, this routine returns
2386/// false and User is unspecified.
2387///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002388/// \param AllowExplicit true if the conversion should consider C++0x
2389/// "explicit" conversion functions as well as non-explicit conversion
2390/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002391static OverloadingResult
2392IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2393 UserDefinedConversionSequence& User,
2394 OverloadCandidateSet& CandidateSet,
2395 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002396 // Whether we will only visit constructors.
2397 bool ConstructorsOnly = false;
2398
2399 // If the type we are conversion to is a class type, enumerate its
2400 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002401 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002402 // C++ [over.match.ctor]p1:
2403 // When objects of class type are direct-initialized (8.5), or
2404 // copy-initialized from an expression of the same or a
2405 // derived class type (8.5), overload resolution selects the
2406 // constructor. [...] For copy-initialization, the candidate
2407 // functions are all the converting constructors (12.3.1) of
2408 // that class. The argument list is the expression-list within
2409 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002410 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002411 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002412 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002413 ConstructorsOnly = true;
2414
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002415 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2416 // RequireCompleteType may have returned true due to some invalid decl
2417 // during template instantiation, but ToType may be complete enough now
2418 // to try to recover.
2419 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002420 // We're not going to find any constructors.
2421 } else if (CXXRecordDecl *ToRecordDecl
2422 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002423 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002424 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002425 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002426 NamedDecl *D = *Con;
2427 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2428
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002429 // Find the constructor (which may be a template).
2430 CXXConstructorDecl *Constructor = 0;
2431 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002432 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002433 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002434 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002435 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2436 else
John McCalla0296f72010-03-19 07:35:19 +00002437 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002438
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002439 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002440 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002441 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002442 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2443 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002444 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002445 /*SuppressUserConversions=*/
2446 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002447 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002448 // Allow one user-defined conversion when user specifies a
2449 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002450 S.AddOverloadCandidate(Constructor, FoundDecl,
2451 &From, 1, CandidateSet,
2452 /*SuppressUserConversions=*/
2453 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002454 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002455 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002456 }
2457 }
2458
Douglas Gregor5ab11652010-04-17 22:01:05 +00002459 // Enumerate conversion functions, if we're allowed to.
2460 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002461 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2462 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002463 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002464 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002465 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002466 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002467 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2468 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002469 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002470 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002471 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002472 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002473 DeclAccessPair FoundDecl = I.getPair();
2474 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002475 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2476 if (isa<UsingShadowDecl>(D))
2477 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2478
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002479 CXXConversionDecl *Conv;
2480 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002481 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2482 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002483 else
John McCallda4458e2010-03-31 01:36:47 +00002484 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002485
2486 if (AllowExplicit || !Conv->isExplicit()) {
2487 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002488 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2489 ActingContext, From, ToType,
2490 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002491 else
John McCall5c32be02010-08-24 20:38:10 +00002492 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2493 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002494 }
2495 }
2496 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002497 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002498
2499 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002500 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002501 case OR_Success:
2502 // Record the standard conversion we used and the conversion function.
2503 if (CXXConstructorDecl *Constructor
2504 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002505 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2506
John McCall5c32be02010-08-24 20:38:10 +00002507 // C++ [over.ics.user]p1:
2508 // If the user-defined conversion is specified by a
2509 // constructor (12.3.1), the initial standard conversion
2510 // sequence converts the source type to the type required by
2511 // the argument of the constructor.
2512 //
2513 QualType ThisType = Constructor->getThisType(S.Context);
2514 if (Best->Conversions[0].isEllipsis())
2515 User.EllipsisConversion = true;
2516 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002517 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002518 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002519 }
John McCall5c32be02010-08-24 20:38:10 +00002520 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00002521 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002522 User.After.setAsIdentityConversion();
2523 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2524 User.After.setAllToTypes(ToType);
2525 return OR_Success;
2526 } else if (CXXConversionDecl *Conversion
2527 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002528 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2529
John McCall5c32be02010-08-24 20:38:10 +00002530 // C++ [over.ics.user]p1:
2531 //
2532 // [...] If the user-defined conversion is specified by a
2533 // conversion function (12.3.2), the initial standard
2534 // conversion sequence converts the source type to the
2535 // implicit object parameter of the conversion function.
2536 User.Before = Best->Conversions[0].Standard;
2537 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00002538 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002539 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002540
John McCall5c32be02010-08-24 20:38:10 +00002541 // C++ [over.ics.user]p2:
2542 // The second standard conversion sequence converts the
2543 // result of the user-defined conversion to the target type
2544 // for the sequence. Since an implicit conversion sequence
2545 // is an initialization, the special rules for
2546 // initialization by user-defined conversion apply when
2547 // selecting the best user-defined conversion for a
2548 // user-defined conversion sequence (see 13.3.3 and
2549 // 13.3.3.1).
2550 User.After = Best->FinalConversion;
2551 return OR_Success;
2552 } else {
2553 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002554 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002555 }
2556
John McCall5c32be02010-08-24 20:38:10 +00002557 case OR_No_Viable_Function:
2558 return OR_No_Viable_Function;
2559 case OR_Deleted:
2560 // No conversion here! We're done.
2561 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002562
John McCall5c32be02010-08-24 20:38:10 +00002563 case OR_Ambiguous:
2564 return OR_Ambiguous;
2565 }
2566
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002567 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002568}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002569
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002570bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002571Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002572 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002573 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002574 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002575 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002576 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002577 if (OvResult == OR_Ambiguous)
2578 Diag(From->getSourceRange().getBegin(),
2579 diag::err_typecheck_ambiguous_condition)
2580 << From->getType() << ToType << From->getSourceRange();
2581 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2582 Diag(From->getSourceRange().getBegin(),
2583 diag::err_typecheck_nonviable_condition)
2584 << From->getType() << ToType << From->getSourceRange();
2585 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002586 return false;
John McCall5c32be02010-08-24 20:38:10 +00002587 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002588 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002589}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002590
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002591/// CompareImplicitConversionSequences - Compare two implicit
2592/// conversion sequences to determine whether one is better than the
2593/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002594static ImplicitConversionSequence::CompareKind
2595CompareImplicitConversionSequences(Sema &S,
2596 const ImplicitConversionSequence& ICS1,
2597 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002598{
2599 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2600 // conversion sequences (as defined in 13.3.3.1)
2601 // -- a standard conversion sequence (13.3.3.1.1) is a better
2602 // conversion sequence than a user-defined conversion sequence or
2603 // an ellipsis conversion sequence, and
2604 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2605 // conversion sequence than an ellipsis conversion sequence
2606 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002607 //
John McCall0d1da222010-01-12 00:44:57 +00002608 // C++0x [over.best.ics]p10:
2609 // For the purpose of ranking implicit conversion sequences as
2610 // described in 13.3.3.2, the ambiguous conversion sequence is
2611 // treated as a user-defined sequence that is indistinguishable
2612 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002613 if (ICS1.getKindRank() < ICS2.getKindRank())
2614 return ImplicitConversionSequence::Better;
2615 else if (ICS2.getKindRank() < ICS1.getKindRank())
2616 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002617
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002618 // The following checks require both conversion sequences to be of
2619 // the same kind.
2620 if (ICS1.getKind() != ICS2.getKind())
2621 return ImplicitConversionSequence::Indistinguishable;
2622
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002623 // Two implicit conversion sequences of the same form are
2624 // indistinguishable conversion sequences unless one of the
2625 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002626 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002627 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002628 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002629 // User-defined conversion sequence U1 is a better conversion
2630 // sequence than another user-defined conversion sequence U2 if
2631 // they contain the same user-defined conversion function or
2632 // constructor and if the second standard conversion sequence of
2633 // U1 is better than the second standard conversion sequence of
2634 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002635 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002636 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002637 return CompareStandardConversionSequences(S,
2638 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002639 ICS2.UserDefined.After);
2640 }
2641
2642 return ImplicitConversionSequence::Indistinguishable;
2643}
2644
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002645static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2646 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2647 Qualifiers Quals;
2648 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002649 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002650 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002651
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002652 return Context.hasSameUnqualifiedType(T1, T2);
2653}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002654
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002655// Per 13.3.3.2p3, compare the given standard conversion sequences to
2656// determine if one is a proper subset of the other.
2657static ImplicitConversionSequence::CompareKind
2658compareStandardConversionSubsets(ASTContext &Context,
2659 const StandardConversionSequence& SCS1,
2660 const StandardConversionSequence& SCS2) {
2661 ImplicitConversionSequence::CompareKind Result
2662 = ImplicitConversionSequence::Indistinguishable;
2663
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002664 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002665 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00002666 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2667 return ImplicitConversionSequence::Better;
2668 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2669 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002670
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002671 if (SCS1.Second != SCS2.Second) {
2672 if (SCS1.Second == ICK_Identity)
2673 Result = ImplicitConversionSequence::Better;
2674 else if (SCS2.Second == ICK_Identity)
2675 Result = ImplicitConversionSequence::Worse;
2676 else
2677 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002678 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002679 return ImplicitConversionSequence::Indistinguishable;
2680
2681 if (SCS1.Third == SCS2.Third) {
2682 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2683 : ImplicitConversionSequence::Indistinguishable;
2684 }
2685
2686 if (SCS1.Third == ICK_Identity)
2687 return Result == ImplicitConversionSequence::Worse
2688 ? ImplicitConversionSequence::Indistinguishable
2689 : ImplicitConversionSequence::Better;
2690
2691 if (SCS2.Third == ICK_Identity)
2692 return Result == ImplicitConversionSequence::Better
2693 ? ImplicitConversionSequence::Indistinguishable
2694 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002695
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002696 return ImplicitConversionSequence::Indistinguishable;
2697}
2698
Douglas Gregore696ebb2011-01-26 14:52:12 +00002699/// \brief Determine whether one of the given reference bindings is better
2700/// than the other based on what kind of bindings they are.
2701static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2702 const StandardConversionSequence &SCS2) {
2703 // C++0x [over.ics.rank]p3b4:
2704 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2705 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002706 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002707 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002708 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002709 // reference*.
2710 //
2711 // FIXME: Rvalue references. We're going rogue with the above edits,
2712 // because the semantics in the current C++0x working paper (N3225 at the
2713 // time of this writing) break the standard definition of std::forward
2714 // and std::reference_wrapper when dealing with references to functions.
2715 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002716 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2717 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2718 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002719
Douglas Gregore696ebb2011-01-26 14:52:12 +00002720 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2721 SCS2.IsLvalueReference) ||
2722 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2723 !SCS2.IsLvalueReference);
2724}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002725
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002726/// CompareStandardConversionSequences - Compare two standard
2727/// conversion sequences to determine whether one is better than the
2728/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002729static ImplicitConversionSequence::CompareKind
2730CompareStandardConversionSequences(Sema &S,
2731 const StandardConversionSequence& SCS1,
2732 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002733{
2734 // Standard conversion sequence S1 is a better conversion sequence
2735 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2736
2737 // -- S1 is a proper subsequence of S2 (comparing the conversion
2738 // sequences in the canonical form defined by 13.3.3.1.1,
2739 // excluding any Lvalue Transformation; the identity conversion
2740 // sequence is considered to be a subsequence of any
2741 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002742 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002743 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002744 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002745
2746 // -- the rank of S1 is better than the rank of S2 (by the rules
2747 // defined below), or, if not that,
2748 ImplicitConversionRank Rank1 = SCS1.getRank();
2749 ImplicitConversionRank Rank2 = SCS2.getRank();
2750 if (Rank1 < Rank2)
2751 return ImplicitConversionSequence::Better;
2752 else if (Rank2 < Rank1)
2753 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002754
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002755 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2756 // are indistinguishable unless one of the following rules
2757 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002758
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002759 // A conversion that is not a conversion of a pointer, or
2760 // pointer to member, to bool is better than another conversion
2761 // that is such a conversion.
2762 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2763 return SCS2.isPointerConversionToBool()
2764 ? ImplicitConversionSequence::Better
2765 : ImplicitConversionSequence::Worse;
2766
Douglas Gregor5c407d92008-10-23 00:40:37 +00002767 // C++ [over.ics.rank]p4b2:
2768 //
2769 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002770 // conversion of B* to A* is better than conversion of B* to
2771 // void*, and conversion of A* to void* is better than conversion
2772 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002773 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002774 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002775 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002776 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002777 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2778 // Exactly one of the conversion sequences is a conversion to
2779 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002780 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2781 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002782 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2783 // Neither conversion sequence converts to a void pointer; compare
2784 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002785 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002786 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002787 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002788 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2789 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002790 // Both conversion sequences are conversions to void
2791 // pointers. Compare the source types to determine if there's an
2792 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002793 QualType FromType1 = SCS1.getFromType();
2794 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002795
2796 // Adjust the types we're converting from via the array-to-pointer
2797 // conversion, if we need to.
2798 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002799 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002800 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002801 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002802
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002803 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2804 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002805
John McCall5c32be02010-08-24 20:38:10 +00002806 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002807 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002808 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002809 return ImplicitConversionSequence::Worse;
2810
2811 // Objective-C++: If one interface is more specific than the
2812 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002813 const ObjCObjectPointerType* FromObjCPtr1
2814 = FromType1->getAs<ObjCObjectPointerType>();
2815 const ObjCObjectPointerType* FromObjCPtr2
2816 = FromType2->getAs<ObjCObjectPointerType>();
2817 if (FromObjCPtr1 && FromObjCPtr2) {
2818 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2819 FromObjCPtr2);
2820 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2821 FromObjCPtr1);
2822 if (AssignLeft != AssignRight) {
2823 return AssignLeft? ImplicitConversionSequence::Better
2824 : ImplicitConversionSequence::Worse;
2825 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002826 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002827 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002828
2829 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2830 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002831 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002832 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002833 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002834
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002835 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002836 // Check for a better reference binding based on the kind of bindings.
2837 if (isBetterReferenceBindingKind(SCS1, SCS2))
2838 return ImplicitConversionSequence::Better;
2839 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2840 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002841
Sebastian Redlb28b4072009-03-22 23:49:27 +00002842 // C++ [over.ics.rank]p3b4:
2843 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2844 // which the references refer are the same type except for
2845 // top-level cv-qualifiers, and the type to which the reference
2846 // initialized by S2 refers is more cv-qualified than the type
2847 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002848 QualType T1 = SCS1.getToType(2);
2849 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002850 T1 = S.Context.getCanonicalType(T1);
2851 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002852 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002853 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2854 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002855 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00002856 // Objective-C++ ARC: If the references refer to objects with different
2857 // lifetimes, prefer bindings that don't change lifetime.
2858 if (SCS1.ObjCLifetimeConversionBinding !=
2859 SCS2.ObjCLifetimeConversionBinding) {
2860 return SCS1.ObjCLifetimeConversionBinding
2861 ? ImplicitConversionSequence::Worse
2862 : ImplicitConversionSequence::Better;
2863 }
2864
Chandler Carruth8e543b32010-12-12 08:17:55 +00002865 // If the type is an array type, promote the element qualifiers to the
2866 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002867 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002868 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002869 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002870 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002871 if (T2.isMoreQualifiedThan(T1))
2872 return ImplicitConversionSequence::Better;
2873 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00002874 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002875 }
2876 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002877
Francois Pichet08d2fa02011-09-18 21:37:37 +00002878 // In Microsoft mode, prefer an integral conversion to a
2879 // floating-to-integral conversion if the integral conversion
2880 // is between types of the same size.
2881 // For example:
2882 // void f(float);
2883 // void f(int);
2884 // int main {
2885 // long a;
2886 // f(a);
2887 // }
2888 // Here, MSVC will call f(int) instead of generating a compile error
2889 // as clang will do in standard mode.
2890 if (S.getLangOptions().MicrosoftMode &&
2891 SCS1.Second == ICK_Integral_Conversion &&
2892 SCS2.Second == ICK_Floating_Integral &&
2893 S.Context.getTypeSize(SCS1.getFromType()) ==
2894 S.Context.getTypeSize(SCS1.getToType(2)))
2895 return ImplicitConversionSequence::Better;
2896
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002897 return ImplicitConversionSequence::Indistinguishable;
2898}
2899
2900/// CompareQualificationConversions - Compares two standard conversion
2901/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002902/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2903ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002904CompareQualificationConversions(Sema &S,
2905 const StandardConversionSequence& SCS1,
2906 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002907 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002908 // -- S1 and S2 differ only in their qualification conversion and
2909 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2910 // cv-qualification signature of type T1 is a proper subset of
2911 // the cv-qualification signature of type T2, and S1 is not the
2912 // deprecated string literal array-to-pointer conversion (4.2).
2913 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2914 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2915 return ImplicitConversionSequence::Indistinguishable;
2916
2917 // FIXME: the example in the standard doesn't use a qualification
2918 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002919 QualType T1 = SCS1.getToType(2);
2920 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002921 T1 = S.Context.getCanonicalType(T1);
2922 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002923 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002924 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2925 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002926
2927 // If the types are the same, we won't learn anything by unwrapped
2928 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002929 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002930 return ImplicitConversionSequence::Indistinguishable;
2931
Chandler Carruth607f38e2009-12-29 07:16:59 +00002932 // If the type is an array type, promote the element qualifiers to the type
2933 // for comparison.
2934 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002935 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002936 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002937 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002938
Mike Stump11289f42009-09-09 15:08:12 +00002939 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002940 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00002941
2942 // Objective-C++ ARC:
2943 // Prefer qualification conversions not involving a change in lifetime
2944 // to qualification conversions that do not change lifetime.
2945 if (SCS1.QualificationIncludesObjCLifetime !=
2946 SCS2.QualificationIncludesObjCLifetime) {
2947 Result = SCS1.QualificationIncludesObjCLifetime
2948 ? ImplicitConversionSequence::Worse
2949 : ImplicitConversionSequence::Better;
2950 }
2951
John McCall5c32be02010-08-24 20:38:10 +00002952 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002953 // Within each iteration of the loop, we check the qualifiers to
2954 // determine if this still looks like a qualification
2955 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002956 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002957 // until there are no more pointers or pointers-to-members left
2958 // to unwrap. This essentially mimics what
2959 // IsQualificationConversion does, but here we're checking for a
2960 // strict subset of qualifiers.
2961 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2962 // The qualifiers are the same, so this doesn't tell us anything
2963 // about how the sequences rank.
2964 ;
2965 else if (T2.isMoreQualifiedThan(T1)) {
2966 // T1 has fewer qualifiers, so it could be the better sequence.
2967 if (Result == ImplicitConversionSequence::Worse)
2968 // Neither has qualifiers that are a subset of the other's
2969 // qualifiers.
2970 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002971
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002972 Result = ImplicitConversionSequence::Better;
2973 } else if (T1.isMoreQualifiedThan(T2)) {
2974 // T2 has fewer qualifiers, so it could be the better sequence.
2975 if (Result == ImplicitConversionSequence::Better)
2976 // Neither has qualifiers that are a subset of the other's
2977 // qualifiers.
2978 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002979
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002980 Result = ImplicitConversionSequence::Worse;
2981 } else {
2982 // Qualifiers are disjoint.
2983 return ImplicitConversionSequence::Indistinguishable;
2984 }
2985
2986 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002987 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002988 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002989 }
2990
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002991 // Check that the winning standard conversion sequence isn't using
2992 // the deprecated string literal array to pointer conversion.
2993 switch (Result) {
2994 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002995 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002996 Result = ImplicitConversionSequence::Indistinguishable;
2997 break;
2998
2999 case ImplicitConversionSequence::Indistinguishable:
3000 break;
3001
3002 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003003 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003004 Result = ImplicitConversionSequence::Indistinguishable;
3005 break;
3006 }
3007
3008 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003009}
3010
Douglas Gregor5c407d92008-10-23 00:40:37 +00003011/// CompareDerivedToBaseConversions - Compares two standard conversion
3012/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003013/// various kinds of derived-to-base conversions (C++
3014/// [over.ics.rank]p4b3). As part of these checks, we also look at
3015/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003016ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003017CompareDerivedToBaseConversions(Sema &S,
3018 const StandardConversionSequence& SCS1,
3019 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003020 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003021 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003022 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003023 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003024
3025 // Adjust the types we're converting from via the array-to-pointer
3026 // conversion, if we need to.
3027 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003028 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003029 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003030 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003031
3032 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003033 FromType1 = S.Context.getCanonicalType(FromType1);
3034 ToType1 = S.Context.getCanonicalType(ToType1);
3035 FromType2 = S.Context.getCanonicalType(FromType2);
3036 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003037
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003038 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003039 //
3040 // If class B is derived directly or indirectly from class A and
3041 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003042 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003043 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003044 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003045 SCS2.Second == ICK_Pointer_Conversion &&
3046 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3047 FromType1->isPointerType() && FromType2->isPointerType() &&
3048 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003049 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003050 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003051 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003052 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003053 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003054 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003055 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003056 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003057
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003058 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003059 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003060 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003061 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003062 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003063 return ImplicitConversionSequence::Worse;
3064 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003065
3066 // -- conversion of B* to A* is better than conversion of C* to A*,
3067 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003068 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003069 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003070 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003071 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003072 }
3073 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3074 SCS2.Second == ICK_Pointer_Conversion) {
3075 const ObjCObjectPointerType *FromPtr1
3076 = FromType1->getAs<ObjCObjectPointerType>();
3077 const ObjCObjectPointerType *FromPtr2
3078 = FromType2->getAs<ObjCObjectPointerType>();
3079 const ObjCObjectPointerType *ToPtr1
3080 = ToType1->getAs<ObjCObjectPointerType>();
3081 const ObjCObjectPointerType *ToPtr2
3082 = ToType2->getAs<ObjCObjectPointerType>();
3083
3084 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3085 // Apply the same conversion ranking rules for Objective-C pointer types
3086 // that we do for C++ pointers to class types. However, we employ the
3087 // Objective-C pseudo-subtyping relationship used for assignment of
3088 // Objective-C pointer types.
3089 bool FromAssignLeft
3090 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3091 bool FromAssignRight
3092 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3093 bool ToAssignLeft
3094 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3095 bool ToAssignRight
3096 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3097
3098 // A conversion to an a non-id object pointer type or qualified 'id'
3099 // type is better than a conversion to 'id'.
3100 if (ToPtr1->isObjCIdType() &&
3101 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3102 return ImplicitConversionSequence::Worse;
3103 if (ToPtr2->isObjCIdType() &&
3104 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3105 return ImplicitConversionSequence::Better;
3106
3107 // A conversion to a non-id object pointer type is better than a
3108 // conversion to a qualified 'id' type
3109 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3110 return ImplicitConversionSequence::Worse;
3111 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3112 return ImplicitConversionSequence::Better;
3113
3114 // A conversion to an a non-Class object pointer type or qualified 'Class'
3115 // type is better than a conversion to 'Class'.
3116 if (ToPtr1->isObjCClassType() &&
3117 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3118 return ImplicitConversionSequence::Worse;
3119 if (ToPtr2->isObjCClassType() &&
3120 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3121 return ImplicitConversionSequence::Better;
3122
3123 // A conversion to a non-Class object pointer type is better than a
3124 // conversion to a qualified 'Class' type.
3125 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3126 return ImplicitConversionSequence::Worse;
3127 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3128 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003129
Douglas Gregor058d3de2011-01-31 18:51:41 +00003130 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3131 if (S.Context.hasSameType(FromType1, FromType2) &&
3132 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3133 (ToAssignLeft != ToAssignRight))
3134 return ToAssignLeft? ImplicitConversionSequence::Worse
3135 : ImplicitConversionSequence::Better;
3136
3137 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3138 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3139 (FromAssignLeft != FromAssignRight))
3140 return FromAssignLeft? ImplicitConversionSequence::Better
3141 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003142 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003143 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003144
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003145 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003146 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3147 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3148 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003149 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003150 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003151 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003152 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003153 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003154 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003155 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003156 ToType2->getAs<MemberPointerType>();
3157 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3158 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3159 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3160 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3161 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3162 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3163 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3164 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003165 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003166 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003167 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003168 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003169 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003170 return ImplicitConversionSequence::Better;
3171 }
3172 // conversion of B::* to C::* is better than conversion of A::* to C::*
3173 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003174 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003175 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003176 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003177 return ImplicitConversionSequence::Worse;
3178 }
3179 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003180
Douglas Gregor5ab11652010-04-17 22:01:05 +00003181 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003182 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003183 // -- binding of an expression of type C to a reference of type
3184 // B& is better than binding an expression of type C to a
3185 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003186 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3187 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3188 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003189 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003190 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003191 return ImplicitConversionSequence::Worse;
3192 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003193
Douglas Gregor2fe98832008-11-03 19:09:14 +00003194 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003195 // -- binding of an expression of type B to a reference of type
3196 // A& is better than binding an expression of type C to a
3197 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003198 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3199 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3200 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003201 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003202 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003203 return ImplicitConversionSequence::Worse;
3204 }
3205 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003206
Douglas Gregor5c407d92008-10-23 00:40:37 +00003207 return ImplicitConversionSequence::Indistinguishable;
3208}
3209
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003210/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3211/// determine whether they are reference-related,
3212/// reference-compatible, reference-compatible with added
3213/// qualification, or incompatible, for use in C++ initialization by
3214/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3215/// type, and the first type (T1) is the pointee type of the reference
3216/// type being initialized.
3217Sema::ReferenceCompareResult
3218Sema::CompareReferenceRelationship(SourceLocation Loc,
3219 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003220 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003221 bool &ObjCConversion,
3222 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003223 assert(!OrigT1->isReferenceType() &&
3224 "T1 must be the pointee type of the reference type");
3225 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3226
3227 QualType T1 = Context.getCanonicalType(OrigT1);
3228 QualType T2 = Context.getCanonicalType(OrigT2);
3229 Qualifiers T1Quals, T2Quals;
3230 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3231 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3232
3233 // C++ [dcl.init.ref]p4:
3234 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3235 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3236 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003237 DerivedToBase = false;
3238 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003239 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003240 if (UnqualT1 == UnqualT2) {
3241 // Nothing to do.
3242 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003243 IsDerivedFrom(UnqualT2, UnqualT1))
3244 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003245 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3246 UnqualT2->isObjCObjectOrInterfaceType() &&
3247 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3248 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003249 else
3250 return Ref_Incompatible;
3251
3252 // At this point, we know that T1 and T2 are reference-related (at
3253 // least).
3254
3255 // If the type is an array type, promote the element qualifiers to the type
3256 // for comparison.
3257 if (isa<ArrayType>(T1) && T1Quals)
3258 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3259 if (isa<ArrayType>(T2) && T2Quals)
3260 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3261
3262 // C++ [dcl.init.ref]p4:
3263 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3264 // reference-related to T2 and cv1 is the same cv-qualification
3265 // as, or greater cv-qualification than, cv2. For purposes of
3266 // overload resolution, cases for which cv1 is greater
3267 // cv-qualification than cv2 are identified as
3268 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003269 //
3270 // Note that we also require equivalence of Objective-C GC and address-space
3271 // qualifiers when performing these computations, so that e.g., an int in
3272 // address space 1 is not reference-compatible with an int in address
3273 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003274 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3275 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3276 T1Quals.removeObjCLifetime();
3277 T2Quals.removeObjCLifetime();
3278 ObjCLifetimeConversion = true;
3279 }
3280
Douglas Gregord517d552011-04-28 17:56:11 +00003281 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003282 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003283 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003284 return Ref_Compatible_With_Added_Qualification;
3285 else
3286 return Ref_Related;
3287}
3288
Douglas Gregor836a7e82010-08-11 02:15:33 +00003289/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003290/// with DeclType. Return true if something definite is found.
3291static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003292FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3293 QualType DeclType, SourceLocation DeclLoc,
3294 Expr *Init, QualType T2, bool AllowRvalues,
3295 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003296 assert(T2->isRecordType() && "Can only find conversions of record types.");
3297 CXXRecordDecl *T2RecordDecl
3298 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3299
3300 OverloadCandidateSet CandidateSet(DeclLoc);
3301 const UnresolvedSetImpl *Conversions
3302 = T2RecordDecl->getVisibleConversionFunctions();
3303 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3304 E = Conversions->end(); I != E; ++I) {
3305 NamedDecl *D = *I;
3306 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3307 if (isa<UsingShadowDecl>(D))
3308 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3309
3310 FunctionTemplateDecl *ConvTemplate
3311 = dyn_cast<FunctionTemplateDecl>(D);
3312 CXXConversionDecl *Conv;
3313 if (ConvTemplate)
3314 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3315 else
3316 Conv = cast<CXXConversionDecl>(D);
3317
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003318 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003319 // explicit conversions, skip it.
3320 if (!AllowExplicit && Conv->isExplicit())
3321 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003322
Douglas Gregor836a7e82010-08-11 02:15:33 +00003323 if (AllowRvalues) {
3324 bool DerivedToBase = false;
3325 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003326 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003327
3328 // If we are initializing an rvalue reference, don't permit conversion
3329 // functions that return lvalues.
3330 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3331 const ReferenceType *RefType
3332 = Conv->getConversionType()->getAs<LValueReferenceType>();
3333 if (RefType && !RefType->getPointeeType()->isFunctionType())
3334 continue;
3335 }
3336
Douglas Gregor836a7e82010-08-11 02:15:33 +00003337 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003338 S.CompareReferenceRelationship(
3339 DeclLoc,
3340 Conv->getConversionType().getNonReferenceType()
3341 .getUnqualifiedType(),
3342 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003343 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003344 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003345 continue;
3346 } else {
3347 // If the conversion function doesn't return a reference type,
3348 // it can't be considered for this conversion. An rvalue reference
3349 // is only acceptable if its referencee is a function type.
3350
3351 const ReferenceType *RefType =
3352 Conv->getConversionType()->getAs<ReferenceType>();
3353 if (!RefType ||
3354 (!RefType->isLValueReferenceType() &&
3355 !RefType->getPointeeType()->isFunctionType()))
3356 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003357 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003358
Douglas Gregor836a7e82010-08-11 02:15:33 +00003359 if (ConvTemplate)
3360 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003361 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003362 else
3363 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003364 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003365 }
3366
3367 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003368 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003369 case OR_Success:
3370 // C++ [over.ics.ref]p1:
3371 //
3372 // [...] If the parameter binds directly to the result of
3373 // applying a conversion function to the argument
3374 // expression, the implicit conversion sequence is a
3375 // user-defined conversion sequence (13.3.3.1.2), with the
3376 // second standard conversion sequence either an identity
3377 // conversion or, if the conversion function returns an
3378 // entity of a type that is a derived class of the parameter
3379 // type, a derived-to-base Conversion.
3380 if (!Best->FinalConversion.DirectBinding)
3381 return false;
3382
Chandler Carruth30141632011-02-25 19:41:05 +00003383 if (Best->Function)
3384 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003385 ICS.setUserDefined();
3386 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3387 ICS.UserDefined.After = Best->FinalConversion;
3388 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003389 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003390 ICS.UserDefined.EllipsisConversion = false;
3391 assert(ICS.UserDefined.After.ReferenceBinding &&
3392 ICS.UserDefined.After.DirectBinding &&
3393 "Expected a direct reference binding!");
3394 return true;
3395
3396 case OR_Ambiguous:
3397 ICS.setAmbiguous();
3398 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3399 Cand != CandidateSet.end(); ++Cand)
3400 if (Cand->Viable)
3401 ICS.Ambiguous.addConversion(Cand->Function);
3402 return true;
3403
3404 case OR_No_Viable_Function:
3405 case OR_Deleted:
3406 // There was no suitable conversion, or we found a deleted
3407 // conversion; continue with other checks.
3408 return false;
3409 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003410
Eric Christopheraba9fb22010-06-30 18:36:32 +00003411 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003412}
3413
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003414/// \brief Compute an implicit conversion sequence for reference
3415/// initialization.
3416static ImplicitConversionSequence
3417TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3418 SourceLocation DeclLoc,
3419 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003420 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003421 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3422
3423 // Most paths end in a failed conversion.
3424 ImplicitConversionSequence ICS;
3425 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3426
3427 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3428 QualType T2 = Init->getType();
3429
3430 // If the initializer is the address of an overloaded function, try
3431 // to resolve the overloaded function. If all goes well, T2 is the
3432 // type of the resulting function.
3433 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3434 DeclAccessPair Found;
3435 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3436 false, Found))
3437 T2 = Fn->getType();
3438 }
3439
3440 // Compute some basic properties of the types and the initializer.
3441 bool isRValRef = DeclType->isRValueReferenceType();
3442 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003443 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003444 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003445 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003446 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003447 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003448 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003449
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003450
Sebastian Redld92badf2010-06-30 18:13:39 +00003451 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003452 // A reference to type "cv1 T1" is initialized by an expression
3453 // of type "cv2 T2" as follows:
3454
Sebastian Redld92badf2010-06-30 18:13:39 +00003455 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003456 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003457 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3458 // reference-compatible with "cv2 T2," or
3459 //
3460 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3461 if (InitCategory.isLValue() &&
3462 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003463 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003464 // When a parameter of reference type binds directly (8.5.3)
3465 // to an argument expression, the implicit conversion sequence
3466 // is the identity conversion, unless the argument expression
3467 // has a type that is a derived class of the parameter type,
3468 // in which case the implicit conversion sequence is a
3469 // derived-to-base Conversion (13.3.3.1).
3470 ICS.setStandard();
3471 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003472 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3473 : ObjCConversion? ICK_Compatible_Conversion
3474 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003475 ICS.Standard.Third = ICK_Identity;
3476 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3477 ICS.Standard.setToType(0, T2);
3478 ICS.Standard.setToType(1, T1);
3479 ICS.Standard.setToType(2, T1);
3480 ICS.Standard.ReferenceBinding = true;
3481 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003482 ICS.Standard.IsLvalueReference = !isRValRef;
3483 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3484 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003485 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003486 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003487 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003488
Sebastian Redld92badf2010-06-30 18:13:39 +00003489 // Nothing more to do: the inaccessibility/ambiguity check for
3490 // derived-to-base conversions is suppressed when we're
3491 // computing the implicit conversion sequence (C++
3492 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003493 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003494 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003495
Sebastian Redld92badf2010-06-30 18:13:39 +00003496 // -- has a class type (i.e., T2 is a class type), where T1 is
3497 // not reference-related to T2, and can be implicitly
3498 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3499 // is reference-compatible with "cv3 T3" 92) (this
3500 // conversion is selected by enumerating the applicable
3501 // conversion functions (13.3.1.6) and choosing the best
3502 // one through overload resolution (13.3)),
3503 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003504 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003505 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003506 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3507 Init, T2, /*AllowRvalues=*/false,
3508 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003509 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003510 }
3511 }
3512
Sebastian Redld92badf2010-06-30 18:13:39 +00003513 // -- Otherwise, the reference shall be an lvalue reference to a
3514 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003515 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003516 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003517 // We actually handle one oddity of C++ [over.ics.ref] at this
3518 // point, which is that, due to p2 (which short-circuits reference
3519 // binding by only attempting a simple conversion for non-direct
3520 // bindings) and p3's strange wording, we allow a const volatile
3521 // reference to bind to an rvalue. Hence the check for the presence
3522 // of "const" rather than checking for "const" being the only
3523 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003524 // This is also the point where rvalue references and lvalue inits no longer
3525 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003526 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003527 return ICS;
3528
Douglas Gregorf143cd52011-01-24 16:14:37 +00003529 // -- If the initializer expression
3530 //
3531 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003532 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003533 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3534 (InitCategory.isXValue() ||
3535 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3536 (InitCategory.isLValue() && T2->isFunctionType()))) {
3537 ICS.setStandard();
3538 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003539 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003540 : ObjCConversion? ICK_Compatible_Conversion
3541 : ICK_Identity;
3542 ICS.Standard.Third = ICK_Identity;
3543 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3544 ICS.Standard.setToType(0, T2);
3545 ICS.Standard.setToType(1, T1);
3546 ICS.Standard.setToType(2, T1);
3547 ICS.Standard.ReferenceBinding = true;
3548 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3549 // binding unless we're binding to a class prvalue.
3550 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3551 // allow the use of rvalue references in C++98/03 for the benefit of
3552 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003553 ICS.Standard.DirectBinding =
3554 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003555 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003556 ICS.Standard.IsLvalueReference = !isRValRef;
3557 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003558 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003559 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003560 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003561 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003562 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003563 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003564
Douglas Gregorf143cd52011-01-24 16:14:37 +00003565 // -- has a class type (i.e., T2 is a class type), where T1 is not
3566 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003567 // an xvalue, class prvalue, or function lvalue of type
3568 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003569 // "cv3 T3",
3570 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003571 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003572 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003573 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003574 // class subobject).
3575 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003576 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003577 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3578 Init, T2, /*AllowRvalues=*/true,
3579 AllowExplicit)) {
3580 // In the second case, if the reference is an rvalue reference
3581 // and the second standard conversion sequence of the
3582 // user-defined conversion sequence includes an lvalue-to-rvalue
3583 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003584 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003585 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3586 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3587
Douglas Gregor95273c32011-01-21 16:36:05 +00003588 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003589 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003590
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003591 // -- Otherwise, a temporary of type "cv1 T1" is created and
3592 // initialized from the initializer expression using the
3593 // rules for a non-reference copy initialization (8.5). The
3594 // reference is then bound to the temporary. If T1 is
3595 // reference-related to T2, cv1 must be the same
3596 // cv-qualification as, or greater cv-qualification than,
3597 // cv2; otherwise, the program is ill-formed.
3598 if (RefRelationship == Sema::Ref_Related) {
3599 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3600 // we would be reference-compatible or reference-compatible with
3601 // added qualification. But that wasn't the case, so the reference
3602 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00003603 //
3604 // Note that we only want to check address spaces and cvr-qualifiers here.
3605 // ObjC GC and lifetime qualifiers aren't important.
3606 Qualifiers T1Quals = T1.getQualifiers();
3607 Qualifiers T2Quals = T2.getQualifiers();
3608 T1Quals.removeObjCGCAttr();
3609 T1Quals.removeObjCLifetime();
3610 T2Quals.removeObjCGCAttr();
3611 T2Quals.removeObjCLifetime();
3612 if (!T1Quals.compatiblyIncludes(T2Quals))
3613 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003614 }
3615
3616 // If at least one of the types is a class type, the types are not
3617 // related, and we aren't allowed any user conversions, the
3618 // reference binding fails. This case is important for breaking
3619 // recursion, since TryImplicitConversion below will attempt to
3620 // create a temporary through the use of a copy constructor.
3621 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3622 (T1->isRecordType() || T2->isRecordType()))
3623 return ICS;
3624
Douglas Gregorcba72b12011-01-21 05:18:22 +00003625 // If T1 is reference-related to T2 and the reference is an rvalue
3626 // reference, the initializer expression shall not be an lvalue.
3627 if (RefRelationship >= Sema::Ref_Related &&
3628 isRValRef && Init->Classify(S.Context).isLValue())
3629 return ICS;
3630
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003631 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003632 // When a parameter of reference type is not bound directly to
3633 // an argument expression, the conversion sequence is the one
3634 // required to convert the argument expression to the
3635 // underlying type of the reference according to
3636 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3637 // to copy-initializing a temporary of the underlying type with
3638 // the argument expression. Any difference in top-level
3639 // cv-qualification is subsumed by the initialization itself
3640 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003641 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3642 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003643 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003644 /*CStyle=*/false,
3645 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003646
3647 // Of course, that's still a reference binding.
3648 if (ICS.isStandard()) {
3649 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003650 ICS.Standard.IsLvalueReference = !isRValRef;
3651 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3652 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003653 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003654 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003655 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003656 // Don't allow rvalue references to bind to lvalues.
3657 if (DeclType->isRValueReferenceType()) {
3658 if (const ReferenceType *RefType
3659 = ICS.UserDefined.ConversionFunction->getResultType()
3660 ->getAs<LValueReferenceType>()) {
3661 if (!RefType->getPointeeType()->isFunctionType()) {
3662 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
3663 DeclType);
3664 return ICS;
3665 }
3666 }
3667 }
3668
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003669 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00003670 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3671 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3672 ICS.UserDefined.After.BindsToRvalue = true;
3673 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3674 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003675 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003676
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003677 return ICS;
3678}
3679
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003680/// TryCopyInitialization - Try to copy-initialize a value of type
3681/// ToType from the expression From. Return the implicit conversion
3682/// sequence required to pass this argument, which may be a bad
3683/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003684/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003685/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003686static ImplicitConversionSequence
3687TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003688 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00003689 bool InOverloadResolution,
3690 bool AllowObjCWritebackConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003691 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003692 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003693 /*FIXME:*/From->getLocStart(),
3694 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003695 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003696
John McCall5c32be02010-08-24 20:38:10 +00003697 return TryImplicitConversion(S, From, ToType,
3698 SuppressUserConversions,
3699 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003700 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00003701 /*CStyle=*/false,
3702 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003703}
3704
Anna Zaks1b068122011-07-28 19:46:48 +00003705static bool TryCopyInitialization(const CanQualType FromQTy,
3706 const CanQualType ToQTy,
3707 Sema &S,
3708 SourceLocation Loc,
3709 ExprValueKind FromVK) {
3710 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
3711 ImplicitConversionSequence ICS =
3712 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
3713
3714 return !ICS.isBad();
3715}
3716
Douglas Gregor436424c2008-11-18 23:14:02 +00003717/// TryObjectArgumentInitialization - Try to initialize the object
3718/// parameter of the given member function (@c Method) from the
3719/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003720static ImplicitConversionSequence
3721TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003722 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003723 CXXMethodDecl *Method,
3724 CXXRecordDecl *ActingContext) {
3725 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003726 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3727 // const volatile object.
3728 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3729 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003730 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003731
3732 // Set up the conversion sequence as a "bad" conversion, to allow us
3733 // to exit early.
3734 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003735
3736 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003737 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003738 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003739 FromType = PT->getPointeeType();
3740
Douglas Gregor02824322011-01-26 19:30:28 +00003741 // When we had a pointer, it's implicitly dereferenced, so we
3742 // better have an lvalue.
3743 assert(FromClassification.isLValue());
3744 }
3745
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003746 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003747
Douglas Gregor02824322011-01-26 19:30:28 +00003748 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003749 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003750 // parameter is
3751 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003752 // - "lvalue reference to cv X" for functions declared without a
3753 // ref-qualifier or with the & ref-qualifier
3754 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003755 // ref-qualifier
3756 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003757 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003758 // cv-qualification on the member function declaration.
3759 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003760 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003761 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003762 // (C++ [over.match.funcs]p5). We perform a simplified version of
3763 // reference binding here, that allows class rvalues to bind to
3764 // non-constant references.
3765
Douglas Gregor02824322011-01-26 19:30:28 +00003766 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003767 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003768 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003769 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003770 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003771 ICS.setBad(BadConversionSequence::bad_qualifiers,
3772 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003773 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003774 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003775
3776 // Check that we have either the same type or a derived type. It
3777 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003778 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003779 ImplicitConversionKind SecondKind;
3780 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3781 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003782 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003783 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003784 else {
John McCall65eb8792010-02-25 01:37:24 +00003785 ICS.setBad(BadConversionSequence::unrelated_class,
3786 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003787 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003788 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003789
Douglas Gregor02824322011-01-26 19:30:28 +00003790 // Check the ref-qualifier.
3791 switch (Method->getRefQualifier()) {
3792 case RQ_None:
3793 // Do nothing; we don't care about lvalueness or rvalueness.
3794 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003795
Douglas Gregor02824322011-01-26 19:30:28 +00003796 case RQ_LValue:
3797 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3798 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003799 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003800 ImplicitParamType);
3801 return ICS;
3802 }
3803 break;
3804
3805 case RQ_RValue:
3806 if (!FromClassification.isRValue()) {
3807 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003808 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003809 ImplicitParamType);
3810 return ICS;
3811 }
3812 break;
3813 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003814
Douglas Gregor436424c2008-11-18 23:14:02 +00003815 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003816 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003817 ICS.Standard.setAsIdentityConversion();
3818 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003819 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003820 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003821 ICS.Standard.ReferenceBinding = true;
3822 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003823 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003824 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003825 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3826 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3827 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003828 return ICS;
3829}
3830
3831/// PerformObjectArgumentInitialization - Perform initialization of
3832/// the implicit object parameter for the given Method with the given
3833/// expression.
John Wiegley01296292011-04-08 18:41:53 +00003834ExprResult
3835Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003836 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003837 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003838 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003839 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003840 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003841 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003842
Douglas Gregor02824322011-01-26 19:30:28 +00003843 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003844 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003845 FromRecordType = PT->getPointeeType();
3846 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003847 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003848 } else {
3849 FromRecordType = From->getType();
3850 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003851 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003852 }
3853
John McCall6e9f8f62009-12-03 04:06:58 +00003854 // Note that we always use the true parent context when performing
3855 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003856 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003857 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3858 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003859 if (ICS.isBad()) {
3860 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3861 Qualifiers FromQs = FromRecordType.getQualifiers();
3862 Qualifiers ToQs = DestType.getQualifiers();
3863 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3864 if (CVR) {
3865 Diag(From->getSourceRange().getBegin(),
3866 diag::err_member_function_call_bad_cvr)
3867 << Method->getDeclName() << FromRecordType << (CVR - 1)
3868 << From->getSourceRange();
3869 Diag(Method->getLocation(), diag::note_previous_decl)
3870 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00003871 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003872 }
3873 }
3874
Douglas Gregor436424c2008-11-18 23:14:02 +00003875 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003876 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003877 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003878 }
Mike Stump11289f42009-09-09 15:08:12 +00003879
John Wiegley01296292011-04-08 18:41:53 +00003880 if (ICS.Standard.Second == ICK_Derived_To_Base) {
3881 ExprResult FromRes =
3882 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3883 if (FromRes.isInvalid())
3884 return ExprError();
3885 From = FromRes.take();
3886 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003887
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003888 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00003889 From = ImpCastExprToType(From, DestType, CK_NoOp,
3890 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3891 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00003892}
3893
Douglas Gregor5fb53972009-01-14 15:45:31 +00003894/// TryContextuallyConvertToBool - Attempt to contextually convert the
3895/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003896static ImplicitConversionSequence
3897TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003898 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003899 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003900 // FIXME: Are these flags correct?
3901 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003902 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003903 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003904 /*CStyle=*/false,
3905 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003906}
3907
3908/// PerformContextuallyConvertToBool - Perform a contextual conversion
3909/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00003910ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00003911 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003912 if (!ICS.isBad())
3913 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003914
Fariborz Jahanian76197412009-11-18 18:26:29 +00003915 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00003916 return Diag(From->getSourceRange().getBegin(),
3917 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003918 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00003919 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00003920}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003921
John McCallfec112d2011-09-09 06:11:02 +00003922/// dropPointerConversions - If the given standard conversion sequence
3923/// involves any pointer conversions, remove them. This may change
3924/// the result type of the conversion sequence.
3925static void dropPointerConversion(StandardConversionSequence &SCS) {
3926 if (SCS.Second == ICK_Pointer_Conversion) {
3927 SCS.Second = ICK_Identity;
3928 SCS.Third = ICK_Identity;
3929 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
3930 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003931}
John McCall5c32be02010-08-24 20:38:10 +00003932
John McCallfec112d2011-09-09 06:11:02 +00003933/// TryContextuallyConvertToObjCPointer - Attempt to contextually
3934/// convert the expression From to an Objective-C pointer type.
3935static ImplicitConversionSequence
3936TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
3937 // Do an implicit conversion to 'id'.
3938 QualType Ty = S.Context.getObjCIdType();
3939 ImplicitConversionSequence ICS
3940 = TryImplicitConversion(S, From, Ty,
3941 // FIXME: Are these flags correct?
3942 /*SuppressUserConversions=*/false,
3943 /*AllowExplicit=*/true,
3944 /*InOverloadResolution=*/false,
3945 /*CStyle=*/false,
3946 /*AllowObjCWritebackConversion=*/false);
3947
3948 // Strip off any final conversions to 'id'.
3949 switch (ICS.getKind()) {
3950 case ImplicitConversionSequence::BadConversion:
3951 case ImplicitConversionSequence::AmbiguousConversion:
3952 case ImplicitConversionSequence::EllipsisConversion:
3953 break;
3954
3955 case ImplicitConversionSequence::UserDefinedConversion:
3956 dropPointerConversion(ICS.UserDefined.After);
3957 break;
3958
3959 case ImplicitConversionSequence::StandardConversion:
3960 dropPointerConversion(ICS.Standard);
3961 break;
3962 }
3963
3964 return ICS;
3965}
3966
3967/// PerformContextuallyConvertToObjCPointer - Perform a contextual
3968/// conversion of the expression From to an Objective-C pointer type.
3969ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00003970 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00003971 ImplicitConversionSequence ICS =
3972 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003973 if (!ICS.isBad())
3974 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00003975 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003976}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003977
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003978/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003979/// enumeration type.
3980///
3981/// This routine will attempt to convert an expression of class type to an
3982/// integral or enumeration type, if that class type only has a single
3983/// conversion to an integral or enumeration type.
3984///
Douglas Gregor4799d032010-06-30 00:20:43 +00003985/// \param Loc The source location of the construct that requires the
3986/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003987///
Douglas Gregor4799d032010-06-30 00:20:43 +00003988/// \param FromE The expression we're converting from.
3989///
3990/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3991/// have integral or enumeration type.
3992///
3993/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3994/// incomplete class type.
3995///
3996/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3997/// explicit conversion function (because no implicit conversion functions
3998/// were available). This is a recovery mode.
3999///
4000/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4001/// showing which conversion was picked.
4002///
4003/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4004/// conversion function that could convert to integral or enumeration type.
4005///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004006/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004007/// usable conversion function.
4008///
4009/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4010/// function, which may be an extension in this case.
4011///
4012/// \returns The expression, converted to an integral or enumeration type if
4013/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004014ExprResult
John McCallb268a282010-08-23 23:25:46 +00004015Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004016 const PartialDiagnostic &NotIntDiag,
4017 const PartialDiagnostic &IncompleteDiag,
4018 const PartialDiagnostic &ExplicitConvDiag,
4019 const PartialDiagnostic &ExplicitConvNote,
4020 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004021 const PartialDiagnostic &AmbigNote,
4022 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004023 // We can't perform any more checking for type-dependent expressions.
4024 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004025 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004026
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004027 // If the expression already has integral or enumeration type, we're golden.
4028 QualType T = From->getType();
4029 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00004030 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004031
4032 // FIXME: Check for missing '()' if T is a function type?
4033
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004034 // 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 +00004035 // expression of integral or enumeration type.
4036 const RecordType *RecordTy = T->getAs<RecordType>();
4037 if (!RecordTy || !getLangOptions().CPlusPlus) {
4038 Diag(Loc, NotIntDiag)
4039 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004040 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004041 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004042
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004043 // We must have a complete class type.
4044 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004045 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004046
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004047 // Look for a conversion to an integral or enumeration type.
4048 UnresolvedSet<4> ViableConversions;
4049 UnresolvedSet<4> ExplicitConversions;
4050 const UnresolvedSetImpl *Conversions
4051 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004052
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004053 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004054 E = Conversions->end();
4055 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004056 ++I) {
4057 if (CXXConversionDecl *Conversion
4058 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4059 if (Conversion->getConversionType().getNonReferenceType()
4060 ->isIntegralOrEnumerationType()) {
4061 if (Conversion->isExplicit())
4062 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4063 else
4064 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4065 }
4066 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004067
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004068 switch (ViableConversions.size()) {
4069 case 0:
4070 if (ExplicitConversions.size() == 1) {
4071 DeclAccessPair Found = ExplicitConversions[0];
4072 CXXConversionDecl *Conversion
4073 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004074
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004075 // The user probably meant to invoke the given explicit
4076 // conversion; use it.
4077 QualType ConvTy
4078 = Conversion->getConversionType().getNonReferenceType();
4079 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00004080 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004081
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004082 Diag(Loc, ExplicitConvDiag)
4083 << T << ConvTy
4084 << FixItHint::CreateInsertion(From->getLocStart(),
4085 "static_cast<" + TypeStr + ">(")
4086 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4087 ")");
4088 Diag(Conversion->getLocation(), ExplicitConvNote)
4089 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004090
4091 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004092 // explicit conversion function.
4093 if (isSFINAEContext())
4094 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004095
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004096 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00004097 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
4098 if (Result.isInvalid())
4099 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004100
Douglas Gregor668443e2011-01-20 00:18:04 +00004101 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004102 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004103
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004104 // We'll complain below about a non-integral condition type.
4105 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004106
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004107 case 1: {
4108 // Apply this conversion.
4109 DeclAccessPair Found = ViableConversions[0];
4110 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004111
Douglas Gregor4799d032010-06-30 00:20:43 +00004112 CXXConversionDecl *Conversion
4113 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4114 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004115 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004116 if (ConvDiag.getDiagID()) {
4117 if (isSFINAEContext())
4118 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119
Douglas Gregor4799d032010-06-30 00:20:43 +00004120 Diag(Loc, ConvDiag)
4121 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4122 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004123
Douglas Gregor668443e2011-01-20 00:18:04 +00004124 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004125 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00004126 if (Result.isInvalid())
4127 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004128
Douglas Gregor668443e2011-01-20 00:18:04 +00004129 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004130 break;
4131 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004132
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004133 default:
4134 Diag(Loc, AmbigDiag)
4135 << T << From->getSourceRange();
4136 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4137 CXXConversionDecl *Conv
4138 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4139 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4140 Diag(Conv->getLocation(), AmbigNote)
4141 << ConvTy->isEnumeralType() << ConvTy;
4142 }
John McCallb268a282010-08-23 23:25:46 +00004143 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004144 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004145
Douglas Gregor5823da32010-06-29 23:25:20 +00004146 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004147 Diag(Loc, NotIntDiag)
4148 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004149
John McCallb268a282010-08-23 23:25:46 +00004150 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004151}
4152
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004153/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004154/// candidate functions, using the given function call arguments. If
4155/// @p SuppressUserConversions, then don't allow user-defined
4156/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004157///
4158/// \para PartialOverloading true if we are performing "partial" overloading
4159/// based on an incomplete set of function arguments. This feature is used by
4160/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004161void
4162Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004163 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004164 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004165 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004166 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004167 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004168 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004169 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004170 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004171 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004172 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004173
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004174 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004175 if (!isa<CXXConstructorDecl>(Method)) {
4176 // If we get here, it's because we're calling a member function
4177 // that is named without a member access expression (e.g.,
4178 // "this->f") that was either written explicitly or created
4179 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004180 // function, e.g., X::f(). We use an empty type for the implied
4181 // object argument (C++ [over.call.func]p3), and the acting context
4182 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004183 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004184 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004185 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004186 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004187 return;
4188 }
4189 // We treat a constructor like a non-member function, since its object
4190 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004191 }
4192
Douglas Gregorff7028a2009-11-13 23:59:09 +00004193 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004194 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004195
Douglas Gregor27381f32009-11-23 12:27:39 +00004196 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004197 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004198
Douglas Gregorffe14e32009-11-14 01:20:54 +00004199 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4200 // C++ [class.copy]p3:
4201 // A member function template is never instantiated to perform the copy
4202 // of a class object to an object of its class type.
4203 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004204 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004205 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004206 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4207 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004208 return;
4209 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004210
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004211 // Add this candidate
4212 CandidateSet.push_back(OverloadCandidate());
4213 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004214 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004215 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004216 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004217 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004218 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004219 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004220
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004221 unsigned NumArgsInProto = Proto->getNumArgs();
4222
4223 // (C++ 13.3.2p2): A candidate function having fewer than m
4224 // parameters is viable only if it has an ellipsis in its parameter
4225 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004226 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004227 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004228 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004229 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004230 return;
4231 }
4232
4233 // (C++ 13.3.2p2): A candidate function having more than m parameters
4234 // is viable only if the (m+1)st parameter has a default argument
4235 // (8.3.6). For the purposes of overload resolution, the
4236 // parameter list is truncated on the right, so that there are
4237 // exactly m parameters.
4238 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004239 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004240 // Not enough arguments.
4241 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004242 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004243 return;
4244 }
4245
Peter Collingbourne7277fe82011-10-02 23:49:40 +00004246 // (CUDA B.1): Check for invalid calls between targets.
4247 if (getLangOptions().CUDA)
4248 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4249 if (CheckCUDATarget(Caller, Function)) {
4250 Candidate.Viable = false;
4251 Candidate.FailureKind = ovl_fail_bad_target;
4252 return;
4253 }
4254
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004255 // Determine the implicit conversion sequences for each of the
4256 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004257 Candidate.Conversions.resize(NumArgs);
4258 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4259 if (ArgIdx < NumArgsInProto) {
4260 // (C++ 13.3.2p3): for F to be a viable function, there shall
4261 // exist for each argument an implicit conversion sequence
4262 // (13.3.3.1) that converts that argument to the corresponding
4263 // parameter of F.
4264 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004265 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004266 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004267 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004268 /*InOverloadResolution=*/true,
4269 /*AllowObjCWritebackConversion=*/
4270 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004271 if (Candidate.Conversions[ArgIdx].isBad()) {
4272 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004273 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004274 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004275 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004276 } else {
4277 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4278 // argument for which there is no corresponding parameter is
4279 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004280 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004281 }
4282 }
4283}
4284
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004285/// \brief Add all of the function declarations in the given function set to
4286/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004287void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004288 Expr **Args, unsigned NumArgs,
4289 OverloadCandidateSet& CandidateSet,
4290 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004291 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004292 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4293 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004294 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004295 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004296 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004297 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004298 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004299 CandidateSet, SuppressUserConversions);
4300 else
John McCalla0296f72010-03-19 07:35:19 +00004301 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004302 SuppressUserConversions);
4303 } else {
John McCalla0296f72010-03-19 07:35:19 +00004304 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004305 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4306 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004307 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004308 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004309 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004310 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004311 Args[0]->Classify(Context),
4312 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004313 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004314 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004315 else
John McCalla0296f72010-03-19 07:35:19 +00004316 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004317 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004318 Args, NumArgs, CandidateSet,
4319 SuppressUserConversions);
4320 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004321 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004322}
4323
John McCallf0f1cf02009-11-17 07:50:12 +00004324/// AddMethodCandidate - Adds a named decl (which is some kind of
4325/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004326void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004327 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004328 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004329 Expr **Args, unsigned NumArgs,
4330 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004331 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004332 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004333 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004334
4335 if (isa<UsingShadowDecl>(Decl))
4336 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004337
John McCallf0f1cf02009-11-17 07:50:12 +00004338 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4339 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4340 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004341 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4342 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004343 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004344 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004345 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004346 } else {
John McCalla0296f72010-03-19 07:35:19 +00004347 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004348 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004349 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004350 }
4351}
4352
Douglas Gregor436424c2008-11-18 23:14:02 +00004353/// AddMethodCandidate - Adds the given C++ member function to the set
4354/// of candidate functions, using the given function call arguments
4355/// and the object argument (@c Object). For example, in a call
4356/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4357/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4358/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004359/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004360void
John McCalla0296f72010-03-19 07:35:19 +00004361Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004362 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004363 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004364 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004365 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004366 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004367 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004368 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004369 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004370 assert(!isa<CXXConstructorDecl>(Method) &&
4371 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004372
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004373 if (!CandidateSet.isNewCandidate(Method))
4374 return;
4375
Douglas Gregor27381f32009-11-23 12:27:39 +00004376 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004377 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004378
Douglas Gregor436424c2008-11-18 23:14:02 +00004379 // Add this candidate
4380 CandidateSet.push_back(OverloadCandidate());
4381 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004382 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004383 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004384 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004385 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004386 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004387
4388 unsigned NumArgsInProto = Proto->getNumArgs();
4389
4390 // (C++ 13.3.2p2): A candidate function having fewer than m
4391 // parameters is viable only if it has an ellipsis in its parameter
4392 // list (8.3.5).
4393 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4394 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004395 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004396 return;
4397 }
4398
4399 // (C++ 13.3.2p2): A candidate function having more than m parameters
4400 // is viable only if the (m+1)st parameter has a default argument
4401 // (8.3.6). For the purposes of overload resolution, the
4402 // parameter list is truncated on the right, so that there are
4403 // exactly m parameters.
4404 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4405 if (NumArgs < MinRequiredArgs) {
4406 // Not enough arguments.
4407 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004408 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004409 return;
4410 }
4411
4412 Candidate.Viable = true;
4413 Candidate.Conversions.resize(NumArgs + 1);
4414
John McCall6e9f8f62009-12-03 04:06:58 +00004415 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004416 // The implicit object argument is ignored.
4417 Candidate.IgnoreObjectArgument = true;
4418 else {
4419 // Determine the implicit conversion sequence for the object
4420 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004421 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004422 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4423 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004424 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004425 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004426 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004427 return;
4428 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004429 }
4430
4431 // Determine the implicit conversion sequences for each of the
4432 // arguments.
4433 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4434 if (ArgIdx < NumArgsInProto) {
4435 // (C++ 13.3.2p3): for F to be a viable function, there shall
4436 // exist for each argument an implicit conversion sequence
4437 // (13.3.3.1) that converts that argument to the corresponding
4438 // parameter of F.
4439 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004440 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004441 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004442 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004443 /*InOverloadResolution=*/true,
4444 /*AllowObjCWritebackConversion=*/
4445 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004446 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004447 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004448 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004449 break;
4450 }
4451 } else {
4452 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4453 // argument for which there is no corresponding parameter is
4454 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004455 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004456 }
4457 }
4458}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004459
Douglas Gregor97628d62009-08-21 00:16:32 +00004460/// \brief Add a C++ member function template as a candidate to the candidate
4461/// set, using template argument deduction to produce an appropriate member
4462/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004463void
Douglas Gregor97628d62009-08-21 00:16:32 +00004464Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004465 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004466 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004467 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004468 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004469 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004470 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004471 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004472 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004473 if (!CandidateSet.isNewCandidate(MethodTmpl))
4474 return;
4475
Douglas Gregor97628d62009-08-21 00:16:32 +00004476 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004477 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004478 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004479 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004480 // candidate functions in the usual way.113) A given name can refer to one
4481 // or more function templates and also to a set of overloaded non-template
4482 // functions. In such a case, the candidate functions generated from each
4483 // function template are combined with the set of non-template candidate
4484 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004485 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004486 FunctionDecl *Specialization = 0;
4487 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004488 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004489 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004490 CandidateSet.push_back(OverloadCandidate());
4491 OverloadCandidate &Candidate = CandidateSet.back();
4492 Candidate.FoundDecl = FoundDecl;
4493 Candidate.Function = MethodTmpl->getTemplatedDecl();
4494 Candidate.Viable = false;
4495 Candidate.FailureKind = ovl_fail_bad_deduction;
4496 Candidate.IsSurrogate = false;
4497 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004498 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004499 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004500 Info);
4501 return;
4502 }
Mike Stump11289f42009-09-09 15:08:12 +00004503
Douglas Gregor97628d62009-08-21 00:16:32 +00004504 // Add the function template specialization produced by template argument
4505 // deduction as a candidate.
4506 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004507 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004508 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004509 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004510 ActingContext, ObjectType, ObjectClassification,
4511 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004512}
4513
Douglas Gregor05155d82009-08-21 23:19:43 +00004514/// \brief Add a C++ function template specialization as a candidate
4515/// in the candidate set, using template argument deduction to produce
4516/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004517void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004518Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004519 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004520 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004521 Expr **Args, unsigned NumArgs,
4522 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004523 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004524 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4525 return;
4526
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004527 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004528 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004529 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004530 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004531 // candidate functions in the usual way.113) A given name can refer to one
4532 // or more function templates and also to a set of overloaded non-template
4533 // functions. In such a case, the candidate functions generated from each
4534 // function template are combined with the set of non-template candidate
4535 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004536 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004537 FunctionDecl *Specialization = 0;
4538 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004539 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004540 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004541 CandidateSet.push_back(OverloadCandidate());
4542 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004543 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004544 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4545 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004546 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004547 Candidate.IsSurrogate = false;
4548 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004549 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004550 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004551 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004552 return;
4553 }
Mike Stump11289f42009-09-09 15:08:12 +00004554
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004555 // Add the function template specialization produced by template argument
4556 // deduction as a candidate.
4557 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004558 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004559 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004560}
Mike Stump11289f42009-09-09 15:08:12 +00004561
Douglas Gregora1f013e2008-11-07 22:36:19 +00004562/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004563/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004564/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004565/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004566/// (which may or may not be the same type as the type that the
4567/// conversion function produces).
4568void
4569Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004570 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004571 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004572 Expr *From, QualType ToType,
4573 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004574 assert(!Conversion->getDescribedFunctionTemplate() &&
4575 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004576 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004577 if (!CandidateSet.isNewCandidate(Conversion))
4578 return;
4579
Douglas Gregor27381f32009-11-23 12:27:39 +00004580 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004581 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004582
Douglas Gregora1f013e2008-11-07 22:36:19 +00004583 // Add this candidate
4584 CandidateSet.push_back(OverloadCandidate());
4585 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004586 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004587 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004588 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004589 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004590 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004591 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004592 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004593 Candidate.Viable = true;
4594 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004595 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004596
Douglas Gregor6affc782010-08-19 15:37:02 +00004597 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004598 // For conversion functions, the function is considered to be a member of
4599 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004600 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004601 //
4602 // Determine the implicit conversion sequence for the implicit
4603 // object parameter.
4604 QualType ImplicitParamType = From->getType();
4605 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4606 ImplicitParamType = FromPtrType->getPointeeType();
4607 CXXRecordDecl *ConversionContext
4608 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004609
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004610 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004611 = TryObjectArgumentInitialization(*this, From->getType(),
4612 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004613 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004614
John McCall0d1da222010-01-12 00:44:57 +00004615 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004616 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004617 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004618 return;
4619 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004620
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004622 // derived to base as such conversions are given Conversion Rank. They only
4623 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4624 QualType FromCanon
4625 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4626 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4627 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4628 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004629 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004630 return;
4631 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004632
Douglas Gregora1f013e2008-11-07 22:36:19 +00004633 // To determine what the conversion from the result of calling the
4634 // conversion function to the type we're eventually trying to
4635 // convert to (ToType), we need to synthesize a call to the
4636 // conversion function and attempt copy initialization from it. This
4637 // makes sure that we get the right semantics with respect to
4638 // lvalues/rvalues and the type. Fortunately, we can allocate this
4639 // call on the stack and we don't need its arguments to be
4640 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004641 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004642 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004643 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4644 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004645 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004646 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004647
Richard Smith48d24642011-07-13 22:53:21 +00004648 QualType ConversionType = Conversion->getConversionType();
4649 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004650 Candidate.Viable = false;
4651 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4652 return;
4653 }
4654
Richard Smith48d24642011-07-13 22:53:21 +00004655 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00004656
Mike Stump11289f42009-09-09 15:08:12 +00004657 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004658 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4659 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00004660 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004661 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004662 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004663 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004664 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004665 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00004666 /*InOverloadResolution=*/false,
4667 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004668
John McCall0d1da222010-01-12 00:44:57 +00004669 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004670 case ImplicitConversionSequence::StandardConversion:
4671 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004672
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004673 // C++ [over.ics.user]p3:
4674 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004675 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004676 // shall have exact match rank.
4677 if (Conversion->getPrimaryTemplate() &&
4678 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4679 Candidate.Viable = false;
4680 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4681 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004682
Douglas Gregorcba72b12011-01-21 05:18:22 +00004683 // C++0x [dcl.init.ref]p5:
4684 // In the second case, if the reference is an rvalue reference and
4685 // the second standard conversion sequence of the user-defined
4686 // conversion sequence includes an lvalue-to-rvalue conversion, the
4687 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004688 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004689 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4690 Candidate.Viable = false;
4691 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4692 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004693 break;
4694
4695 case ImplicitConversionSequence::BadConversion:
4696 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004697 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004698 break;
4699
4700 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004701 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00004702 "Can only end up with a standard conversion sequence or failure");
4703 }
4704}
4705
Douglas Gregor05155d82009-08-21 23:19:43 +00004706/// \brief Adds a conversion function template specialization
4707/// candidate to the overload set, using template argument deduction
4708/// to deduce the template arguments of the conversion function
4709/// template from the type that we are converting to (C++
4710/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004711void
Douglas Gregor05155d82009-08-21 23:19:43 +00004712Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004713 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004714 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004715 Expr *From, QualType ToType,
4716 OverloadCandidateSet &CandidateSet) {
4717 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4718 "Only conversion function templates permitted here");
4719
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004720 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4721 return;
4722
John McCallbc077cf2010-02-08 23:07:23 +00004723 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004724 CXXConversionDecl *Specialization = 0;
4725 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004726 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004727 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004728 CandidateSet.push_back(OverloadCandidate());
4729 OverloadCandidate &Candidate = CandidateSet.back();
4730 Candidate.FoundDecl = FoundDecl;
4731 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4732 Candidate.Viable = false;
4733 Candidate.FailureKind = ovl_fail_bad_deduction;
4734 Candidate.IsSurrogate = false;
4735 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004736 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004737 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004738 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004739 return;
4740 }
Mike Stump11289f42009-09-09 15:08:12 +00004741
Douglas Gregor05155d82009-08-21 23:19:43 +00004742 // Add the conversion function template specialization produced by
4743 // template argument deduction as a candidate.
4744 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004745 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004746 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004747}
4748
Douglas Gregorab7897a2008-11-19 22:57:39 +00004749/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4750/// converts the given @c Object to a function pointer via the
4751/// conversion function @c Conversion, and then attempts to call it
4752/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4753/// the type of function that we'll eventually be calling.
4754void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004755 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004756 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004757 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004758 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004759 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004760 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004761 if (!CandidateSet.isNewCandidate(Conversion))
4762 return;
4763
Douglas Gregor27381f32009-11-23 12:27:39 +00004764 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004765 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004766
Douglas Gregorab7897a2008-11-19 22:57:39 +00004767 CandidateSet.push_back(OverloadCandidate());
4768 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004769 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004770 Candidate.Function = 0;
4771 Candidate.Surrogate = Conversion;
4772 Candidate.Viable = true;
4773 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004774 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004775 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004776 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004777
4778 // Determine the implicit conversion sequence for the implicit
4779 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004780 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004781 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004782 Object->Classify(Context),
4783 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004784 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004785 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004786 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004787 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004788 return;
4789 }
4790
4791 // The first conversion is actually a user-defined conversion whose
4792 // first conversion is ObjectInit's standard conversion (which is
4793 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004794 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004795 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004796 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004797 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00004798 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00004799 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004800 = Candidate.Conversions[0].UserDefined.Before;
4801 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4802
Mike Stump11289f42009-09-09 15:08:12 +00004803 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004804 unsigned NumArgsInProto = Proto->getNumArgs();
4805
4806 // (C++ 13.3.2p2): A candidate function having fewer than m
4807 // parameters is viable only if it has an ellipsis in its parameter
4808 // list (8.3.5).
4809 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4810 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004811 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004812 return;
4813 }
4814
4815 // Function types don't have any default arguments, so just check if
4816 // we have enough arguments.
4817 if (NumArgs < NumArgsInProto) {
4818 // Not enough arguments.
4819 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004820 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004821 return;
4822 }
4823
4824 // Determine the implicit conversion sequences for each of the
4825 // arguments.
4826 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4827 if (ArgIdx < NumArgsInProto) {
4828 // (C++ 13.3.2p3): for F to be a viable function, there shall
4829 // exist for each argument an implicit conversion sequence
4830 // (13.3.3.1) that converts that argument to the corresponding
4831 // parameter of F.
4832 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004833 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004834 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004835 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00004836 /*InOverloadResolution=*/false,
4837 /*AllowObjCWritebackConversion=*/
4838 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004839 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004840 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004841 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004842 break;
4843 }
4844 } else {
4845 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4846 // argument for which there is no corresponding parameter is
4847 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004848 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004849 }
4850 }
4851}
4852
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004853/// \brief Add overload candidates for overloaded operators that are
4854/// member functions.
4855///
4856/// Add the overloaded operator candidates that are member functions
4857/// for the operator Op that was used in an operator expression such
4858/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4859/// CandidateSet will store the added overload candidates. (C++
4860/// [over.match.oper]).
4861void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4862 SourceLocation OpLoc,
4863 Expr **Args, unsigned NumArgs,
4864 OverloadCandidateSet& CandidateSet,
4865 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004866 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4867
4868 // C++ [over.match.oper]p3:
4869 // For a unary operator @ with an operand of a type whose
4870 // cv-unqualified version is T1, and for a binary operator @ with
4871 // a left operand of a type whose cv-unqualified version is T1 and
4872 // a right operand of a type whose cv-unqualified version is T2,
4873 // three sets of candidate functions, designated member
4874 // candidates, non-member candidates and built-in candidates, are
4875 // constructed as follows:
4876 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004877
4878 // -- If T1 is a class type, the set of member candidates is the
4879 // result of the qualified lookup of T1::operator@
4880 // (13.3.1.1.1); otherwise, the set of member candidates is
4881 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004882 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004883 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004884 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004885 return;
Mike Stump11289f42009-09-09 15:08:12 +00004886
John McCall27b18f82009-11-17 02:14:36 +00004887 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4888 LookupQualifiedName(Operators, T1Rec->getDecl());
4889 Operators.suppressDiagnostics();
4890
Mike Stump11289f42009-09-09 15:08:12 +00004891 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004892 OperEnd = Operators.end();
4893 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004894 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004895 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004896 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00004897 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004898 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004899 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004900}
4901
Douglas Gregora11693b2008-11-12 17:17:38 +00004902/// AddBuiltinCandidate - Add a candidate for a built-in
4903/// operator. ResultTy and ParamTys are the result and parameter types
4904/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004905/// arguments being passed to the candidate. IsAssignmentOperator
4906/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004907/// operator. NumContextualBoolArguments is the number of arguments
4908/// (at the beginning of the argument list) that will be contextually
4909/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004910void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004911 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004912 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004913 bool IsAssignmentOperator,
4914 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004915 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004916 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004917
Douglas Gregora11693b2008-11-12 17:17:38 +00004918 // Add this candidate
4919 CandidateSet.push_back(OverloadCandidate());
4920 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004921 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004922 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004923 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004924 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004925 Candidate.BuiltinTypes.ResultTy = ResultTy;
4926 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4927 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4928
4929 // Determine the implicit conversion sequences for each of the
4930 // arguments.
4931 Candidate.Viable = true;
4932 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004933 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004934 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004935 // C++ [over.match.oper]p4:
4936 // For the built-in assignment operators, conversions of the
4937 // left operand are restricted as follows:
4938 // -- no temporaries are introduced to hold the left operand, and
4939 // -- no user-defined conversions are applied to the left
4940 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004941 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004942 //
4943 // We block these conversions by turning off user-defined
4944 // conversions, since that is the only way that initialization of
4945 // a reference to a non-class type can occur from something that
4946 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004947 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004948 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004949 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004950 Candidate.Conversions[ArgIdx]
4951 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004952 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004953 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004954 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004955 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00004956 /*InOverloadResolution=*/false,
4957 /*AllowObjCWritebackConversion=*/
4958 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004959 }
John McCall0d1da222010-01-12 00:44:57 +00004960 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004961 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004962 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004963 break;
4964 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004965 }
4966}
4967
4968/// BuiltinCandidateTypeSet - A set of types that will be used for the
4969/// candidate operator functions for built-in operators (C++
4970/// [over.built]). The types are separated into pointer types and
4971/// enumeration types.
4972class BuiltinCandidateTypeSet {
4973 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004974 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004975
4976 /// PointerTypes - The set of pointer types that will be used in the
4977 /// built-in candidates.
4978 TypeSet PointerTypes;
4979
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004980 /// MemberPointerTypes - The set of member pointer types that will be
4981 /// used in the built-in candidates.
4982 TypeSet MemberPointerTypes;
4983
Douglas Gregora11693b2008-11-12 17:17:38 +00004984 /// EnumerationTypes - The set of enumeration types that will be
4985 /// used in the built-in candidates.
4986 TypeSet EnumerationTypes;
4987
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004988 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004989 /// candidates.
4990 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004991
4992 /// \brief A flag indicating non-record types are viable candidates
4993 bool HasNonRecordTypes;
4994
4995 /// \brief A flag indicating whether either arithmetic or enumeration types
4996 /// were present in the candidate set.
4997 bool HasArithmeticOrEnumeralTypes;
4998
Douglas Gregor80af3132011-05-21 23:15:46 +00004999 /// \brief A flag indicating whether the nullptr type was present in the
5000 /// candidate set.
5001 bool HasNullPtrType;
5002
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005003 /// Sema - The semantic analysis instance where we are building the
5004 /// candidate type set.
5005 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005006
Douglas Gregora11693b2008-11-12 17:17:38 +00005007 /// Context - The AST context in which we will build the type sets.
5008 ASTContext &Context;
5009
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005010 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5011 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005012 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005013
5014public:
5015 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005016 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005017
Mike Stump11289f42009-09-09 15:08:12 +00005018 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005019 : HasNonRecordTypes(false),
5020 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005021 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005022 SemaRef(SemaRef),
5023 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005024
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005025 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005026 SourceLocation Loc,
5027 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005028 bool AllowExplicitConversions,
5029 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005030
5031 /// pointer_begin - First pointer type found;
5032 iterator pointer_begin() { return PointerTypes.begin(); }
5033
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005034 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005035 iterator pointer_end() { return PointerTypes.end(); }
5036
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005037 /// member_pointer_begin - First member pointer type found;
5038 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5039
5040 /// member_pointer_end - Past the last member pointer type found;
5041 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5042
Douglas Gregora11693b2008-11-12 17:17:38 +00005043 /// enumeration_begin - First enumeration type found;
5044 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5045
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005046 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005047 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005048
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005049 iterator vector_begin() { return VectorTypes.begin(); }
5050 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005051
5052 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5053 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005054 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005055};
5056
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005057/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005058/// the set of pointer types along with any more-qualified variants of
5059/// that type. For example, if @p Ty is "int const *", this routine
5060/// will add "int const *", "int const volatile *", "int const
5061/// restrict *", and "int const volatile restrict *" to the set of
5062/// pointer types. Returns true if the add of @p Ty itself succeeded,
5063/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005064///
5065/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005066bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005067BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5068 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00005069
Douglas Gregora11693b2008-11-12 17:17:38 +00005070 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005071 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00005072 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005073
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005074 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00005075 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005076 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005077 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005078 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005079 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005080 buildObjCPtr = true;
5081 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005082 else
David Blaikie83d382b2011-09-23 05:06:16 +00005083 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005084 }
5085 else
5086 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005087
Sebastian Redl4990a632009-11-18 20:39:26 +00005088 // Don't add qualified variants of arrays. For one, they're not allowed
5089 // (the qualifier would sink to the element type), and for another, the
5090 // only overload situation where it matters is subscript or pointer +- int,
5091 // and those shouldn't have qualifier variants anyway.
5092 if (PointeeTy->isArrayType())
5093 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005094 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005095 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005096 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005097 bool hasVolatile = VisibleQuals.hasVolatile();
5098 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005099
John McCall8ccfcb52009-09-24 19:53:00 +00005100 // Iterate through all strict supersets of BaseCVR.
5101 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5102 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005103 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5104 // in the types.
5105 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5106 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005107 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005108 if (!buildObjCPtr)
5109 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5110 else
5111 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005112 }
5113
5114 return true;
5115}
5116
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005117/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5118/// to the set of pointer types along with any more-qualified variants of
5119/// that type. For example, if @p Ty is "int const *", this routine
5120/// will add "int const *", "int const volatile *", "int const
5121/// restrict *", and "int const volatile restrict *" to the set of
5122/// pointer types. Returns true if the add of @p Ty itself succeeded,
5123/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005124///
5125/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005126bool
5127BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5128 QualType Ty) {
5129 // Insert this type.
5130 if (!MemberPointerTypes.insert(Ty))
5131 return false;
5132
John McCall8ccfcb52009-09-24 19:53:00 +00005133 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5134 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005135
John McCall8ccfcb52009-09-24 19:53:00 +00005136 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005137 // Don't add qualified variants of arrays. For one, they're not allowed
5138 // (the qualifier would sink to the element type), and for another, the
5139 // only overload situation where it matters is subscript or pointer +- int,
5140 // and those shouldn't have qualifier variants anyway.
5141 if (PointeeTy->isArrayType())
5142 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005143 const Type *ClassTy = PointerTy->getClass();
5144
5145 // Iterate through all strict supersets of the pointee type's CVR
5146 // qualifiers.
5147 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5148 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5149 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005150
John McCall8ccfcb52009-09-24 19:53:00 +00005151 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005152 MemberPointerTypes.insert(
5153 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005154 }
5155
5156 return true;
5157}
5158
Douglas Gregora11693b2008-11-12 17:17:38 +00005159/// AddTypesConvertedFrom - Add each of the types to which the type @p
5160/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005161/// primarily interested in pointer types and enumeration types. We also
5162/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005163/// AllowUserConversions is true if we should look at the conversion
5164/// functions of a class type, and AllowExplicitConversions if we
5165/// should also include the explicit conversion functions of a class
5166/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005167void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005168BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005169 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005170 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005171 bool AllowExplicitConversions,
5172 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005173 // Only deal with canonical types.
5174 Ty = Context.getCanonicalType(Ty);
5175
5176 // Look through reference types; they aren't part of the type of an
5177 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005178 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005179 Ty = RefTy->getPointeeType();
5180
John McCall33ddac02011-01-19 10:06:00 +00005181 // If we're dealing with an array type, decay to the pointer.
5182 if (Ty->isArrayType())
5183 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5184
5185 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005186 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005187
Chandler Carruth00a38332010-12-13 01:44:01 +00005188 // Flag if we ever add a non-record type.
5189 const RecordType *TyRec = Ty->getAs<RecordType>();
5190 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5191
Chandler Carruth00a38332010-12-13 01:44:01 +00005192 // Flag if we encounter an arithmetic type.
5193 HasArithmeticOrEnumeralTypes =
5194 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5195
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005196 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5197 PointerTypes.insert(Ty);
5198 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005199 // Insert our type, and its more-qualified variants, into the set
5200 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005201 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005202 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005203 } else if (Ty->isMemberPointerType()) {
5204 // Member pointers are far easier, since the pointee can't be converted.
5205 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5206 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005207 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005208 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005209 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005210 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005211 // We treat vector types as arithmetic types in many contexts as an
5212 // extension.
5213 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005214 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005215 } else if (Ty->isNullPtrType()) {
5216 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005217 } else if (AllowUserConversions && TyRec) {
5218 // No conversion functions in incomplete types.
5219 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5220 return;
Mike Stump11289f42009-09-09 15:08:12 +00005221
Chandler Carruth00a38332010-12-13 01:44:01 +00005222 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5223 const UnresolvedSetImpl *Conversions
5224 = ClassDecl->getVisibleConversionFunctions();
5225 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5226 E = Conversions->end(); I != E; ++I) {
5227 NamedDecl *D = I.getDecl();
5228 if (isa<UsingShadowDecl>(D))
5229 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005230
Chandler Carruth00a38332010-12-13 01:44:01 +00005231 // Skip conversion function templates; they don't tell us anything
5232 // about which builtin types we can convert to.
5233 if (isa<FunctionTemplateDecl>(D))
5234 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005235
Chandler Carruth00a38332010-12-13 01:44:01 +00005236 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5237 if (AllowExplicitConversions || !Conv->isExplicit()) {
5238 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5239 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005240 }
5241 }
5242 }
5243}
5244
Douglas Gregor84605ae2009-08-24 13:43:27 +00005245/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5246/// the volatile- and non-volatile-qualified assignment operators for the
5247/// given type to the candidate set.
5248static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5249 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005250 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005251 unsigned NumArgs,
5252 OverloadCandidateSet &CandidateSet) {
5253 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005254
Douglas Gregor84605ae2009-08-24 13:43:27 +00005255 // T& operator=(T&, T)
5256 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5257 ParamTypes[1] = T;
5258 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5259 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005260
Douglas Gregor84605ae2009-08-24 13:43:27 +00005261 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5262 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005263 ParamTypes[0]
5264 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005265 ParamTypes[1] = T;
5266 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005267 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005268 }
5269}
Mike Stump11289f42009-09-09 15:08:12 +00005270
Sebastian Redl1054fae2009-10-25 17:03:50 +00005271/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5272/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005273static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5274 Qualifiers VRQuals;
5275 const RecordType *TyRec;
5276 if (const MemberPointerType *RHSMPType =
5277 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005278 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005279 else
5280 TyRec = ArgExpr->getType()->getAs<RecordType>();
5281 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005282 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005283 VRQuals.addVolatile();
5284 VRQuals.addRestrict();
5285 return VRQuals;
5286 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005287
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005288 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005289 if (!ClassDecl->hasDefinition())
5290 return VRQuals;
5291
John McCallad371252010-01-20 00:46:10 +00005292 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005293 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005294
John McCallad371252010-01-20 00:46:10 +00005295 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005296 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005297 NamedDecl *D = I.getDecl();
5298 if (isa<UsingShadowDecl>(D))
5299 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5300 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005301 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5302 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5303 CanTy = ResTypeRef->getPointeeType();
5304 // Need to go down the pointer/mempointer chain and add qualifiers
5305 // as see them.
5306 bool done = false;
5307 while (!done) {
5308 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5309 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005310 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005311 CanTy->getAs<MemberPointerType>())
5312 CanTy = ResTypeMPtr->getPointeeType();
5313 else
5314 done = true;
5315 if (CanTy.isVolatileQualified())
5316 VRQuals.addVolatile();
5317 if (CanTy.isRestrictQualified())
5318 VRQuals.addRestrict();
5319 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5320 return VRQuals;
5321 }
5322 }
5323 }
5324 return VRQuals;
5325}
John McCall52872982010-11-13 05:51:15 +00005326
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005327namespace {
John McCall52872982010-11-13 05:51:15 +00005328
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005329/// \brief Helper class to manage the addition of builtin operator overload
5330/// candidates. It provides shared state and utility methods used throughout
5331/// the process, as well as a helper method to add each group of builtin
5332/// operator overloads from the standard to a candidate set.
5333class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005334 // Common instance state available to all overload candidate addition methods.
5335 Sema &S;
5336 Expr **Args;
5337 unsigned NumArgs;
5338 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005339 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005340 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005341 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005342
Chandler Carruthc6586e52010-12-12 10:35:00 +00005343 // Define some constants used to index and iterate over the arithemetic types
5344 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005345 // The "promoted arithmetic types" are the arithmetic
5346 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005347 static const unsigned FirstIntegralType = 3;
5348 static const unsigned LastIntegralType = 18;
5349 static const unsigned FirstPromotedIntegralType = 3,
5350 LastPromotedIntegralType = 9;
5351 static const unsigned FirstPromotedArithmeticType = 0,
5352 LastPromotedArithmeticType = 9;
5353 static const unsigned NumArithmeticTypes = 18;
5354
Chandler Carruthc6586e52010-12-12 10:35:00 +00005355 /// \brief Get the canonical type for a given arithmetic type index.
5356 CanQualType getArithmeticType(unsigned index) {
5357 assert(index < NumArithmeticTypes);
5358 static CanQualType ASTContext::* const
5359 ArithmeticTypes[NumArithmeticTypes] = {
5360 // Start of promoted types.
5361 &ASTContext::FloatTy,
5362 &ASTContext::DoubleTy,
5363 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005364
Chandler Carruthc6586e52010-12-12 10:35:00 +00005365 // Start of integral types.
5366 &ASTContext::IntTy,
5367 &ASTContext::LongTy,
5368 &ASTContext::LongLongTy,
5369 &ASTContext::UnsignedIntTy,
5370 &ASTContext::UnsignedLongTy,
5371 &ASTContext::UnsignedLongLongTy,
5372 // End of promoted types.
5373
5374 &ASTContext::BoolTy,
5375 &ASTContext::CharTy,
5376 &ASTContext::WCharTy,
5377 &ASTContext::Char16Ty,
5378 &ASTContext::Char32Ty,
5379 &ASTContext::SignedCharTy,
5380 &ASTContext::ShortTy,
5381 &ASTContext::UnsignedCharTy,
5382 &ASTContext::UnsignedShortTy,
5383 // End of integral types.
5384 // FIXME: What about complex?
5385 };
5386 return S.Context.*ArithmeticTypes[index];
5387 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005388
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005389 /// \brief Gets the canonical type resulting from the usual arithemetic
5390 /// converions for the given arithmetic types.
5391 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5392 // Accelerator table for performing the usual arithmetic conversions.
5393 // The rules are basically:
5394 // - if either is floating-point, use the wider floating-point
5395 // - if same signedness, use the higher rank
5396 // - if same size, use unsigned of the higher rank
5397 // - use the larger type
5398 // These rules, together with the axiom that higher ranks are
5399 // never smaller, are sufficient to precompute all of these results
5400 // *except* when dealing with signed types of higher rank.
5401 // (we could precompute SLL x UI for all known platforms, but it's
5402 // better not to make any assumptions).
5403 enum PromotedType {
5404 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5405 };
5406 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5407 [LastPromotedArithmeticType] = {
5408 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5409 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5410 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5411 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5412 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5413 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5414 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5415 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5416 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5417 };
5418
5419 assert(L < LastPromotedArithmeticType);
5420 assert(R < LastPromotedArithmeticType);
5421 int Idx = ConversionsTable[L][R];
5422
5423 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005424 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005425
5426 // Slow path: we need to compare widths.
5427 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005428 CanQualType LT = getArithmeticType(L),
5429 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005430 unsigned LW = S.Context.getIntWidth(LT),
5431 RW = S.Context.getIntWidth(RT);
5432
5433 // If they're different widths, use the signed type.
5434 if (LW > RW) return LT;
5435 else if (LW < RW) return RT;
5436
5437 // Otherwise, use the unsigned type of the signed type's rank.
5438 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5439 assert(L == SLL || R == SLL);
5440 return S.Context.UnsignedLongLongTy;
5441 }
5442
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005443 /// \brief Helper method to factor out the common pattern of adding overloads
5444 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005445 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5446 bool HasVolatile) {
5447 QualType ParamTypes[2] = {
5448 S.Context.getLValueReferenceType(CandidateTy),
5449 S.Context.IntTy
5450 };
5451
5452 // Non-volatile version.
5453 if (NumArgs == 1)
5454 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5455 else
5456 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5457
5458 // Use a heuristic to reduce number of builtin candidates in the set:
5459 // add volatile version only if there are conversions to a volatile type.
5460 if (HasVolatile) {
5461 ParamTypes[0] =
5462 S.Context.getLValueReferenceType(
5463 S.Context.getVolatileType(CandidateTy));
5464 if (NumArgs == 1)
5465 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5466 else
5467 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5468 }
5469 }
5470
5471public:
5472 BuiltinOperatorOverloadBuilder(
5473 Sema &S, Expr **Args, unsigned NumArgs,
5474 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005475 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005476 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005477 OverloadCandidateSet &CandidateSet)
5478 : S(S), Args(Args), NumArgs(NumArgs),
5479 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005480 HasArithmeticOrEnumeralCandidateType(
5481 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005482 CandidateTypes(CandidateTypes),
5483 CandidateSet(CandidateSet) {
5484 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005485 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005486 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005487 assert(getArithmeticType(LastPromotedIntegralType - 1)
5488 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005489 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005490 assert(getArithmeticType(FirstPromotedArithmeticType)
5491 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005492 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005493 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5494 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005495 "Invalid last promoted arithmetic type");
5496 }
5497
5498 // C++ [over.built]p3:
5499 //
5500 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5501 // is either volatile or empty, there exist candidate operator
5502 // functions of the form
5503 //
5504 // VQ T& operator++(VQ T&);
5505 // T operator++(VQ T&, int);
5506 //
5507 // C++ [over.built]p4:
5508 //
5509 // For every pair (T, VQ), where T is an arithmetic type other
5510 // than bool, and VQ is either volatile or empty, there exist
5511 // candidate operator functions of the form
5512 //
5513 // VQ T& operator--(VQ T&);
5514 // T operator--(VQ T&, int);
5515 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005516 if (!HasArithmeticOrEnumeralCandidateType)
5517 return;
5518
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005519 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5520 Arith < NumArithmeticTypes; ++Arith) {
5521 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005522 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005523 VisibleTypeConversionsQuals.hasVolatile());
5524 }
5525 }
5526
5527 // C++ [over.built]p5:
5528 //
5529 // For every pair (T, VQ), where T is a cv-qualified or
5530 // cv-unqualified object type, and VQ is either volatile or
5531 // empty, there exist candidate operator functions of the form
5532 //
5533 // T*VQ& operator++(T*VQ&);
5534 // T*VQ& operator--(T*VQ&);
5535 // T* operator++(T*VQ&, int);
5536 // T* operator--(T*VQ&, int);
5537 void addPlusPlusMinusMinusPointerOverloads() {
5538 for (BuiltinCandidateTypeSet::iterator
5539 Ptr = CandidateTypes[0].pointer_begin(),
5540 PtrEnd = CandidateTypes[0].pointer_end();
5541 Ptr != PtrEnd; ++Ptr) {
5542 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005543 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005544 continue;
5545
5546 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5547 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5548 VisibleTypeConversionsQuals.hasVolatile()));
5549 }
5550 }
5551
5552 // C++ [over.built]p6:
5553 // For every cv-qualified or cv-unqualified object type T, there
5554 // exist candidate operator functions of the form
5555 //
5556 // T& operator*(T*);
5557 //
5558 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005559 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005560 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005561 // T& operator*(T*);
5562 void addUnaryStarPointerOverloads() {
5563 for (BuiltinCandidateTypeSet::iterator
5564 Ptr = CandidateTypes[0].pointer_begin(),
5565 PtrEnd = CandidateTypes[0].pointer_end();
5566 Ptr != PtrEnd; ++Ptr) {
5567 QualType ParamTy = *Ptr;
5568 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005569 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5570 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005571
Douglas Gregor02824322011-01-26 19:30:28 +00005572 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5573 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5574 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005575
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005576 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5577 &ParamTy, Args, 1, CandidateSet);
5578 }
5579 }
5580
5581 // C++ [over.built]p9:
5582 // For every promoted arithmetic type T, there exist candidate
5583 // operator functions of the form
5584 //
5585 // T operator+(T);
5586 // T operator-(T);
5587 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005588 if (!HasArithmeticOrEnumeralCandidateType)
5589 return;
5590
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005591 for (unsigned Arith = FirstPromotedArithmeticType;
5592 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005593 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005594 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5595 }
5596
5597 // Extension: We also add these operators for vector types.
5598 for (BuiltinCandidateTypeSet::iterator
5599 Vec = CandidateTypes[0].vector_begin(),
5600 VecEnd = CandidateTypes[0].vector_end();
5601 Vec != VecEnd; ++Vec) {
5602 QualType VecTy = *Vec;
5603 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5604 }
5605 }
5606
5607 // C++ [over.built]p8:
5608 // For every type T, there exist candidate operator functions of
5609 // the form
5610 //
5611 // T* operator+(T*);
5612 void addUnaryPlusPointerOverloads() {
5613 for (BuiltinCandidateTypeSet::iterator
5614 Ptr = CandidateTypes[0].pointer_begin(),
5615 PtrEnd = CandidateTypes[0].pointer_end();
5616 Ptr != PtrEnd; ++Ptr) {
5617 QualType ParamTy = *Ptr;
5618 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5619 }
5620 }
5621
5622 // C++ [over.built]p10:
5623 // For every promoted integral type T, there exist candidate
5624 // operator functions of the form
5625 //
5626 // T operator~(T);
5627 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005628 if (!HasArithmeticOrEnumeralCandidateType)
5629 return;
5630
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005631 for (unsigned Int = FirstPromotedIntegralType;
5632 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005633 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005634 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5635 }
5636
5637 // Extension: We also add this operator for vector types.
5638 for (BuiltinCandidateTypeSet::iterator
5639 Vec = CandidateTypes[0].vector_begin(),
5640 VecEnd = CandidateTypes[0].vector_end();
5641 Vec != VecEnd; ++Vec) {
5642 QualType VecTy = *Vec;
5643 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5644 }
5645 }
5646
5647 // C++ [over.match.oper]p16:
5648 // For every pointer to member type T, there exist candidate operator
5649 // functions of the form
5650 //
5651 // bool operator==(T,T);
5652 // bool operator!=(T,T);
5653 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5654 /// Set of (canonical) types that we've already handled.
5655 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5656
5657 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5658 for (BuiltinCandidateTypeSet::iterator
5659 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5660 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5661 MemPtr != MemPtrEnd;
5662 ++MemPtr) {
5663 // Don't add the same builtin candidate twice.
5664 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5665 continue;
5666
5667 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5668 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5669 CandidateSet);
5670 }
5671 }
5672 }
5673
5674 // C++ [over.built]p15:
5675 //
Douglas Gregor80af3132011-05-21 23:15:46 +00005676 // For every T, where T is an enumeration type, a pointer type, or
5677 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005678 //
5679 // bool operator<(T, T);
5680 // bool operator>(T, T);
5681 // bool operator<=(T, T);
5682 // bool operator>=(T, T);
5683 // bool operator==(T, T);
5684 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005685 void addRelationalPointerOrEnumeralOverloads() {
5686 // C++ [over.built]p1:
5687 // If there is a user-written candidate with the same name and parameter
5688 // types as a built-in candidate operator function, the built-in operator
5689 // function is hidden and is not included in the set of candidate
5690 // functions.
5691 //
5692 // The text is actually in a note, but if we don't implement it then we end
5693 // up with ambiguities when the user provides an overloaded operator for
5694 // an enumeration type. Note that only enumeration types have this problem,
5695 // so we track which enumeration types we've seen operators for. Also, the
5696 // only other overloaded operator with enumeration argumenst, operator=,
5697 // cannot be overloaded for enumeration types, so this is the only place
5698 // where we must suppress candidates like this.
5699 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5700 UserDefinedBinaryOperators;
5701
5702 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5703 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5704 CandidateTypes[ArgIdx].enumeration_end()) {
5705 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5706 CEnd = CandidateSet.end();
5707 C != CEnd; ++C) {
5708 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5709 continue;
5710
5711 QualType FirstParamType =
5712 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5713 QualType SecondParamType =
5714 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5715
5716 // Skip if either parameter isn't of enumeral type.
5717 if (!FirstParamType->isEnumeralType() ||
5718 !SecondParamType->isEnumeralType())
5719 continue;
5720
5721 // Add this operator to the set of known user-defined operators.
5722 UserDefinedBinaryOperators.insert(
5723 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5724 S.Context.getCanonicalType(SecondParamType)));
5725 }
5726 }
5727 }
5728
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005729 /// Set of (canonical) types that we've already handled.
5730 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5731
5732 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5733 for (BuiltinCandidateTypeSet::iterator
5734 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5735 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5736 Ptr != PtrEnd; ++Ptr) {
5737 // Don't add the same builtin candidate twice.
5738 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5739 continue;
5740
5741 QualType ParamTypes[2] = { *Ptr, *Ptr };
5742 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5743 CandidateSet);
5744 }
5745 for (BuiltinCandidateTypeSet::iterator
5746 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5747 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5748 Enum != EnumEnd; ++Enum) {
5749 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5750
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005751 // Don't add the same builtin candidate twice, or if a user defined
5752 // candidate exists.
5753 if (!AddedTypes.insert(CanonType) ||
5754 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5755 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005756 continue;
5757
5758 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005759 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5760 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005761 }
Douglas Gregor80af3132011-05-21 23:15:46 +00005762
5763 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5764 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5765 if (AddedTypes.insert(NullPtrTy) &&
5766 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5767 NullPtrTy))) {
5768 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5769 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5770 CandidateSet);
5771 }
5772 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005773 }
5774 }
5775
5776 // C++ [over.built]p13:
5777 //
5778 // For every cv-qualified or cv-unqualified object type T
5779 // there exist candidate operator functions of the form
5780 //
5781 // T* operator+(T*, ptrdiff_t);
5782 // T& operator[](T*, ptrdiff_t); [BELOW]
5783 // T* operator-(T*, ptrdiff_t);
5784 // T* operator+(ptrdiff_t, T*);
5785 // T& operator[](ptrdiff_t, T*); [BELOW]
5786 //
5787 // C++ [over.built]p14:
5788 //
5789 // For every T, where T is a pointer to object type, there
5790 // exist candidate operator functions of the form
5791 //
5792 // ptrdiff_t operator-(T, T);
5793 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5794 /// Set of (canonical) types that we've already handled.
5795 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5796
5797 for (int Arg = 0; Arg < 2; ++Arg) {
5798 QualType AsymetricParamTypes[2] = {
5799 S.Context.getPointerDiffType(),
5800 S.Context.getPointerDiffType(),
5801 };
5802 for (BuiltinCandidateTypeSet::iterator
5803 Ptr = CandidateTypes[Arg].pointer_begin(),
5804 PtrEnd = CandidateTypes[Arg].pointer_end();
5805 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005806 QualType PointeeTy = (*Ptr)->getPointeeType();
5807 if (!PointeeTy->isObjectType())
5808 continue;
5809
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005810 AsymetricParamTypes[Arg] = *Ptr;
5811 if (Arg == 0 || Op == OO_Plus) {
5812 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5813 // T* operator+(ptrdiff_t, T*);
5814 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5815 CandidateSet);
5816 }
5817 if (Op == OO_Minus) {
5818 // ptrdiff_t operator-(T, T);
5819 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5820 continue;
5821
5822 QualType ParamTypes[2] = { *Ptr, *Ptr };
5823 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5824 Args, 2, CandidateSet);
5825 }
5826 }
5827 }
5828 }
5829
5830 // C++ [over.built]p12:
5831 //
5832 // For every pair of promoted arithmetic types L and R, there
5833 // exist candidate operator functions of the form
5834 //
5835 // LR operator*(L, R);
5836 // LR operator/(L, R);
5837 // LR operator+(L, R);
5838 // LR operator-(L, R);
5839 // bool operator<(L, R);
5840 // bool operator>(L, R);
5841 // bool operator<=(L, R);
5842 // bool operator>=(L, R);
5843 // bool operator==(L, R);
5844 // bool operator!=(L, R);
5845 //
5846 // where LR is the result of the usual arithmetic conversions
5847 // between types L and R.
5848 //
5849 // C++ [over.built]p24:
5850 //
5851 // For every pair of promoted arithmetic types L and R, there exist
5852 // candidate operator functions of the form
5853 //
5854 // LR operator?(bool, L, R);
5855 //
5856 // where LR is the result of the usual arithmetic conversions
5857 // between types L and R.
5858 // Our candidates ignore the first parameter.
5859 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005860 if (!HasArithmeticOrEnumeralCandidateType)
5861 return;
5862
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005863 for (unsigned Left = FirstPromotedArithmeticType;
5864 Left < LastPromotedArithmeticType; ++Left) {
5865 for (unsigned Right = FirstPromotedArithmeticType;
5866 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005867 QualType LandR[2] = { getArithmeticType(Left),
5868 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005869 QualType Result =
5870 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005871 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005872 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5873 }
5874 }
5875
5876 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5877 // conditional operator for vector types.
5878 for (BuiltinCandidateTypeSet::iterator
5879 Vec1 = CandidateTypes[0].vector_begin(),
5880 Vec1End = CandidateTypes[0].vector_end();
5881 Vec1 != Vec1End; ++Vec1) {
5882 for (BuiltinCandidateTypeSet::iterator
5883 Vec2 = CandidateTypes[1].vector_begin(),
5884 Vec2End = CandidateTypes[1].vector_end();
5885 Vec2 != Vec2End; ++Vec2) {
5886 QualType LandR[2] = { *Vec1, *Vec2 };
5887 QualType Result = S.Context.BoolTy;
5888 if (!isComparison) {
5889 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5890 Result = *Vec1;
5891 else
5892 Result = *Vec2;
5893 }
5894
5895 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5896 }
5897 }
5898 }
5899
5900 // C++ [over.built]p17:
5901 //
5902 // For every pair of promoted integral types L and R, there
5903 // exist candidate operator functions of the form
5904 //
5905 // LR operator%(L, R);
5906 // LR operator&(L, R);
5907 // LR operator^(L, R);
5908 // LR operator|(L, R);
5909 // L operator<<(L, R);
5910 // L operator>>(L, R);
5911 //
5912 // where LR is the result of the usual arithmetic conversions
5913 // between types L and R.
5914 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005915 if (!HasArithmeticOrEnumeralCandidateType)
5916 return;
5917
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005918 for (unsigned Left = FirstPromotedIntegralType;
5919 Left < LastPromotedIntegralType; ++Left) {
5920 for (unsigned Right = FirstPromotedIntegralType;
5921 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005922 QualType LandR[2] = { getArithmeticType(Left),
5923 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005924 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5925 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005926 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005927 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5928 }
5929 }
5930 }
5931
5932 // C++ [over.built]p20:
5933 //
5934 // For every pair (T, VQ), where T is an enumeration or
5935 // pointer to member type and VQ is either volatile or
5936 // empty, there exist candidate operator functions of the form
5937 //
5938 // VQ T& operator=(VQ T&, T);
5939 void addAssignmentMemberPointerOrEnumeralOverloads() {
5940 /// Set of (canonical) types that we've already handled.
5941 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5942
5943 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5944 for (BuiltinCandidateTypeSet::iterator
5945 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5946 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5947 Enum != EnumEnd; ++Enum) {
5948 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5949 continue;
5950
5951 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5952 CandidateSet);
5953 }
5954
5955 for (BuiltinCandidateTypeSet::iterator
5956 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5957 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5958 MemPtr != MemPtrEnd; ++MemPtr) {
5959 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5960 continue;
5961
5962 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5963 CandidateSet);
5964 }
5965 }
5966 }
5967
5968 // C++ [over.built]p19:
5969 //
5970 // For every pair (T, VQ), where T is any type and VQ is either
5971 // volatile or empty, there exist candidate operator functions
5972 // of the form
5973 //
5974 // T*VQ& operator=(T*VQ&, T*);
5975 //
5976 // C++ [over.built]p21:
5977 //
5978 // For every pair (T, VQ), where T is a cv-qualified or
5979 // cv-unqualified object type and VQ is either volatile or
5980 // empty, there exist candidate operator functions of the form
5981 //
5982 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5983 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5984 void addAssignmentPointerOverloads(bool isEqualOp) {
5985 /// Set of (canonical) types that we've already handled.
5986 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5987
5988 for (BuiltinCandidateTypeSet::iterator
5989 Ptr = CandidateTypes[0].pointer_begin(),
5990 PtrEnd = CandidateTypes[0].pointer_end();
5991 Ptr != PtrEnd; ++Ptr) {
5992 // If this is operator=, keep track of the builtin candidates we added.
5993 if (isEqualOp)
5994 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005995 else if (!(*Ptr)->getPointeeType()->isObjectType())
5996 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005997
5998 // non-volatile version
5999 QualType ParamTypes[2] = {
6000 S.Context.getLValueReferenceType(*Ptr),
6001 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6002 };
6003 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6004 /*IsAssigmentOperator=*/ isEqualOp);
6005
6006 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6007 VisibleTypeConversionsQuals.hasVolatile()) {
6008 // volatile version
6009 ParamTypes[0] =
6010 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6011 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6012 /*IsAssigmentOperator=*/isEqualOp);
6013 }
6014 }
6015
6016 if (isEqualOp) {
6017 for (BuiltinCandidateTypeSet::iterator
6018 Ptr = CandidateTypes[1].pointer_begin(),
6019 PtrEnd = CandidateTypes[1].pointer_end();
6020 Ptr != PtrEnd; ++Ptr) {
6021 // Make sure we don't add the same candidate twice.
6022 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6023 continue;
6024
Chandler Carruth8e543b32010-12-12 08:17:55 +00006025 QualType ParamTypes[2] = {
6026 S.Context.getLValueReferenceType(*Ptr),
6027 *Ptr,
6028 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006029
6030 // non-volatile version
6031 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6032 /*IsAssigmentOperator=*/true);
6033
6034 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6035 VisibleTypeConversionsQuals.hasVolatile()) {
6036 // volatile version
6037 ParamTypes[0] =
6038 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006039 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6040 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006041 }
6042 }
6043 }
6044 }
6045
6046 // C++ [over.built]p18:
6047 //
6048 // For every triple (L, VQ, R), where L is an arithmetic type,
6049 // VQ is either volatile or empty, and R is a promoted
6050 // arithmetic type, there exist candidate operator functions of
6051 // the form
6052 //
6053 // VQ L& operator=(VQ L&, R);
6054 // VQ L& operator*=(VQ L&, R);
6055 // VQ L& operator/=(VQ L&, R);
6056 // VQ L& operator+=(VQ L&, R);
6057 // VQ L& operator-=(VQ L&, R);
6058 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006059 if (!HasArithmeticOrEnumeralCandidateType)
6060 return;
6061
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006062 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6063 for (unsigned Right = FirstPromotedArithmeticType;
6064 Right < LastPromotedArithmeticType; ++Right) {
6065 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006066 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006067
6068 // Add this built-in operator as a candidate (VQ is empty).
6069 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006070 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006071 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6072 /*IsAssigmentOperator=*/isEqualOp);
6073
6074 // Add this built-in operator as a candidate (VQ is 'volatile').
6075 if (VisibleTypeConversionsQuals.hasVolatile()) {
6076 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006077 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006078 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006079 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6080 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006081 /*IsAssigmentOperator=*/isEqualOp);
6082 }
6083 }
6084 }
6085
6086 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6087 for (BuiltinCandidateTypeSet::iterator
6088 Vec1 = CandidateTypes[0].vector_begin(),
6089 Vec1End = CandidateTypes[0].vector_end();
6090 Vec1 != Vec1End; ++Vec1) {
6091 for (BuiltinCandidateTypeSet::iterator
6092 Vec2 = CandidateTypes[1].vector_begin(),
6093 Vec2End = CandidateTypes[1].vector_end();
6094 Vec2 != Vec2End; ++Vec2) {
6095 QualType ParamTypes[2];
6096 ParamTypes[1] = *Vec2;
6097 // Add this built-in operator as a candidate (VQ is empty).
6098 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6099 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6100 /*IsAssigmentOperator=*/isEqualOp);
6101
6102 // Add this built-in operator as a candidate (VQ is 'volatile').
6103 if (VisibleTypeConversionsQuals.hasVolatile()) {
6104 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6105 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006106 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6107 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006108 /*IsAssigmentOperator=*/isEqualOp);
6109 }
6110 }
6111 }
6112 }
6113
6114 // C++ [over.built]p22:
6115 //
6116 // For every triple (L, VQ, R), where L is an integral type, VQ
6117 // is either volatile or empty, and R is a promoted integral
6118 // type, there exist candidate operator functions of the form
6119 //
6120 // VQ L& operator%=(VQ L&, R);
6121 // VQ L& operator<<=(VQ L&, R);
6122 // VQ L& operator>>=(VQ L&, R);
6123 // VQ L& operator&=(VQ L&, R);
6124 // VQ L& operator^=(VQ L&, R);
6125 // VQ L& operator|=(VQ L&, R);
6126 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006127 if (!HasArithmeticOrEnumeralCandidateType)
6128 return;
6129
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006130 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6131 for (unsigned Right = FirstPromotedIntegralType;
6132 Right < LastPromotedIntegralType; ++Right) {
6133 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006134 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006135
6136 // Add this built-in operator as a candidate (VQ is empty).
6137 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006138 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006139 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6140 if (VisibleTypeConversionsQuals.hasVolatile()) {
6141 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006142 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006143 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6144 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6145 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6146 CandidateSet);
6147 }
6148 }
6149 }
6150 }
6151
6152 // C++ [over.operator]p23:
6153 //
6154 // There also exist candidate operator functions of the form
6155 //
6156 // bool operator!(bool);
6157 // bool operator&&(bool, bool);
6158 // bool operator||(bool, bool);
6159 void addExclaimOverload() {
6160 QualType ParamTy = S.Context.BoolTy;
6161 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6162 /*IsAssignmentOperator=*/false,
6163 /*NumContextualBoolArguments=*/1);
6164 }
6165 void addAmpAmpOrPipePipeOverload() {
6166 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6167 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6168 /*IsAssignmentOperator=*/false,
6169 /*NumContextualBoolArguments=*/2);
6170 }
6171
6172 // C++ [over.built]p13:
6173 //
6174 // For every cv-qualified or cv-unqualified object type T there
6175 // exist candidate operator functions of the form
6176 //
6177 // T* operator+(T*, ptrdiff_t); [ABOVE]
6178 // T& operator[](T*, ptrdiff_t);
6179 // T* operator-(T*, ptrdiff_t); [ABOVE]
6180 // T* operator+(ptrdiff_t, T*); [ABOVE]
6181 // T& operator[](ptrdiff_t, T*);
6182 void addSubscriptOverloads() {
6183 for (BuiltinCandidateTypeSet::iterator
6184 Ptr = CandidateTypes[0].pointer_begin(),
6185 PtrEnd = CandidateTypes[0].pointer_end();
6186 Ptr != PtrEnd; ++Ptr) {
6187 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6188 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006189 if (!PointeeType->isObjectType())
6190 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006191
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006192 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6193
6194 // T& operator[](T*, ptrdiff_t)
6195 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6196 }
6197
6198 for (BuiltinCandidateTypeSet::iterator
6199 Ptr = CandidateTypes[1].pointer_begin(),
6200 PtrEnd = CandidateTypes[1].pointer_end();
6201 Ptr != PtrEnd; ++Ptr) {
6202 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6203 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006204 if (!PointeeType->isObjectType())
6205 continue;
6206
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006207 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6208
6209 // T& operator[](ptrdiff_t, T*)
6210 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6211 }
6212 }
6213
6214 // C++ [over.built]p11:
6215 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6216 // C1 is the same type as C2 or is a derived class of C2, T is an object
6217 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6218 // there exist candidate operator functions of the form
6219 //
6220 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6221 //
6222 // where CV12 is the union of CV1 and CV2.
6223 void addArrowStarOverloads() {
6224 for (BuiltinCandidateTypeSet::iterator
6225 Ptr = CandidateTypes[0].pointer_begin(),
6226 PtrEnd = CandidateTypes[0].pointer_end();
6227 Ptr != PtrEnd; ++Ptr) {
6228 QualType C1Ty = (*Ptr);
6229 QualType C1;
6230 QualifierCollector Q1;
6231 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6232 if (!isa<RecordType>(C1))
6233 continue;
6234 // heuristic to reduce number of builtin candidates in the set.
6235 // Add volatile/restrict version only if there are conversions to a
6236 // volatile/restrict type.
6237 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6238 continue;
6239 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6240 continue;
6241 for (BuiltinCandidateTypeSet::iterator
6242 MemPtr = CandidateTypes[1].member_pointer_begin(),
6243 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6244 MemPtr != MemPtrEnd; ++MemPtr) {
6245 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6246 QualType C2 = QualType(mptr->getClass(), 0);
6247 C2 = C2.getUnqualifiedType();
6248 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6249 break;
6250 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6251 // build CV12 T&
6252 QualType T = mptr->getPointeeType();
6253 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6254 T.isVolatileQualified())
6255 continue;
6256 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6257 T.isRestrictQualified())
6258 continue;
6259 T = Q1.apply(S.Context, T);
6260 QualType ResultTy = S.Context.getLValueReferenceType(T);
6261 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6262 }
6263 }
6264 }
6265
6266 // Note that we don't consider the first argument, since it has been
6267 // contextually converted to bool long ago. The candidates below are
6268 // therefore added as binary.
6269 //
6270 // C++ [over.built]p25:
6271 // For every type T, where T is a pointer, pointer-to-member, or scoped
6272 // enumeration type, there exist candidate operator functions of the form
6273 //
6274 // T operator?(bool, T, T);
6275 //
6276 void addConditionalOperatorOverloads() {
6277 /// Set of (canonical) types that we've already handled.
6278 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6279
6280 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6281 for (BuiltinCandidateTypeSet::iterator
6282 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6283 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6284 Ptr != PtrEnd; ++Ptr) {
6285 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6286 continue;
6287
6288 QualType ParamTypes[2] = { *Ptr, *Ptr };
6289 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6290 }
6291
6292 for (BuiltinCandidateTypeSet::iterator
6293 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6294 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6295 MemPtr != MemPtrEnd; ++MemPtr) {
6296 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6297 continue;
6298
6299 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6300 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6301 }
6302
6303 if (S.getLangOptions().CPlusPlus0x) {
6304 for (BuiltinCandidateTypeSet::iterator
6305 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6306 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6307 Enum != EnumEnd; ++Enum) {
6308 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6309 continue;
6310
6311 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6312 continue;
6313
6314 QualType ParamTypes[2] = { *Enum, *Enum };
6315 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6316 }
6317 }
6318 }
6319 }
6320};
6321
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006322} // end anonymous namespace
6323
6324/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6325/// operator overloads to the candidate set (C++ [over.built]), based
6326/// on the operator @p Op and the arguments given. For example, if the
6327/// operator is a binary '+', this routine might add "int
6328/// operator+(int, int)" to cover integer addition.
6329void
6330Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6331 SourceLocation OpLoc,
6332 Expr **Args, unsigned NumArgs,
6333 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006334 // Find all of the types that the arguments can convert to, but only
6335 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006336 // that make use of these types. Also record whether we encounter non-record
6337 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006338 Qualifiers VisibleTypeConversionsQuals;
6339 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006340 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6341 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006342
6343 bool HasNonRecordCandidateType = false;
6344 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006345 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006346 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6347 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6348 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6349 OpLoc,
6350 true,
6351 (Op == OO_Exclaim ||
6352 Op == OO_AmpAmp ||
6353 Op == OO_PipePipe),
6354 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006355 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6356 CandidateTypes[ArgIdx].hasNonRecordTypes();
6357 HasArithmeticOrEnumeralCandidateType =
6358 HasArithmeticOrEnumeralCandidateType ||
6359 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006360 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006361
Chandler Carruth00a38332010-12-13 01:44:01 +00006362 // Exit early when no non-record types have been added to the candidate set
6363 // for any of the arguments to the operator.
6364 if (!HasNonRecordCandidateType)
6365 return;
6366
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006367 // Setup an object to manage the common state for building overloads.
6368 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6369 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006370 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006371 CandidateTypes, CandidateSet);
6372
6373 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006374 switch (Op) {
6375 case OO_None:
6376 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00006377 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00006378
Chandler Carruth5184de02010-12-12 08:51:33 +00006379 case OO_New:
6380 case OO_Delete:
6381 case OO_Array_New:
6382 case OO_Array_Delete:
6383 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00006384 llvm_unreachable(
6385 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00006386
6387 case OO_Comma:
6388 case OO_Arrow:
6389 // C++ [over.match.oper]p3:
6390 // -- For the operator ',', the unary operator '&', or the
6391 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006392 break;
6393
6394 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006395 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006396 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006397 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006398
6399 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006400 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006401 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006402 } else {
6403 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6404 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6405 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006406 break;
6407
Chandler Carruth5184de02010-12-12 08:51:33 +00006408 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006409 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006410 OpBuilder.addUnaryStarPointerOverloads();
6411 else
6412 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6413 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006414
Chandler Carruth5184de02010-12-12 08:51:33 +00006415 case OO_Slash:
6416 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006417 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006418
6419 case OO_PlusPlus:
6420 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006421 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6422 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006423 break;
6424
Douglas Gregor84605ae2009-08-24 13:43:27 +00006425 case OO_EqualEqual:
6426 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006427 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006428 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006429
Douglas Gregora11693b2008-11-12 17:17:38 +00006430 case OO_Less:
6431 case OO_Greater:
6432 case OO_LessEqual:
6433 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006434 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006435 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6436 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006437
Douglas Gregora11693b2008-11-12 17:17:38 +00006438 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006439 case OO_Caret:
6440 case OO_Pipe:
6441 case OO_LessLess:
6442 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006443 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006444 break;
6445
Chandler Carruth5184de02010-12-12 08:51:33 +00006446 case OO_Amp: // '&' is either unary or binary
6447 if (NumArgs == 1)
6448 // C++ [over.match.oper]p3:
6449 // -- For the operator ',', the unary operator '&', or the
6450 // operator '->', the built-in candidates set is empty.
6451 break;
6452
6453 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6454 break;
6455
6456 case OO_Tilde:
6457 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6458 break;
6459
Douglas Gregora11693b2008-11-12 17:17:38 +00006460 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006461 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006462 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006463
6464 case OO_PlusEqual:
6465 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006466 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006467 // Fall through.
6468
6469 case OO_StarEqual:
6470 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006471 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006472 break;
6473
6474 case OO_PercentEqual:
6475 case OO_LessLessEqual:
6476 case OO_GreaterGreaterEqual:
6477 case OO_AmpEqual:
6478 case OO_CaretEqual:
6479 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006480 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006481 break;
6482
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006483 case OO_Exclaim:
6484 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006485 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006486
Douglas Gregora11693b2008-11-12 17:17:38 +00006487 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006488 case OO_PipePipe:
6489 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006490 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006491
6492 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006493 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006494 break;
6495
6496 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006497 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006498 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006499
6500 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006501 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006502 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6503 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006504 }
6505}
6506
Douglas Gregore254f902009-02-04 00:32:51 +00006507/// \brief Add function candidates found via argument-dependent lookup
6508/// to the set of overloading candidates.
6509///
6510/// This routine performs argument-dependent name lookup based on the
6511/// given function name (which may also be an operator name) and adds
6512/// all of the overload candidates found by ADL to the overload
6513/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006514void
Douglas Gregore254f902009-02-04 00:32:51 +00006515Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006516 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006517 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006518 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006519 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006520 bool PartialOverloading,
6521 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006522 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006523
John McCall91f61fc2010-01-26 06:04:06 +00006524 // FIXME: This approach for uniquing ADL results (and removing
6525 // redundant candidates from the set) relies on pointer-equality,
6526 // which means we need to key off the canonical decl. However,
6527 // always going back to the canonical decl might not get us the
6528 // right set of default arguments. What default arguments are
6529 // we supposed to consider on ADL candidates, anyway?
6530
Douglas Gregorcabea402009-09-22 15:41:20 +00006531 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006532 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6533 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006534
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006535 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006536 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6537 CandEnd = CandidateSet.end();
6538 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006539 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006540 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006541 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006542 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006543 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006544
6545 // For each of the ADL candidates we found, add it to the overload
6546 // set.
John McCall8fe68082010-01-26 07:16:45 +00006547 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006548 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006549 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006550 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006551 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006552
John McCalla0296f72010-03-19 07:35:19 +00006553 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006554 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006555 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006556 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006557 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006558 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006559 }
Douglas Gregore254f902009-02-04 00:32:51 +00006560}
6561
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006562/// isBetterOverloadCandidate - Determines whether the first overload
6563/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006564bool
John McCall5c32be02010-08-24 20:38:10 +00006565isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006566 const OverloadCandidate &Cand1,
6567 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006568 SourceLocation Loc,
6569 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006570 // Define viable functions to be better candidates than non-viable
6571 // functions.
6572 if (!Cand2.Viable)
6573 return Cand1.Viable;
6574 else if (!Cand1.Viable)
6575 return false;
6576
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006577 // C++ [over.match.best]p1:
6578 //
6579 // -- if F is a static member function, ICS1(F) is defined such
6580 // that ICS1(F) is neither better nor worse than ICS1(G) for
6581 // any function G, and, symmetrically, ICS1(G) is neither
6582 // better nor worse than ICS1(F).
6583 unsigned StartArg = 0;
6584 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6585 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006586
Douglas Gregord3cb3562009-07-07 23:38:56 +00006587 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006588 // A viable function F1 is defined to be a better function than another
6589 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006590 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006591 unsigned NumArgs = Cand1.Conversions.size();
6592 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6593 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006594 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006595 switch (CompareImplicitConversionSequences(S,
6596 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006597 Cand2.Conversions[ArgIdx])) {
6598 case ImplicitConversionSequence::Better:
6599 // Cand1 has a better conversion sequence.
6600 HasBetterConversion = true;
6601 break;
6602
6603 case ImplicitConversionSequence::Worse:
6604 // Cand1 can't be better than Cand2.
6605 return false;
6606
6607 case ImplicitConversionSequence::Indistinguishable:
6608 // Do nothing.
6609 break;
6610 }
6611 }
6612
Mike Stump11289f42009-09-09 15:08:12 +00006613 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006614 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006615 if (HasBetterConversion)
6616 return true;
6617
Mike Stump11289f42009-09-09 15:08:12 +00006618 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006619 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006620 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006621 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6622 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006623
6624 // -- F1 and F2 are function template specializations, and the function
6625 // template for F1 is more specialized than the template for F2
6626 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006627 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006628 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006629 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006630 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006631 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6632 Cand2.Function->getPrimaryTemplate(),
6633 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006634 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006635 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006636 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006637 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006638 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006639
Douglas Gregora1f013e2008-11-07 22:36:19 +00006640 // -- the context is an initialization by user-defined conversion
6641 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6642 // from the return type of F1 to the destination type (i.e.,
6643 // the type of the entity being initialized) is a better
6644 // conversion sequence than the standard conversion sequence
6645 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006646 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006647 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006648 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006649 switch (CompareStandardConversionSequences(S,
6650 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006651 Cand2.FinalConversion)) {
6652 case ImplicitConversionSequence::Better:
6653 // Cand1 has a better conversion sequence.
6654 return true;
6655
6656 case ImplicitConversionSequence::Worse:
6657 // Cand1 can't be better than Cand2.
6658 return false;
6659
6660 case ImplicitConversionSequence::Indistinguishable:
6661 // Do nothing
6662 break;
6663 }
6664 }
6665
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006666 return false;
6667}
6668
Mike Stump11289f42009-09-09 15:08:12 +00006669/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006670/// within an overload candidate set.
6671///
6672/// \param CandidateSet the set of candidate functions.
6673///
6674/// \param Loc the location of the function name (or operator symbol) for
6675/// which overload resolution occurs.
6676///
Mike Stump11289f42009-09-09 15:08:12 +00006677/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006678/// function, Best points to the candidate function found.
6679///
6680/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006681OverloadingResult
6682OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006683 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00006684 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006685 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006686 Best = end();
6687 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6688 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006689 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006690 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006691 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006692 }
6693
6694 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006695 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006696 return OR_No_Viable_Function;
6697
6698 // Make sure that this function is better than every other viable
6699 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006700 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006701 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006702 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006703 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006704 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006705 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006706 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006707 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006708 }
Mike Stump11289f42009-09-09 15:08:12 +00006709
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006710 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006711 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00006712 (Best->Function->isDeleted() ||
6713 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006714 return OR_Deleted;
6715
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006716 return OR_Success;
6717}
6718
John McCall53262c92010-01-12 02:15:36 +00006719namespace {
6720
6721enum OverloadCandidateKind {
6722 oc_function,
6723 oc_method,
6724 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006725 oc_function_template,
6726 oc_method_template,
6727 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006728 oc_implicit_default_constructor,
6729 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006730 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006731 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006732 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00006733 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006734};
6735
John McCalle1ac8d12010-01-13 00:25:19 +00006736OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6737 FunctionDecl *Fn,
6738 std::string &Description) {
6739 bool isTemplate = false;
6740
6741 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6742 isTemplate = true;
6743 Description = S.getTemplateArgumentBindingsText(
6744 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6745 }
John McCallfd0b2f82010-01-06 09:43:14 +00006746
6747 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006748 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006749 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006750
Sebastian Redl08905022011-02-05 19:23:19 +00006751 if (Ctor->getInheritedConstructor())
6752 return oc_implicit_inherited_constructor;
6753
Alexis Hunt119c10e2011-05-25 23:16:36 +00006754 if (Ctor->isDefaultConstructor())
6755 return oc_implicit_default_constructor;
6756
6757 if (Ctor->isMoveConstructor())
6758 return oc_implicit_move_constructor;
6759
6760 assert(Ctor->isCopyConstructor() &&
6761 "unexpected sort of implicit constructor");
6762 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006763 }
6764
6765 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6766 // This actually gets spelled 'candidate function' for now, but
6767 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006768 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006769 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006770
Alexis Hunt119c10e2011-05-25 23:16:36 +00006771 if (Meth->isMoveAssignmentOperator())
6772 return oc_implicit_move_assignment;
6773
Douglas Gregorec3bec02010-09-27 22:37:28 +00006774 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006775 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006776 return oc_implicit_copy_assignment;
6777 }
6778
John McCalle1ac8d12010-01-13 00:25:19 +00006779 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006780}
6781
Sebastian Redl08905022011-02-05 19:23:19 +00006782void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6783 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6784 if (!Ctor) return;
6785
6786 Ctor = Ctor->getInheritedConstructor();
6787 if (!Ctor) return;
6788
6789 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6790}
6791
John McCall53262c92010-01-12 02:15:36 +00006792} // end anonymous namespace
6793
6794// Notes the location of an overload candidate.
6795void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006796 std::string FnDesc;
6797 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6798 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6799 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00006800 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00006801}
6802
Douglas Gregorb491ed32011-02-19 21:32:49 +00006803//Notes the location of all overload candidates designated through
6804// OverloadedExpr
6805void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6806 assert(OverloadedExpr->getType() == Context.OverloadTy);
6807
6808 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6809 OverloadExpr *OvlExpr = Ovl.Expression;
6810
6811 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6812 IEnd = OvlExpr->decls_end();
6813 I != IEnd; ++I) {
6814 if (FunctionTemplateDecl *FunTmpl =
6815 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6816 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6817 } else if (FunctionDecl *Fun
6818 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6819 NoteOverloadCandidate(Fun);
6820 }
6821 }
6822}
6823
John McCall0d1da222010-01-12 00:44:57 +00006824/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6825/// "lead" diagnostic; it will be given two arguments, the source and
6826/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006827void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6828 Sema &S,
6829 SourceLocation CaretLoc,
6830 const PartialDiagnostic &PDiag) const {
6831 S.Diag(CaretLoc, PDiag)
6832 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006833 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006834 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6835 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006836 }
John McCall12f97bc2010-01-08 04:41:39 +00006837}
6838
John McCall0d1da222010-01-12 00:44:57 +00006839namespace {
6840
John McCall6a61b522010-01-13 09:16:55 +00006841void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6842 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6843 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006844 assert(Cand->Function && "for now, candidate must be a function");
6845 FunctionDecl *Fn = Cand->Function;
6846
6847 // There's a conversion slot for the object argument if this is a
6848 // non-constructor method. Note that 'I' corresponds the
6849 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006850 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006851 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006852 if (I == 0)
6853 isObjectArgument = true;
6854 else
6855 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006856 }
6857
John McCalle1ac8d12010-01-13 00:25:19 +00006858 std::string FnDesc;
6859 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6860
John McCall6a61b522010-01-13 09:16:55 +00006861 Expr *FromExpr = Conv.Bad.FromExpr;
6862 QualType FromTy = Conv.Bad.getFromType();
6863 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006864
John McCallfb7ad0f2010-02-02 02:42:52 +00006865 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006866 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006867 Expr *E = FromExpr->IgnoreParens();
6868 if (isa<UnaryOperator>(E))
6869 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006870 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006871
6872 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6873 << (unsigned) FnKind << FnDesc
6874 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6875 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006876 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00006877 return;
6878 }
6879
John McCall6d174642010-01-23 08:10:49 +00006880 // Do some hand-waving analysis to see if the non-viability is due
6881 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006882 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6883 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6884 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6885 CToTy = RT->getPointeeType();
6886 else {
6887 // TODO: detect and diagnose the full richness of const mismatches.
6888 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6889 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6890 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6891 }
6892
6893 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6894 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6895 // It is dumb that we have to do this here.
6896 while (isa<ArrayType>(CFromTy))
6897 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6898 while (isa<ArrayType>(CToTy))
6899 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6900
6901 Qualifiers FromQs = CFromTy.getQualifiers();
6902 Qualifiers ToQs = CToTy.getQualifiers();
6903
6904 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6905 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6906 << (unsigned) FnKind << FnDesc
6907 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6908 << FromTy
6909 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6910 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006911 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006912 return;
6913 }
6914
John McCall31168b02011-06-15 23:02:42 +00006915 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00006916 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00006917 << (unsigned) FnKind << FnDesc
6918 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6919 << FromTy
6920 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
6921 << (unsigned) isObjectArgument << I+1;
6922 MaybeEmitInheritedConstructorNote(S, Fn);
6923 return;
6924 }
6925
Douglas Gregoraec25842011-04-26 23:16:46 +00006926 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
6927 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
6928 << (unsigned) FnKind << FnDesc
6929 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6930 << FromTy
6931 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
6932 << (unsigned) isObjectArgument << I+1;
6933 MaybeEmitInheritedConstructorNote(S, Fn);
6934 return;
6935 }
6936
John McCall47000992010-01-14 03:28:57 +00006937 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6938 assert(CVR && "unexpected qualifiers mismatch");
6939
6940 if (isObjectArgument) {
6941 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6942 << (unsigned) FnKind << FnDesc
6943 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6944 << FromTy << (CVR - 1);
6945 } else {
6946 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6947 << (unsigned) FnKind << FnDesc
6948 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6949 << FromTy << (CVR - 1) << I+1;
6950 }
Sebastian Redl08905022011-02-05 19:23:19 +00006951 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00006952 return;
6953 }
6954
Sebastian Redla72462c2011-09-24 17:48:32 +00006955 // Special diagnostic for failure to convert an initializer list, since
6956 // telling the user that it has type void is not useful.
6957 if (FromExpr && isa<InitListExpr>(FromExpr)) {
6958 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
6959 << (unsigned) FnKind << FnDesc
6960 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6961 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6962 MaybeEmitInheritedConstructorNote(S, Fn);
6963 return;
6964 }
6965
John McCall6d174642010-01-23 08:10:49 +00006966 // Diagnose references or pointers to incomplete types differently,
6967 // since it's far from impossible that the incompleteness triggered
6968 // the failure.
6969 QualType TempFromTy = FromTy.getNonReferenceType();
6970 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6971 TempFromTy = PTy->getPointeeType();
6972 if (TempFromTy->isIncompleteType()) {
6973 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6974 << (unsigned) FnKind << FnDesc
6975 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6976 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006977 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00006978 return;
6979 }
6980
Douglas Gregor56f2e342010-06-30 23:01:39 +00006981 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006982 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006983 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6984 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6985 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6986 FromPtrTy->getPointeeType()) &&
6987 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6988 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006989 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00006990 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006991 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006992 }
6993 } else if (const ObjCObjectPointerType *FromPtrTy
6994 = FromTy->getAs<ObjCObjectPointerType>()) {
6995 if (const ObjCObjectPointerType *ToPtrTy
6996 = ToTy->getAs<ObjCObjectPointerType>())
6997 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6998 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6999 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7000 FromPtrTy->getPointeeType()) &&
7001 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007002 BaseToDerivedConversion = 2;
7003 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7004 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7005 !FromTy->isIncompleteType() &&
7006 !ToRefTy->getPointeeType()->isIncompleteType() &&
7007 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7008 BaseToDerivedConversion = 3;
7009 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007010
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007011 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007012 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007013 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007014 << (unsigned) FnKind << FnDesc
7015 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007016 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007017 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007018 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007019 return;
7020 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007021
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007022 if (isa<ObjCObjectPointerType>(CFromTy) &&
7023 isa<PointerType>(CToTy)) {
7024 Qualifiers FromQs = CFromTy.getQualifiers();
7025 Qualifiers ToQs = CToTy.getQualifiers();
7026 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7027 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7028 << (unsigned) FnKind << FnDesc
7029 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7030 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7031 MaybeEmitInheritedConstructorNote(S, Fn);
7032 return;
7033 }
7034 }
7035
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007036 // Emit the generic diagnostic and, optionally, add the hints to it.
7037 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7038 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007039 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007040 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7041 << (unsigned) (Cand->Fix.Kind);
7042
7043 // If we can fix the conversion, suggest the FixIts.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007044 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007045 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7046 HI != HE; ++HI)
7047 FDiag << *HI;
7048 S.Diag(Fn->getLocation(), FDiag);
7049
Sebastian Redl08905022011-02-05 19:23:19 +00007050 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007051}
7052
7053void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7054 unsigned NumFormalArgs) {
7055 // TODO: treat calls to a missing default constructor as a special case
7056
7057 FunctionDecl *Fn = Cand->Function;
7058 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7059
7060 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007061
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00007062 // With invalid overloaded operators, it's possible that we think we
7063 // have an arity mismatch when it fact it looks like we have the
7064 // right number of arguments, because only overloaded operators have
7065 // the weird behavior of overloading member and non-member functions.
7066 // Just don't report anything.
7067 if (Fn->isInvalidDecl() &&
7068 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7069 return;
7070
John McCall6a61b522010-01-13 09:16:55 +00007071 // at least / at most / exactly
7072 unsigned mode, modeCount;
7073 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007074 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7075 (Cand->FailureKind == ovl_fail_bad_deduction &&
7076 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007077 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00007078 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00007079 mode = 0; // "at least"
7080 else
7081 mode = 2; // "exactly"
7082 modeCount = MinParams;
7083 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007084 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7085 (Cand->FailureKind == ovl_fail_bad_deduction &&
7086 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00007087 if (MinParams != FnTy->getNumArgs())
7088 mode = 1; // "at most"
7089 else
7090 mode = 2; // "exactly"
7091 modeCount = FnTy->getNumArgs();
7092 }
7093
7094 std::string Description;
7095 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7096
7097 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007098 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00007099 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00007100 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007101}
7102
John McCall8b9ed552010-02-01 18:53:26 +00007103/// Diagnose a failed template-argument deduction.
7104void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7105 Expr **Args, unsigned NumArgs) {
7106 FunctionDecl *Fn = Cand->Function; // pattern
7107
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007108 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007109 NamedDecl *ParamD;
7110 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7111 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7112 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007113 switch (Cand->DeductionFailure.Result) {
7114 case Sema::TDK_Success:
7115 llvm_unreachable("TDK_success while diagnosing bad deduction");
7116
7117 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007118 assert(ParamD && "no parameter found for incomplete deduction result");
7119 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7120 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007121 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007122 return;
7123 }
7124
John McCall42d7d192010-08-05 09:05:08 +00007125 case Sema::TDK_Underqualified: {
7126 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7127 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7128
7129 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7130
7131 // Param will have been canonicalized, but it should just be a
7132 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007133 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007134 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007135 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007136 assert(S.Context.hasSameType(Param, NonCanonParam));
7137
7138 // Arg has also been canonicalized, but there's nothing we can do
7139 // about that. It also doesn't matter as much, because it won't
7140 // have any template parameters in it (because deduction isn't
7141 // done on dependent types).
7142 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7143
7144 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7145 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007146 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007147 return;
7148 }
7149
7150 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007151 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007152 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007153 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007154 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007155 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007156 which = 1;
7157 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007158 which = 2;
7159 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007160
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007161 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007162 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007163 << *Cand->DeductionFailure.getFirstArg()
7164 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007165 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007166 return;
7167 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007168
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007169 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007170 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007171 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007172 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007173 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7174 << ParamD->getDeclName();
7175 else {
7176 int index = 0;
7177 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7178 index = TTP->getIndex();
7179 else if (NonTypeTemplateParmDecl *NTTP
7180 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7181 index = NTTP->getIndex();
7182 else
7183 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007184 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007185 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7186 << (index + 1);
7187 }
Sebastian Redl08905022011-02-05 19:23:19 +00007188 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007189 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007190
Douglas Gregor02eb4832010-05-08 18:13:28 +00007191 case Sema::TDK_TooManyArguments:
7192 case Sema::TDK_TooFewArguments:
7193 DiagnoseArityMismatch(S, Cand, NumArgs);
7194 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007195
7196 case Sema::TDK_InstantiationDepth:
7197 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007198 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007199 return;
7200
7201 case Sema::TDK_SubstitutionFailure: {
7202 std::string ArgString;
7203 if (TemplateArgumentList *Args
7204 = Cand->DeductionFailure.getTemplateArgumentList())
7205 ArgString = S.getTemplateArgumentBindingsText(
7206 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7207 *Args);
7208 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7209 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007210 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007211 return;
7212 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007213
John McCall8b9ed552010-02-01 18:53:26 +00007214 // TODO: diagnose these individually, then kill off
7215 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007216 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007217 case Sema::TDK_FailedOverloadResolution:
7218 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007219 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007220 return;
7221 }
7222}
7223
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007224/// CUDA: diagnose an invalid call across targets.
7225void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7226 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7227 FunctionDecl *Callee = Cand->Function;
7228
7229 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7230 CalleeTarget = S.IdentifyCUDATarget(Callee);
7231
7232 std::string FnDesc;
7233 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7234
7235 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7236 << (unsigned) FnKind << CalleeTarget << CallerTarget;
7237}
7238
John McCall8b9ed552010-02-01 18:53:26 +00007239/// Generates a 'note' diagnostic for an overload candidate. We've
7240/// already generated a primary error at the call site.
7241///
7242/// It really does need to be a single diagnostic with its caret
7243/// pointed at the candidate declaration. Yes, this creates some
7244/// major challenges of technical writing. Yes, this makes pointing
7245/// out problems with specific arguments quite awkward. It's still
7246/// better than generating twenty screens of text for every failed
7247/// overload.
7248///
7249/// It would be great to be able to express per-candidate problems
7250/// more richly for those diagnostic clients that cared, but we'd
7251/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007252void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7253 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007254 FunctionDecl *Fn = Cand->Function;
7255
John McCall12f97bc2010-01-08 04:41:39 +00007256 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007257 if (Cand->Viable && (Fn->isDeleted() ||
7258 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007259 std::string FnDesc;
7260 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007261
7262 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007263 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007264 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007265 return;
John McCall12f97bc2010-01-08 04:41:39 +00007266 }
7267
John McCalle1ac8d12010-01-13 00:25:19 +00007268 // We don't really have anything else to say about viable candidates.
7269 if (Cand->Viable) {
7270 S.NoteOverloadCandidate(Fn);
7271 return;
7272 }
John McCall0d1da222010-01-12 00:44:57 +00007273
John McCall6a61b522010-01-13 09:16:55 +00007274 switch (Cand->FailureKind) {
7275 case ovl_fail_too_many_arguments:
7276 case ovl_fail_too_few_arguments:
7277 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007278
John McCall6a61b522010-01-13 09:16:55 +00007279 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007280 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7281
John McCallfe796dd2010-01-23 05:17:32 +00007282 case ovl_fail_trivial_conversion:
7283 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007284 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007285 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007286
John McCall65eb8792010-02-25 01:37:24 +00007287 case ovl_fail_bad_conversion: {
7288 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7289 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007290 if (Cand->Conversions[I].isBad())
7291 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007292
John McCall6a61b522010-01-13 09:16:55 +00007293 // FIXME: this currently happens when we're called from SemaInit
7294 // when user-conversion overload fails. Figure out how to handle
7295 // those conditions and diagnose them well.
7296 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007297 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007298
7299 case ovl_fail_bad_target:
7300 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00007301 }
John McCalld3224162010-01-08 00:58:21 +00007302}
7303
7304void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7305 // Desugar the type of the surrogate down to a function type,
7306 // retaining as many typedefs as possible while still showing
7307 // the function type (and, therefore, its parameter types).
7308 QualType FnType = Cand->Surrogate->getConversionType();
7309 bool isLValueReference = false;
7310 bool isRValueReference = false;
7311 bool isPointer = false;
7312 if (const LValueReferenceType *FnTypeRef =
7313 FnType->getAs<LValueReferenceType>()) {
7314 FnType = FnTypeRef->getPointeeType();
7315 isLValueReference = true;
7316 } else if (const RValueReferenceType *FnTypeRef =
7317 FnType->getAs<RValueReferenceType>()) {
7318 FnType = FnTypeRef->getPointeeType();
7319 isRValueReference = true;
7320 }
7321 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7322 FnType = FnTypePtr->getPointeeType();
7323 isPointer = true;
7324 }
7325 // Desugar down to a function type.
7326 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7327 // Reconstruct the pointer/reference as appropriate.
7328 if (isPointer) FnType = S.Context.getPointerType(FnType);
7329 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7330 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7331
7332 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7333 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007334 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007335}
7336
7337void NoteBuiltinOperatorCandidate(Sema &S,
7338 const char *Opc,
7339 SourceLocation OpLoc,
7340 OverloadCandidate *Cand) {
7341 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7342 std::string TypeStr("operator");
7343 TypeStr += Opc;
7344 TypeStr += "(";
7345 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7346 if (Cand->Conversions.size() == 1) {
7347 TypeStr += ")";
7348 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7349 } else {
7350 TypeStr += ", ";
7351 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7352 TypeStr += ")";
7353 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7354 }
7355}
7356
7357void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7358 OverloadCandidate *Cand) {
7359 unsigned NoOperands = Cand->Conversions.size();
7360 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7361 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007362 if (ICS.isBad()) break; // all meaningless after first invalid
7363 if (!ICS.isAmbiguous()) continue;
7364
John McCall5c32be02010-08-24 20:38:10 +00007365 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007366 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007367 }
7368}
7369
John McCall3712d9e2010-01-15 23:32:50 +00007370SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7371 if (Cand->Function)
7372 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007373 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007374 return Cand->Surrogate->getLocation();
7375 return SourceLocation();
7376}
7377
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007378static unsigned
7379RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00007380 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007381 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00007382 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007383
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007384 case Sema::TDK_Incomplete:
7385 return 1;
7386
7387 case Sema::TDK_Underqualified:
7388 case Sema::TDK_Inconsistent:
7389 return 2;
7390
7391 case Sema::TDK_SubstitutionFailure:
7392 case Sema::TDK_NonDeducedMismatch:
7393 return 3;
7394
7395 case Sema::TDK_InstantiationDepth:
7396 case Sema::TDK_FailedOverloadResolution:
7397 return 4;
7398
7399 case Sema::TDK_InvalidExplicitArguments:
7400 return 5;
7401
7402 case Sema::TDK_TooManyArguments:
7403 case Sema::TDK_TooFewArguments:
7404 return 6;
7405 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007406 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007407}
7408
John McCallad2587a2010-01-12 00:48:53 +00007409struct CompareOverloadCandidatesForDisplay {
7410 Sema &S;
7411 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007412
7413 bool operator()(const OverloadCandidate *L,
7414 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007415 // Fast-path this check.
7416 if (L == R) return false;
7417
John McCall12f97bc2010-01-08 04:41:39 +00007418 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007419 if (L->Viable) {
7420 if (!R->Viable) return true;
7421
7422 // TODO: introduce a tri-valued comparison for overload
7423 // candidates. Would be more worthwhile if we had a sort
7424 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007425 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7426 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007427 } else if (R->Viable)
7428 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007429
John McCall3712d9e2010-01-15 23:32:50 +00007430 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007431
John McCall3712d9e2010-01-15 23:32:50 +00007432 // Criteria by which we can sort non-viable candidates:
7433 if (!L->Viable) {
7434 // 1. Arity mismatches come after other candidates.
7435 if (L->FailureKind == ovl_fail_too_many_arguments ||
7436 L->FailureKind == ovl_fail_too_few_arguments)
7437 return false;
7438 if (R->FailureKind == ovl_fail_too_many_arguments ||
7439 R->FailureKind == ovl_fail_too_few_arguments)
7440 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007441
John McCallfe796dd2010-01-23 05:17:32 +00007442 // 2. Bad conversions come first and are ordered by the number
7443 // of bad conversions and quality of good conversions.
7444 if (L->FailureKind == ovl_fail_bad_conversion) {
7445 if (R->FailureKind != ovl_fail_bad_conversion)
7446 return true;
7447
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007448 // The conversion that can be fixed with a smaller number of changes,
7449 // comes first.
7450 unsigned numLFixes = L->Fix.NumConversionsFixed;
7451 unsigned numRFixes = R->Fix.NumConversionsFixed;
7452 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7453 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007454 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007455 if (numLFixes < numRFixes)
7456 return true;
7457 else
7458 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007459 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007460
John McCallfe796dd2010-01-23 05:17:32 +00007461 // If there's any ordering between the defined conversions...
7462 // FIXME: this might not be transitive.
7463 assert(L->Conversions.size() == R->Conversions.size());
7464
7465 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007466 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7467 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007468 switch (CompareImplicitConversionSequences(S,
7469 L->Conversions[I],
7470 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007471 case ImplicitConversionSequence::Better:
7472 leftBetter++;
7473 break;
7474
7475 case ImplicitConversionSequence::Worse:
7476 leftBetter--;
7477 break;
7478
7479 case ImplicitConversionSequence::Indistinguishable:
7480 break;
7481 }
7482 }
7483 if (leftBetter > 0) return true;
7484 if (leftBetter < 0) return false;
7485
7486 } else if (R->FailureKind == ovl_fail_bad_conversion)
7487 return false;
7488
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007489 if (L->FailureKind == ovl_fail_bad_deduction) {
7490 if (R->FailureKind != ovl_fail_bad_deduction)
7491 return true;
7492
7493 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7494 return RankDeductionFailure(L->DeductionFailure)
7495 <= RankDeductionFailure(R->DeductionFailure);
7496 }
7497
John McCall3712d9e2010-01-15 23:32:50 +00007498 // TODO: others?
7499 }
7500
7501 // Sort everything else by location.
7502 SourceLocation LLoc = GetLocationForCandidate(L);
7503 SourceLocation RLoc = GetLocationForCandidate(R);
7504
7505 // Put candidates without locations (e.g. builtins) at the end.
7506 if (LLoc.isInvalid()) return false;
7507 if (RLoc.isInvalid()) return true;
7508
7509 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007510 }
7511};
7512
John McCallfe796dd2010-01-23 05:17:32 +00007513/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007514/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00007515void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7516 Expr **Args, unsigned NumArgs) {
7517 assert(!Cand->Viable);
7518
7519 // Don't do anything on failures other than bad conversion.
7520 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7521
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007522 // We only want the FixIts if all the arguments can be corrected.
7523 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00007524 // Use a implicit copy initialization to check conversion fixes.
7525 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007526
John McCallfe796dd2010-01-23 05:17:32 +00007527 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007528 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007529 unsigned ConvCount = Cand->Conversions.size();
7530 while (true) {
7531 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7532 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007533 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00007534 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00007535 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007536 }
John McCallfe796dd2010-01-23 05:17:32 +00007537 }
7538
7539 if (ConvIdx == ConvCount)
7540 return;
7541
John McCall65eb8792010-02-25 01:37:24 +00007542 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7543 "remaining conversion is initialized?");
7544
Douglas Gregoradc7a702010-04-16 17:45:54 +00007545 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007546 // operation somehow.
7547 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007548
7549 const FunctionProtoType* Proto;
7550 unsigned ArgIdx = ConvIdx;
7551
7552 if (Cand->IsSurrogate) {
7553 QualType ConvType
7554 = Cand->Surrogate->getConversionType().getNonReferenceType();
7555 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7556 ConvType = ConvPtrType->getPointeeType();
7557 Proto = ConvType->getAs<FunctionProtoType>();
7558 ArgIdx--;
7559 } else if (Cand->Function) {
7560 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7561 if (isa<CXXMethodDecl>(Cand->Function) &&
7562 !isa<CXXConstructorDecl>(Cand->Function))
7563 ArgIdx--;
7564 } else {
7565 // Builtin binary operator with a bad first conversion.
7566 assert(ConvCount <= 3);
7567 for (; ConvIdx != ConvCount; ++ConvIdx)
7568 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007569 = TryCopyInitialization(S, Args[ConvIdx],
7570 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007571 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007572 /*InOverloadResolution*/ true,
7573 /*AllowObjCWritebackConversion=*/
7574 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00007575 return;
7576 }
7577
7578 // Fill in the rest of the conversions.
7579 unsigned NumArgsInProto = Proto->getNumArgs();
7580 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007581 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00007582 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007583 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007584 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007585 /*InOverloadResolution=*/true,
7586 /*AllowObjCWritebackConversion=*/
7587 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007588 // Store the FixIt in the candidate if it exists.
7589 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00007590 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007591 }
John McCallfe796dd2010-01-23 05:17:32 +00007592 else
7593 Cand->Conversions[ConvIdx].setEllipsis();
7594 }
7595}
7596
John McCalld3224162010-01-08 00:58:21 +00007597} // end anonymous namespace
7598
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007599/// PrintOverloadCandidates - When overload resolution fails, prints
7600/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007601/// set.
John McCall5c32be02010-08-24 20:38:10 +00007602void OverloadCandidateSet::NoteCandidates(Sema &S,
7603 OverloadCandidateDisplayKind OCD,
7604 Expr **Args, unsigned NumArgs,
7605 const char *Opc,
7606 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007607 // Sort the candidates by viability and position. Sorting directly would
7608 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007609 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007610 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7611 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007612 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007613 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007614 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007615 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007616 if (Cand->Function || Cand->IsSurrogate)
7617 Cands.push_back(Cand);
7618 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7619 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007620 }
7621 }
7622
John McCallad2587a2010-01-12 00:48:53 +00007623 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007624 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007625
John McCall0d1da222010-01-12 00:44:57 +00007626 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007627
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007628 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00007629 const DiagnosticsEngine::OverloadsShown ShowOverloads =
7630 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007631 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007632 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7633 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007634
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007635 // Set an arbitrary limit on the number of candidate functions we'll spam
7636 // the user with. FIXME: This limit should depend on details of the
7637 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00007638 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007639 break;
7640 }
7641 ++CandsShown;
7642
John McCalld3224162010-01-08 00:58:21 +00007643 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007644 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007645 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007646 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007647 else {
7648 assert(Cand->Viable &&
7649 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007650 // Generally we only see ambiguities including viable builtin
7651 // operators if overload resolution got screwed up by an
7652 // ambiguous user-defined conversion.
7653 //
7654 // FIXME: It's quite possible for different conversions to see
7655 // different ambiguities, though.
7656 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007657 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007658 ReportedAmbiguousConversions = true;
7659 }
John McCalld3224162010-01-08 00:58:21 +00007660
John McCall0d1da222010-01-12 00:44:57 +00007661 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007662 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007663 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007664 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007665
7666 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007667 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007668}
7669
Douglas Gregorb491ed32011-02-19 21:32:49 +00007670// [PossiblyAFunctionType] --> [Return]
7671// NonFunctionType --> NonFunctionType
7672// R (A) --> R(A)
7673// R (*)(A) --> R (A)
7674// R (&)(A) --> R (A)
7675// R (S::*)(A) --> R (A)
7676QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7677 QualType Ret = PossiblyAFunctionType;
7678 if (const PointerType *ToTypePtr =
7679 PossiblyAFunctionType->getAs<PointerType>())
7680 Ret = ToTypePtr->getPointeeType();
7681 else if (const ReferenceType *ToTypeRef =
7682 PossiblyAFunctionType->getAs<ReferenceType>())
7683 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007684 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007685 PossiblyAFunctionType->getAs<MemberPointerType>())
7686 Ret = MemTypePtr->getPointeeType();
7687 Ret =
7688 Context.getCanonicalType(Ret).getUnqualifiedType();
7689 return Ret;
7690}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007691
Douglas Gregorb491ed32011-02-19 21:32:49 +00007692// A helper class to help with address of function resolution
7693// - allows us to avoid passing around all those ugly parameters
7694class AddressOfFunctionResolver
7695{
7696 Sema& S;
7697 Expr* SourceExpr;
7698 const QualType& TargetType;
7699 QualType TargetFunctionType; // Extracted function type from target type
7700
7701 bool Complain;
7702 //DeclAccessPair& ResultFunctionAccessPair;
7703 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007704
Douglas Gregorb491ed32011-02-19 21:32:49 +00007705 bool TargetTypeIsNonStaticMemberFunction;
7706 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007707
Douglas Gregorb491ed32011-02-19 21:32:49 +00007708 OverloadExpr::FindResult OvlExprInfo;
7709 OverloadExpr *OvlExpr;
7710 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007711 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007712
Douglas Gregorb491ed32011-02-19 21:32:49 +00007713public:
7714 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7715 const QualType& TargetType, bool Complain)
7716 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7717 Complain(Complain), Context(S.getASTContext()),
7718 TargetTypeIsNonStaticMemberFunction(
7719 !!TargetType->getAs<MemberPointerType>()),
7720 FoundNonTemplateFunction(false),
7721 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7722 OvlExpr(OvlExprInfo.Expression)
7723 {
7724 ExtractUnqualifiedFunctionTypeFromTargetType();
7725
7726 if (!TargetFunctionType->isFunctionType()) {
7727 if (OvlExpr->hasExplicitTemplateArgs()) {
7728 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00007729 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00007730 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00007731
7732 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7733 if (!Method->isStatic()) {
7734 // If the target type is a non-function type and the function
7735 // found is a non-static member function, pretend as if that was
7736 // the target, it's the only possible type to end up with.
7737 TargetTypeIsNonStaticMemberFunction = true;
7738
7739 // And skip adding the function if its not in the proper form.
7740 // We'll diagnose this due to an empty set of functions.
7741 if (!OvlExprInfo.HasFormOfMemberPointer)
7742 return;
7743 }
7744 }
7745
Douglas Gregorb491ed32011-02-19 21:32:49 +00007746 Matches.push_back(std::make_pair(dap,Fn));
7747 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007748 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007749 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007750 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007751
7752 if (OvlExpr->hasExplicitTemplateArgs())
7753 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007754
Douglas Gregorb491ed32011-02-19 21:32:49 +00007755 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7756 // C++ [over.over]p4:
7757 // If more than one function is selected, [...]
7758 if (Matches.size() > 1) {
7759 if (FoundNonTemplateFunction)
7760 EliminateAllTemplateMatches();
7761 else
7762 EliminateAllExceptMostSpecializedTemplate();
7763 }
7764 }
7765 }
7766
7767private:
7768 bool isTargetTypeAFunction() const {
7769 return TargetFunctionType->isFunctionType();
7770 }
7771
7772 // [ToType] [Return]
7773
7774 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7775 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7776 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7777 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7778 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7779 }
7780
7781 // return true if any matching specializations were found
7782 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7783 const DeclAccessPair& CurAccessFunPair) {
7784 if (CXXMethodDecl *Method
7785 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7786 // Skip non-static function templates when converting to pointer, and
7787 // static when converting to member pointer.
7788 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7789 return false;
7790 }
7791 else if (TargetTypeIsNonStaticMemberFunction)
7792 return false;
7793
7794 // C++ [over.over]p2:
7795 // If the name is a function template, template argument deduction is
7796 // done (14.8.2.2), and if the argument deduction succeeds, the
7797 // resulting template argument list is used to generate a single
7798 // function template specialization, which is added to the set of
7799 // overloaded functions considered.
7800 FunctionDecl *Specialization = 0;
7801 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7802 if (Sema::TemplateDeductionResult Result
7803 = S.DeduceTemplateArguments(FunctionTemplate,
7804 &OvlExplicitTemplateArgs,
7805 TargetFunctionType, Specialization,
7806 Info)) {
7807 // FIXME: make a note of the failed deduction for diagnostics.
7808 (void)Result;
7809 return false;
7810 }
7811
7812 // Template argument deduction ensures that we have an exact match.
7813 // This function template specicalization works.
7814 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7815 assert(TargetFunctionType
7816 == Context.getCanonicalType(Specialization->getType()));
7817 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7818 return true;
7819 }
7820
7821 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7822 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007823 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007824 // Skip non-static functions when converting to pointer, and static
7825 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007826 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7827 return false;
7828 }
7829 else if (TargetTypeIsNonStaticMemberFunction)
7830 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007831
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007832 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007833 if (S.getLangOptions().CUDA)
7834 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
7835 if (S.CheckCUDATarget(Caller, FunDecl))
7836 return false;
7837
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007838 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007839 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7840 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00007841 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
7842 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007843 Matches.push_back(std::make_pair(CurAccessFunPair,
7844 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007845 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007846 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007847 }
Mike Stump11289f42009-09-09 15:08:12 +00007848 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007849
7850 return false;
7851 }
7852
7853 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7854 bool Ret = false;
7855
7856 // If the overload expression doesn't have the form of a pointer to
7857 // member, don't try to convert it to a pointer-to-member type.
7858 if (IsInvalidFormOfPointerToMemberFunction())
7859 return false;
7860
7861 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7862 E = OvlExpr->decls_end();
7863 I != E; ++I) {
7864 // Look through any using declarations to find the underlying function.
7865 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7866
7867 // C++ [over.over]p3:
7868 // Non-member functions and static member functions match
7869 // targets of type "pointer-to-function" or "reference-to-function."
7870 // Nonstatic member functions match targets of
7871 // type "pointer-to-member-function."
7872 // Note that according to DR 247, the containing class does not matter.
7873 if (FunctionTemplateDecl *FunctionTemplate
7874 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7875 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7876 Ret = true;
7877 }
7878 // If we have explicit template arguments supplied, skip non-templates.
7879 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7880 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7881 Ret = true;
7882 }
7883 assert(Ret || Matches.empty());
7884 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007885 }
7886
Douglas Gregorb491ed32011-02-19 21:32:49 +00007887 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00007888 // [...] and any given function template specialization F1 is
7889 // eliminated if the set contains a second function template
7890 // specialization whose function template is more specialized
7891 // than the function template of F1 according to the partial
7892 // ordering rules of 14.5.5.2.
7893
7894 // The algorithm specified above is quadratic. We instead use a
7895 // two-pass algorithm (similar to the one used to identify the
7896 // best viable function in an overload set) that identifies the
7897 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00007898
7899 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
7900 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
7901 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007902
John McCall58cc69d2010-01-27 01:50:18 +00007903 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007904 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
7905 TPOC_Other, 0, SourceExpr->getLocStart(),
7906 S.PDiag(),
7907 S.PDiag(diag::err_addr_ovl_ambiguous)
7908 << Matches[0].second->getDeclName(),
7909 S.PDiag(diag::note_ovl_candidate)
7910 << (unsigned) oc_function_template,
7911 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007912
Douglas Gregorb491ed32011-02-19 21:32:49 +00007913 if (Result != MatchesCopy.end()) {
7914 // Make it the first and only element
7915 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
7916 Matches[0].second = cast<FunctionDecl>(*Result);
7917 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00007918 }
7919 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007920
Douglas Gregorb491ed32011-02-19 21:32:49 +00007921 void EliminateAllTemplateMatches() {
7922 // [...] any function template specializations in the set are
7923 // eliminated if the set also contains a non-template function, [...]
7924 for (unsigned I = 0, N = Matches.size(); I != N; ) {
7925 if (Matches[I].second->getPrimaryTemplate() == 0)
7926 ++I;
7927 else {
7928 Matches[I] = Matches[--N];
7929 Matches.set_size(N);
7930 }
7931 }
7932 }
7933
7934public:
7935 void ComplainNoMatchesFound() const {
7936 assert(Matches.empty());
7937 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
7938 << OvlExpr->getName() << TargetFunctionType
7939 << OvlExpr->getSourceRange();
7940 S.NoteAllOverloadCandidates(OvlExpr);
7941 }
7942
7943 bool IsInvalidFormOfPointerToMemberFunction() const {
7944 return TargetTypeIsNonStaticMemberFunction &&
7945 !OvlExprInfo.HasFormOfMemberPointer;
7946 }
7947
7948 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
7949 // TODO: Should we condition this on whether any functions might
7950 // have matched, or is it more appropriate to do that in callers?
7951 // TODO: a fixit wouldn't hurt.
7952 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
7953 << TargetType << OvlExpr->getSourceRange();
7954 }
7955
7956 void ComplainOfInvalidConversion() const {
7957 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
7958 << OvlExpr->getName() << TargetType;
7959 }
7960
7961 void ComplainMultipleMatchesFound() const {
7962 assert(Matches.size() > 1);
7963 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
7964 << OvlExpr->getName()
7965 << OvlExpr->getSourceRange();
7966 S.NoteAllOverloadCandidates(OvlExpr);
7967 }
7968
7969 int getNumMatches() const { return Matches.size(); }
7970
7971 FunctionDecl* getMatchingFunctionDecl() const {
7972 if (Matches.size() != 1) return 0;
7973 return Matches[0].second;
7974 }
7975
7976 const DeclAccessPair* getMatchingFunctionAccessPair() const {
7977 if (Matches.size() != 1) return 0;
7978 return &Matches[0].first;
7979 }
7980};
7981
7982/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
7983/// an overloaded function (C++ [over.over]), where @p From is an
7984/// expression with overloaded function type and @p ToType is the type
7985/// we're trying to resolve to. For example:
7986///
7987/// @code
7988/// int f(double);
7989/// int f(int);
7990///
7991/// int (*pfd)(double) = f; // selects f(double)
7992/// @endcode
7993///
7994/// This routine returns the resulting FunctionDecl if it could be
7995/// resolved, and NULL otherwise. When @p Complain is true, this
7996/// routine will emit diagnostics if there is an error.
7997FunctionDecl *
7998Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
7999 bool Complain,
8000 DeclAccessPair &FoundResult) {
8001
8002 assert(AddressOfExpr->getType() == Context.OverloadTy);
8003
8004 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
8005 int NumMatches = Resolver.getNumMatches();
8006 FunctionDecl* Fn = 0;
8007 if ( NumMatches == 0 && Complain) {
8008 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8009 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8010 else
8011 Resolver.ComplainNoMatchesFound();
8012 }
8013 else if (NumMatches > 1 && Complain)
8014 Resolver.ComplainMultipleMatchesFound();
8015 else if (NumMatches == 1) {
8016 Fn = Resolver.getMatchingFunctionDecl();
8017 assert(Fn);
8018 FoundResult = *Resolver.getMatchingFunctionAccessPair();
8019 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00008020 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00008021 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00008022 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008023
8024 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008025}
8026
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008027/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008028/// resolve that overloaded function expression down to a single function.
8029///
8030/// This routine can only resolve template-ids that refer to a single function
8031/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008032/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008033/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00008034FunctionDecl *
8035Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8036 bool Complain,
8037 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008038 // C++ [over.over]p1:
8039 // [...] [Note: any redundant set of parentheses surrounding the
8040 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008041 // C++ [over.over]p1:
8042 // [...] The overloaded function name can be preceded by the &
8043 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008044
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008045 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00008046 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008047 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00008048
8049 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00008050 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008051
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008052 // Look through all of the overloaded functions, searching for one
8053 // whose type matches exactly.
8054 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008055 for (UnresolvedSetIterator I = ovl->decls_begin(),
8056 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008057 // C++0x [temp.arg.explicit]p3:
8058 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008059 // where deduction is not done, if a template argument list is
8060 // specified and it, along with any default template arguments,
8061 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008062 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00008063 FunctionTemplateDecl *FunctionTemplate
8064 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008065
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008066 // C++ [over.over]p2:
8067 // If the name is a function template, template argument deduction is
8068 // done (14.8.2.2), and if the argument deduction succeeds, the
8069 // resulting template argument list is used to generate a single
8070 // function template specialization, which is added to the set of
8071 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008072 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008073 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008074 if (TemplateDeductionResult Result
8075 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8076 Specialization, Info)) {
8077 // FIXME: make a note of the failed deduction for diagnostics.
8078 (void)Result;
8079 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008080 }
8081
John McCall0009fcc2011-04-26 20:42:42 +00008082 assert(Specialization && "no specialization and no error?");
8083
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008084 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008085 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008086 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00008087 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8088 << ovl->getName();
8089 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008090 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008091 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00008092 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008093
John McCall0009fcc2011-04-26 20:42:42 +00008094 Matched = Specialization;
8095 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008096 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008097
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008098 return Matched;
8099}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008100
Douglas Gregor1beec452011-03-12 01:48:56 +00008101
8102
8103
8104// Resolve and fix an overloaded expression that
8105// can be resolved because it identifies a single function
8106// template specialization
8107// Last three arguments should only be supplied if Complain = true
8108ExprResult Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
John McCall0009fcc2011-04-26 20:42:42 +00008109 Expr *SrcExpr, bool doFunctionPointerConverion, bool complain,
Douglas Gregor1beec452011-03-12 01:48:56 +00008110 const SourceRange& OpRangeForComplaining,
8111 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00008112 unsigned DiagIDForComplaining) {
8113 assert(SrcExpr->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00008114
John McCall0009fcc2011-04-26 20:42:42 +00008115 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr);
Douglas Gregor1beec452011-03-12 01:48:56 +00008116
John McCall0009fcc2011-04-26 20:42:42 +00008117 DeclAccessPair found;
8118 ExprResult SingleFunctionExpression;
8119 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8120 ovl.Expression, /*complain*/ false, &found)) {
8121 if (DiagnoseUseOfDecl(fn, SrcExpr->getSourceRange().getBegin()))
8122 return ExprError();
8123
8124 // It is only correct to resolve to an instance method if we're
8125 // resolving a form that's permitted to be a pointer to member.
8126 // Otherwise we'll end up making a bound member expression, which
8127 // is illegal in all the contexts we resolve like this.
8128 if (!ovl.HasFormOfMemberPointer &&
8129 isa<CXXMethodDecl>(fn) &&
8130 cast<CXXMethodDecl>(fn)->isInstance()) {
8131 if (complain) {
8132 Diag(ovl.Expression->getExprLoc(),
8133 diag::err_invalid_use_of_bound_member_func)
8134 << ovl.Expression->getSourceRange();
8135 // TODO: I believe we only end up here if there's a mix of
8136 // static and non-static candidates (otherwise the expression
8137 // would have 'bound member' type, not 'overload' type).
8138 // Ideally we would note which candidate was chosen and why
8139 // the static candidates were rejected.
8140 }
8141
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008142 return ExprError();
Douglas Gregor1beec452011-03-12 01:48:56 +00008143 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008144
John McCall0009fcc2011-04-26 20:42:42 +00008145 // Fix the expresion to refer to 'fn'.
8146 SingleFunctionExpression =
8147 Owned(FixOverloadedFunctionReference(SrcExpr, found, fn));
8148
8149 // If desired, do function-to-pointer decay.
8150 if (doFunctionPointerConverion)
8151 SingleFunctionExpression =
8152 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
8153 }
8154
8155 if (!SingleFunctionExpression.isUsable()) {
8156 if (complain) {
8157 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8158 << ovl.Expression->getName()
8159 << DestTypeForComplaining
8160 << OpRangeForComplaining
8161 << ovl.Expression->getQualifierLoc().getSourceRange();
8162 NoteAllOverloadCandidates(SrcExpr);
8163 }
8164 return ExprError();
8165 }
8166
8167 return SingleFunctionExpression;
Douglas Gregor1beec452011-03-12 01:48:56 +00008168}
8169
Douglas Gregorcabea402009-09-22 15:41:20 +00008170/// \brief Add a single candidate to the overload set.
8171static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00008172 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008173 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008174 Expr **Args, unsigned NumArgs,
8175 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008176 bool PartialOverloading,
8177 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00008178 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00008179 if (isa<UsingShadowDecl>(Callee))
8180 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8181
Douglas Gregorcabea402009-09-22 15:41:20 +00008182 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00008183 if (ExplicitTemplateArgs) {
8184 assert(!KnownValid && "Explicit template arguments?");
8185 return;
8186 }
John McCalla0296f72010-03-19 07:35:19 +00008187 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00008188 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008189 return;
John McCalld14a8642009-11-21 08:51:07 +00008190 }
8191
8192 if (FunctionTemplateDecl *FuncTemplate
8193 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00008194 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8195 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00008196 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00008197 return;
8198 }
8199
Richard Smith95ce4f62011-06-26 22:19:54 +00008200 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00008201}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008202
Douglas Gregorcabea402009-09-22 15:41:20 +00008203/// \brief Add the overload candidates named by callee and/or found by argument
8204/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00008205void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00008206 Expr **Args, unsigned NumArgs,
8207 OverloadCandidateSet &CandidateSet,
8208 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00008209
8210#ifndef NDEBUG
8211 // Verify that ArgumentDependentLookup is consistent with the rules
8212 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00008213 //
Douglas Gregorcabea402009-09-22 15:41:20 +00008214 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8215 // and let Y be the lookup set produced by argument dependent
8216 // lookup (defined as follows). If X contains
8217 //
8218 // -- a declaration of a class member, or
8219 //
8220 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00008221 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00008222 //
8223 // -- a declaration that is neither a function or a function
8224 // template
8225 //
8226 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00008227
John McCall57500772009-12-16 12:17:52 +00008228 if (ULE->requiresADL()) {
8229 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8230 E = ULE->decls_end(); I != E; ++I) {
8231 assert(!(*I)->getDeclContext()->isRecord());
8232 assert(isa<UsingShadowDecl>(*I) ||
8233 !(*I)->getDeclContext()->isFunctionOrMethod());
8234 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008235 }
8236 }
8237#endif
8238
John McCall57500772009-12-16 12:17:52 +00008239 // It would be nice to avoid this copy.
8240 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008241 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008242 if (ULE->hasExplicitTemplateArgs()) {
8243 ULE->copyTemplateArgumentsInto(TABuffer);
8244 ExplicitTemplateArgs = &TABuffer;
8245 }
8246
8247 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8248 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008249 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008250 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008251 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008252
John McCall57500772009-12-16 12:17:52 +00008253 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008254 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8255 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008256 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008257 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008258 PartialOverloading,
8259 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008260}
John McCalld681c392009-12-16 08:11:27 +00008261
Richard Smith998a5912011-06-05 22:42:48 +00008262/// Attempt to recover from an ill-formed use of a non-dependent name in a
8263/// template, where the non-dependent name was declared after the template
8264/// was defined. This is common in code written for a compilers which do not
8265/// correctly implement two-stage name lookup.
8266///
8267/// Returns true if a viable candidate was found and a diagnostic was issued.
8268static bool
8269DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8270 const CXXScopeSpec &SS, LookupResult &R,
8271 TemplateArgumentListInfo *ExplicitTemplateArgs,
8272 Expr **Args, unsigned NumArgs) {
8273 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8274 return false;
8275
8276 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8277 SemaRef.LookupQualifiedName(R, DC);
8278
8279 if (!R.empty()) {
8280 R.suppressDiagnostics();
8281
8282 if (isa<CXXRecordDecl>(DC)) {
8283 // Don't diagnose names we find in classes; we get much better
8284 // diagnostics for these from DiagnoseEmptyLookup.
8285 R.clear();
8286 return false;
8287 }
8288
8289 OverloadCandidateSet Candidates(FnLoc);
8290 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8291 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8292 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008293 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008294
8295 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008296 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008297 // No viable functions. Don't bother the user with notes for functions
8298 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008299 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008300 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008301 }
Richard Smith998a5912011-06-05 22:42:48 +00008302
8303 // Find the namespaces where ADL would have looked, and suggest
8304 // declaring the function there instead.
8305 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8306 Sema::AssociatedClassSet AssociatedClasses;
8307 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8308 AssociatedNamespaces,
8309 AssociatedClasses);
8310 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008311 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008312 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008313 for (Sema::AssociatedNamespaceSet::iterator
8314 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008315 end = AssociatedNamespaces.end(); it != end; ++it) {
8316 if (!Std->Encloses(*it))
8317 SuggestedNamespaces.insert(*it);
8318 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008319 } else {
8320 // Lacking the 'std::' namespace, use all of the associated namespaces.
8321 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008322 }
8323
8324 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8325 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008326 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008327 SemaRef.Diag(Best->Function->getLocation(),
8328 diag::note_not_found_by_two_phase_lookup)
8329 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008330 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008331 SemaRef.Diag(Best->Function->getLocation(),
8332 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008333 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008334 } else {
8335 // FIXME: It would be useful to list the associated namespaces here,
8336 // but the diagnostics infrastructure doesn't provide a way to produce
8337 // a localized representation of a list of items.
8338 SemaRef.Diag(Best->Function->getLocation(),
8339 diag::note_not_found_by_two_phase_lookup)
8340 << R.getLookupName() << 2;
8341 }
8342
8343 // Try to recover by calling this function.
8344 return true;
8345 }
8346
8347 R.clear();
8348 }
8349
8350 return false;
8351}
8352
8353/// Attempt to recover from ill-formed use of a non-dependent operator in a
8354/// template, where the non-dependent operator was declared after the template
8355/// was defined.
8356///
8357/// Returns true if a viable candidate was found and a diagnostic was issued.
8358static bool
8359DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8360 SourceLocation OpLoc,
8361 Expr **Args, unsigned NumArgs) {
8362 DeclarationName OpName =
8363 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8364 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8365 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8366 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8367}
8368
John McCalld681c392009-12-16 08:11:27 +00008369/// Attempts to recover from a call where no functions were found.
8370///
8371/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008372static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008373BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008374 UnresolvedLookupExpr *ULE,
8375 SourceLocation LParenLoc,
8376 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008377 SourceLocation RParenLoc,
8378 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008379
8380 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008381 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008382
John McCall57500772009-12-16 12:17:52 +00008383 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008384 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008385 if (ULE->hasExplicitTemplateArgs()) {
8386 ULE->copyTemplateArgumentsInto(TABuffer);
8387 ExplicitTemplateArgs = &TABuffer;
8388 }
8389
John McCalld681c392009-12-16 08:11:27 +00008390 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8391 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008392 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8393 ExplicitTemplateArgs, Args, NumArgs) &&
8394 (!EmptyLookup ||
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00008395 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00008396 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00008397 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008398
John McCall57500772009-12-16 12:17:52 +00008399 assert(!R.empty() && "lookup results empty despite recovery");
8400
8401 // Build an implicit member call if appropriate. Just drop the
8402 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008403 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008404 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008405 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8406 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008407 else if (ExplicitTemplateArgs)
8408 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8409 else
8410 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8411
8412 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008413 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008414
8415 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008416 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008417 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008418 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008419 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008420}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008421
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008422/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008423/// (which eventually refers to the declaration Func) and the call
8424/// arguments Args/NumArgs, attempt to resolve the function call down
8425/// to a specific function. If overload resolution succeeds, returns
8426/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008427/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008428/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008429ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008430Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008431 SourceLocation LParenLoc,
8432 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008433 SourceLocation RParenLoc,
8434 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008435#ifndef NDEBUG
8436 if (ULE->requiresADL()) {
8437 // To do ADL, we must have found an unqualified name.
8438 assert(!ULE->getQualifier() && "qualified name with ADL");
8439
8440 // We don't perform ADL for implicit declarations of builtins.
8441 // Verify that this was correctly set up.
8442 FunctionDecl *F;
8443 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8444 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8445 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00008446 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008447
John McCall57500772009-12-16 12:17:52 +00008448 // We don't perform ADL in C.
8449 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008450 } else
8451 assert(!ULE->isStdAssociatedNamespace() &&
8452 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008453#endif
8454
John McCallbc077cf2010-02-08 23:07:23 +00008455 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008456
John McCall57500772009-12-16 12:17:52 +00008457 // Add the functions denoted by the callee to the set of candidate
8458 // functions, including those from argument-dependent lookup.
8459 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008460
8461 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008462 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8463 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00008464 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008465 // In Microsoft mode, if we are inside a template class member function then
8466 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00008467 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008468 // classes.
8469 if (getLangOptions().MicrosoftExt && CurContext->isDependentContext() &&
8470 isa<CXXMethodDecl>(CurContext)) {
8471 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8472 Context.DependentTy, VK_RValue,
8473 RParenLoc);
8474 CE->setTypeDependent(true);
8475 return Owned(CE);
8476 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008477 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008478 RParenLoc, /*EmptyLookup=*/true);
Francois Pichetbcf64712011-09-07 00:14:57 +00008479 }
John McCalld681c392009-12-16 08:11:27 +00008480
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008481 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008482 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008483 case OR_Success: {
8484 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008485 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008486 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008487 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
8488 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008489 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008490 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8491 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008492 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008493
Richard Smith998a5912011-06-05 22:42:48 +00008494 case OR_No_Viable_Function: {
8495 // Try to recover by looking for viable functions which the user might
8496 // have meant to call.
8497 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8498 Args, NumArgs, RParenLoc,
8499 /*EmptyLookup=*/false);
8500 if (!Recovery.isInvalid())
8501 return Recovery;
8502
Chris Lattner45d9d602009-02-17 07:29:20 +00008503 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008504 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008505 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008506 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008507 break;
Richard Smith998a5912011-06-05 22:42:48 +00008508 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008509
8510 case OR_Ambiguous:
8511 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008512 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008513 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008514 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008515
8516 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008517 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008518 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8519 << Best->Function->isDeleted()
8520 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008521 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008522 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008523 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8524 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008525 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008526 }
8527
Douglas Gregorb412e172010-07-25 18:17:45 +00008528 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00008529 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008530}
8531
John McCall4c4c1df2010-01-26 03:27:55 +00008532static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00008533 return Functions.size() > 1 ||
8534 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8535}
8536
Douglas Gregor084d8552009-03-13 23:49:33 +00008537/// \brief Create a unary operation that may resolve to an overloaded
8538/// operator.
8539///
8540/// \param OpLoc The location of the operator itself (e.g., '*').
8541///
8542/// \param OpcIn The UnaryOperator::Opcode that describes this
8543/// operator.
8544///
8545/// \param Functions The set of non-member functions that will be
8546/// considered by overload resolution. The caller needs to build this
8547/// set based on the context using, e.g.,
8548/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8549/// set should not contain any member functions; those will be added
8550/// by CreateOverloadedUnaryOp().
8551///
8552/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00008553ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00008554Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8555 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00008556 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008557 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00008558
8559 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8560 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8561 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008562 // TODO: provide better source location info.
8563 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008564
John Wiegley01296292011-04-08 18:41:53 +00008565 if (Input->getObjectKind() == OK_ObjCProperty) {
8566 ExprResult Result = ConvertPropertyForRValue(Input);
8567 if (Result.isInvalid())
8568 return ExprError();
8569 Input = Result.take();
8570 }
John McCalle26a8722010-12-04 08:14:53 +00008571
Douglas Gregor084d8552009-03-13 23:49:33 +00008572 Expr *Args[2] = { Input, 0 };
8573 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00008574
Douglas Gregor084d8552009-03-13 23:49:33 +00008575 // For post-increment and post-decrement, add the implicit '0' as
8576 // the second argument, so that we know this is a post-increment or
8577 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00008578 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008579 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008580 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8581 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00008582 NumArgs = 2;
8583 }
8584
8585 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00008586 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00008587 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008588 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00008589 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008590 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00008591 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008592
John McCall58cc69d2010-01-27 01:50:18 +00008593 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00008594 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008595 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008596 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008597 /*ADL*/ true, IsOverloaded(Fns),
8598 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00008599 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008600 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00008601 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008602 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00008603 OpLoc));
8604 }
8605
8606 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008607 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008608
8609 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008610 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00008611
8612 // Add operator candidates that are member functions.
8613 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8614
John McCall4c4c1df2010-01-26 03:27:55 +00008615 // Add candidates from ADL.
8616 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00008617 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00008618 /*ExplicitTemplateArgs*/ 0,
8619 CandidateSet);
8620
Douglas Gregor084d8552009-03-13 23:49:33 +00008621 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008622 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00008623
8624 // Perform overload resolution.
8625 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008626 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008627 case OR_Success: {
8628 // We found a built-in operator or an overloaded operator.
8629 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00008630
Douglas Gregor084d8552009-03-13 23:49:33 +00008631 if (FnDecl) {
8632 // We matched an overloaded operator. Build a call to that
8633 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00008634
Chandler Carruth30141632011-02-25 19:41:05 +00008635 MarkDeclarationReferenced(OpLoc, FnDecl);
8636
Douglas Gregor084d8552009-03-13 23:49:33 +00008637 // Convert the arguments.
8638 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00008639 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008640
John Wiegley01296292011-04-08 18:41:53 +00008641 ExprResult InputRes =
8642 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8643 Best->FoundDecl, Method);
8644 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008645 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008646 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008647 } else {
8648 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008649 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00008650 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008651 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00008652 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008653 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00008654 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00008655 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008656 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008657 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008658 }
8659
John McCall4fa0d5f2010-05-06 18:15:07 +00008660 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8661
John McCall7decc9e2010-11-18 06:31:45 +00008662 // Determine the result type.
8663 QualType ResultTy = FnDecl->getResultType();
8664 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8665 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00008666
Douglas Gregor084d8552009-03-13 23:49:33 +00008667 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008668 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl);
8669 if (FnExpr.isInvalid())
8670 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00008671
Eli Friedman030eee42009-11-18 03:58:17 +00008672 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00008673 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008674 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008675 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00008676
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008677 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00008678 FnDecl))
8679 return ExprError();
8680
John McCallb268a282010-08-23 23:25:46 +00008681 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00008682 } else {
8683 // We matched a built-in operator. Convert the arguments, then
8684 // break out so that we will build the appropriate built-in
8685 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008686 ExprResult InputRes =
8687 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8688 Best->Conversions[0], AA_Passing);
8689 if (InputRes.isInvalid())
8690 return ExprError();
8691 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008692 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00008693 }
John Wiegley01296292011-04-08 18:41:53 +00008694 }
8695
8696 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00008697 // This is an erroneous use of an operator which can be overloaded by
8698 // a non-member function. Check for non-member operators which were
8699 // defined too late to be candidates.
8700 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8701 // FIXME: Recover by calling the found function.
8702 return ExprError();
8703
John Wiegley01296292011-04-08 18:41:53 +00008704 // No viable function; fall through to handling this as a
8705 // built-in operator, which will produce an error message for us.
8706 break;
8707
8708 case OR_Ambiguous:
8709 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8710 << UnaryOperator::getOpcodeStr(Opc)
8711 << Input->getType()
8712 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008713 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00008714 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8715 return ExprError();
8716
8717 case OR_Deleted:
8718 Diag(OpLoc, diag::err_ovl_deleted_oper)
8719 << Best->Function->isDeleted()
8720 << UnaryOperator::getOpcodeStr(Opc)
8721 << getDeletedOrUnavailableSuffix(Best->Function)
8722 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008723 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
8724 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00008725 return ExprError();
8726 }
Douglas Gregor084d8552009-03-13 23:49:33 +00008727
8728 // Either we found no viable overloaded operator or we matched a
8729 // built-in operator. In either case, fall through to trying to
8730 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00008731 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008732}
8733
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008734/// \brief Create a binary operation that may resolve to an overloaded
8735/// operator.
8736///
8737/// \param OpLoc The location of the operator itself (e.g., '+').
8738///
8739/// \param OpcIn The BinaryOperator::Opcode that describes this
8740/// operator.
8741///
8742/// \param Functions The set of non-member functions that will be
8743/// considered by overload resolution. The caller needs to build this
8744/// set based on the context using, e.g.,
8745/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8746/// set should not contain any member functions; those will be added
8747/// by CreateOverloadedBinOp().
8748///
8749/// \param LHS Left-hand argument.
8750/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00008751ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008752Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008753 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00008754 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008755 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008756 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00008757 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008758
8759 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8760 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8761 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8762
8763 // If either side is type-dependent, create an appropriate dependent
8764 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00008765 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00008766 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008767 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00008768 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00008769 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00008770 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00008771 Context.DependentTy,
8772 VK_RValue, OK_Ordinary,
8773 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008774
Douglas Gregor5287f092009-11-05 00:51:44 +00008775 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8776 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008777 VK_LValue,
8778 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00008779 Context.DependentTy,
8780 Context.DependentTy,
8781 OpLoc));
8782 }
John McCall4c4c1df2010-01-26 03:27:55 +00008783
8784 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00008785 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008786 // TODO: provide better source location info in DNLoc component.
8787 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00008788 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00008789 = UnresolvedLookupExpr::Create(Context, NamingClass,
8790 NestedNameSpecifierLoc(), OpNameInfo,
8791 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008792 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008793 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00008794 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008795 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008796 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008797 OpLoc));
8798 }
8799
John McCalle26a8722010-12-04 08:14:53 +00008800 // Always do property rvalue conversions on the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008801 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8802 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8803 if (Result.isInvalid())
8804 return ExprError();
8805 Args[1] = Result.take();
8806 }
John McCalle26a8722010-12-04 08:14:53 +00008807
8808 // The LHS is more complicated.
8809 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8810
8811 // There's a tension for assignment operators between primitive
8812 // property assignment and the overloaded operators.
8813 if (BinaryOperator::isAssignmentOp(Opc)) {
8814 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8815
8816 // Is the property "logically" settable?
8817 bool Settable = (PRE->isExplicitProperty() ||
8818 PRE->getImplicitPropertySetter());
8819
8820 // To avoid gratuitously inventing semantics, use the primitive
8821 // unless it isn't. Thoughts in case we ever really care:
8822 // - If the property isn't logically settable, we have to
8823 // load and hope.
8824 // - If the property is settable and this is simple assignment,
8825 // we really should use the primitive.
8826 // - If the property is settable, then we could try overloading
8827 // on a generic lvalue of the appropriate type; if it works
8828 // out to a builtin candidate, we would do that same operation
8829 // on the property, and otherwise just error.
8830 if (Settable)
8831 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8832 }
8833
John Wiegley01296292011-04-08 18:41:53 +00008834 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8835 if (Result.isInvalid())
8836 return ExprError();
8837 Args[0] = Result.take();
John McCalle26a8722010-12-04 08:14:53 +00008838 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008839
Sebastian Redl6a96bf72009-11-18 23:10:33 +00008840 // If this is the assignment operator, we only perform overload resolution
8841 // if the left-hand side is a class or enumeration type. This is actually
8842 // a hack. The standard requires that we do overload resolution between the
8843 // various built-in candidates, but as DR507 points out, this can lead to
8844 // problems. So we do it this way, which pretty much follows what GCC does.
8845 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00008846 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00008847 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008848
John McCalle26a8722010-12-04 08:14:53 +00008849 // If this is the .* operator, which is not overloadable, just
8850 // create a built-in binary operator.
8851 if (Opc == BO_PtrMemD)
8852 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8853
Douglas Gregor084d8552009-03-13 23:49:33 +00008854 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008855 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008856
8857 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008858 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008859
8860 // Add operator candidates that are member functions.
8861 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8862
John McCall4c4c1df2010-01-26 03:27:55 +00008863 // Add candidates from ADL.
8864 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8865 Args, 2,
8866 /*ExplicitTemplateArgs*/ 0,
8867 CandidateSet);
8868
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008869 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008870 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008871
8872 // Perform overload resolution.
8873 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008874 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00008875 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008876 // We found a built-in operator or an overloaded operator.
8877 FunctionDecl *FnDecl = Best->Function;
8878
8879 if (FnDecl) {
8880 // We matched an overloaded operator. Build a call to that
8881 // operator.
8882
Chandler Carruth30141632011-02-25 19:41:05 +00008883 MarkDeclarationReferenced(OpLoc, FnDecl);
8884
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008885 // Convert the arguments.
8886 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00008887 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00008888 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008889
Chandler Carruth8e543b32010-12-12 08:17:55 +00008890 ExprResult Arg1 =
8891 PerformCopyInitialization(
8892 InitializedEntity::InitializeParameter(Context,
8893 FnDecl->getParamDecl(0)),
8894 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008895 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008896 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008897
John Wiegley01296292011-04-08 18:41:53 +00008898 ExprResult Arg0 =
8899 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
8900 Best->FoundDecl, Method);
8901 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008902 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008903 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008904 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008905 } else {
8906 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00008907 ExprResult Arg0 = PerformCopyInitialization(
8908 InitializedEntity::InitializeParameter(Context,
8909 FnDecl->getParamDecl(0)),
8910 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008911 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008912 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008913
Chandler Carruth8e543b32010-12-12 08:17:55 +00008914 ExprResult Arg1 =
8915 PerformCopyInitialization(
8916 InitializedEntity::InitializeParameter(Context,
8917 FnDecl->getParamDecl(1)),
8918 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00008919 if (Arg1.isInvalid())
8920 return ExprError();
8921 Args[0] = LHS = Arg0.takeAs<Expr>();
8922 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008923 }
8924
John McCall4fa0d5f2010-05-06 18:15:07 +00008925 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8926
John McCall7decc9e2010-11-18 06:31:45 +00008927 // Determine the result type.
8928 QualType ResultTy = FnDecl->getResultType();
8929 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8930 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008931
8932 // Build the actual expression node.
John Wiegley01296292011-04-08 18:41:53 +00008933 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
8934 if (FnExpr.isInvalid())
8935 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008936
John McCallb268a282010-08-23 23:25:46 +00008937 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008938 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008939 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008940
8941 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008942 FnDecl))
8943 return ExprError();
8944
John McCallb268a282010-08-23 23:25:46 +00008945 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008946 } else {
8947 // We matched a built-in operator. Convert the arguments, then
8948 // break out so that we will build the appropriate built-in
8949 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008950 ExprResult ArgsRes0 =
8951 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
8952 Best->Conversions[0], AA_Passing);
8953 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008954 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008955 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008956
John Wiegley01296292011-04-08 18:41:53 +00008957 ExprResult ArgsRes1 =
8958 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
8959 Best->Conversions[1], AA_Passing);
8960 if (ArgsRes1.isInvalid())
8961 return ExprError();
8962 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008963 break;
8964 }
8965 }
8966
Douglas Gregor66950a32009-09-30 21:46:01 +00008967 case OR_No_Viable_Function: {
8968 // C++ [over.match.oper]p9:
8969 // If the operator is the operator , [...] and there are no
8970 // viable functions, then the operator is assumed to be the
8971 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00008972 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00008973 break;
8974
Chandler Carruth8e543b32010-12-12 08:17:55 +00008975 // For class as left operand for assignment or compound assigment
8976 // operator do not fall through to handling in built-in, but report that
8977 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00008978 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008979 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00008980 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00008981 Diag(OpLoc, diag::err_ovl_no_viable_oper)
8982 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00008983 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00008984 } else {
Richard Smith998a5912011-06-05 22:42:48 +00008985 // This is an erroneous use of an operator which can be overloaded by
8986 // a non-member function. Check for non-member operators which were
8987 // defined too late to be candidates.
8988 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
8989 // FIXME: Recover by calling the found function.
8990 return ExprError();
8991
Douglas Gregor66950a32009-09-30 21:46:01 +00008992 // No viable function; try to create a built-in operation, which will
8993 // produce an error. Then, show the non-viable candidates.
8994 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00008995 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008996 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00008997 "C++ binary operator overloading is missing candidates!");
8998 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00008999 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9000 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00009001 return move(Result);
9002 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009003
9004 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009005 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009006 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00009007 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00009008 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009009 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9010 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009011 return ExprError();
9012
9013 case OR_Deleted:
9014 Diag(OpLoc, diag::err_ovl_deleted_oper)
9015 << Best->Function->isDeleted()
9016 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009017 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00009018 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009019 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9020 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009021 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00009022 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009023
Douglas Gregor66950a32009-09-30 21:46:01 +00009024 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00009025 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009026}
9027
John McCalldadc5752010-08-24 06:29:42 +00009028ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00009029Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9030 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00009031 Expr *Base, Expr *Idx) {
9032 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00009033 DeclarationName OpName =
9034 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9035
9036 // If either side is type-dependent, create an appropriate dependent
9037 // expression.
9038 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9039
John McCall58cc69d2010-01-27 01:50:18 +00009040 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009041 // CHECKME: no 'operator' keyword?
9042 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9043 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00009044 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009045 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009046 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009047 /*ADL*/ true, /*Overloaded*/ false,
9048 UnresolvedSetIterator(),
9049 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00009050 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00009051
Sebastian Redladba46e2009-10-29 20:17:01 +00009052 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9053 Args, 2,
9054 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009055 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00009056 RLoc));
9057 }
9058
John Wiegley01296292011-04-08 18:41:53 +00009059 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
9060 ExprResult Result = ConvertPropertyForRValue(Args[0]);
9061 if (Result.isInvalid())
9062 return ExprError();
9063 Args[0] = Result.take();
9064 }
9065 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
9066 ExprResult Result = ConvertPropertyForRValue(Args[1]);
9067 if (Result.isInvalid())
9068 return ExprError();
9069 Args[1] = Result.take();
9070 }
John McCalle26a8722010-12-04 08:14:53 +00009071
Sebastian Redladba46e2009-10-29 20:17:01 +00009072 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009073 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009074
9075 // Subscript can only be overloaded as a member function.
9076
9077 // Add operator candidates that are member functions.
9078 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9079
9080 // Add builtin operator candidates.
9081 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9082
9083 // Perform overload resolution.
9084 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009085 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00009086 case OR_Success: {
9087 // We found a built-in operator or an overloaded operator.
9088 FunctionDecl *FnDecl = Best->Function;
9089
9090 if (FnDecl) {
9091 // We matched an overloaded operator. Build a call to that
9092 // operator.
9093
Chandler Carruth30141632011-02-25 19:41:05 +00009094 MarkDeclarationReferenced(LLoc, FnDecl);
9095
John McCalla0296f72010-03-19 07:35:19 +00009096 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009097 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00009098
Sebastian Redladba46e2009-10-29 20:17:01 +00009099 // Convert the arguments.
9100 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00009101 ExprResult Arg0 =
9102 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9103 Best->FoundDecl, Method);
9104 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009105 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009106 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009107
Anders Carlssona68e51e2010-01-29 18:37:50 +00009108 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009109 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00009110 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009111 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00009112 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009113 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00009114 Owned(Args[1]));
9115 if (InputInit.isInvalid())
9116 return ExprError();
9117
9118 Args[1] = InputInit.takeAs<Expr>();
9119
Sebastian Redladba46e2009-10-29 20:17:01 +00009120 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00009121 QualType ResultTy = FnDecl->getResultType();
9122 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9123 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00009124
9125 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00009126 DeclarationNameLoc LocInfo;
9127 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9128 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
9129 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00009130 if (FnExpr.isInvalid())
9131 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009132
John McCallb268a282010-08-23 23:25:46 +00009133 CXXOperatorCallExpr *TheCall =
9134 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00009135 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00009136 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009137
John McCallb268a282010-08-23 23:25:46 +00009138 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00009139 FnDecl))
9140 return ExprError();
9141
John McCallb268a282010-08-23 23:25:46 +00009142 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00009143 } else {
9144 // We matched a built-in operator. Convert the arguments, then
9145 // break out so that we will build the appropriate built-in
9146 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009147 ExprResult ArgsRes0 =
9148 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9149 Best->Conversions[0], AA_Passing);
9150 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009151 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009152 Args[0] = ArgsRes0.take();
9153
9154 ExprResult ArgsRes1 =
9155 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9156 Best->Conversions[1], AA_Passing);
9157 if (ArgsRes1.isInvalid())
9158 return ExprError();
9159 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009160
9161 break;
9162 }
9163 }
9164
9165 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00009166 if (CandidateSet.empty())
9167 Diag(LLoc, diag::err_ovl_no_oper)
9168 << Args[0]->getType() << /*subscript*/ 0
9169 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9170 else
9171 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9172 << Args[0]->getType()
9173 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009174 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9175 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00009176 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009177 }
9178
9179 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009180 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009181 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00009182 << Args[0]->getType() << Args[1]->getType()
9183 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009184 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9185 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009186 return ExprError();
9187
9188 case OR_Deleted:
9189 Diag(LLoc, diag::err_ovl_deleted_oper)
9190 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009191 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00009192 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009193 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9194 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009195 return ExprError();
9196 }
9197
9198 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00009199 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009200}
9201
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009202/// BuildCallToMemberFunction - Build a call to a member
9203/// function. MemExpr is the expression that refers to the member
9204/// function (and includes the object parameter), Args/NumArgs are the
9205/// arguments to the function call (not including the object
9206/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00009207/// expression refers to a non-static member function or an overloaded
9208/// member function.
John McCalldadc5752010-08-24 06:29:42 +00009209ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00009210Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9211 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009212 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00009213 assert(MemExprE->getType() == Context.BoundMemberTy ||
9214 MemExprE->getType() == Context.OverloadTy);
9215
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009216 // Dig out the member expression. This holds both the object
9217 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00009218 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009219
John McCall0009fcc2011-04-26 20:42:42 +00009220 // Determine whether this is a call to a pointer-to-member function.
9221 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9222 assert(op->getType() == Context.BoundMemberTy);
9223 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9224
9225 QualType fnType =
9226 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9227
9228 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9229 QualType resultType = proto->getCallResultType(Context);
9230 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9231
9232 // Check that the object type isn't more qualified than the
9233 // member function we're calling.
9234 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9235
9236 QualType objectType = op->getLHS()->getType();
9237 if (op->getOpcode() == BO_PtrMemI)
9238 objectType = objectType->castAs<PointerType>()->getPointeeType();
9239 Qualifiers objectQuals = objectType.getQualifiers();
9240
9241 Qualifiers difference = objectQuals - funcQuals;
9242 difference.removeObjCGCAttr();
9243 difference.removeAddressSpace();
9244 if (difference) {
9245 std::string qualsString = difference.getAsString();
9246 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9247 << fnType.getUnqualifiedType()
9248 << qualsString
9249 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9250 }
9251
9252 CXXMemberCallExpr *call
9253 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9254 resultType, valueKind, RParenLoc);
9255
9256 if (CheckCallReturnType(proto->getResultType(),
9257 op->getRHS()->getSourceRange().getBegin(),
9258 call, 0))
9259 return ExprError();
9260
9261 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9262 return ExprError();
9263
9264 return MaybeBindToTemporary(call);
9265 }
9266
John McCall10eae182009-11-30 22:42:35 +00009267 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009268 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009269 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009270 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009271 if (isa<MemberExpr>(NakedMemExpr)) {
9272 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009273 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009274 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009275 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00009276 } else {
9277 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009278 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009279
John McCall6e9f8f62009-12-03 04:06:58 +00009280 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009281 Expr::Classification ObjectClassification
9282 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9283 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009284
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009285 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009286 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009287
John McCall2d74de92009-12-01 22:10:20 +00009288 // FIXME: avoid copy.
9289 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9290 if (UnresExpr->hasExplicitTemplateArgs()) {
9291 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9292 TemplateArgs = &TemplateArgsBuffer;
9293 }
9294
John McCall10eae182009-11-30 22:42:35 +00009295 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9296 E = UnresExpr->decls_end(); I != E; ++I) {
9297
John McCall6e9f8f62009-12-03 04:06:58 +00009298 NamedDecl *Func = *I;
9299 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9300 if (isa<UsingShadowDecl>(Func))
9301 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9302
Douglas Gregor02824322011-01-26 19:30:28 +00009303
Francois Pichet64225792011-01-18 05:04:39 +00009304 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +00009305 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +00009306 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9307 CandidateSet);
9308 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009309 // If explicit template arguments were provided, we can't call a
9310 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009311 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009312 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009313
John McCalla0296f72010-03-19 07:35:19 +00009314 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009315 ObjectClassification,
9316 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009317 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009318 } else {
John McCall10eae182009-11-30 22:42:35 +00009319 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009320 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009321 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009322 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009323 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009324 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009325 }
Mike Stump11289f42009-09-09 15:08:12 +00009326
John McCall10eae182009-11-30 22:42:35 +00009327 DeclarationName DeclName = UnresExpr->getMemberName();
9328
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009329 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009330 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009331 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009332 case OR_Success:
9333 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009334 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009335 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009336 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009337 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009338 break;
9339
9340 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009341 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009342 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009343 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009344 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009345 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009346 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009347
9348 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009349 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009350 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009351 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009352 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009353 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009354
9355 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009356 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009357 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009358 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009359 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009360 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009361 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009362 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009363 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009364 }
9365
John McCall16df1e52010-03-30 21:47:33 +00009366 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009367
John McCall2d74de92009-12-01 22:10:20 +00009368 // If overload resolution picked a static member, build a
9369 // non-member call based on that function.
9370 if (Method->isStatic()) {
9371 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9372 Args, NumArgs, RParenLoc);
9373 }
9374
John McCall10eae182009-11-30 22:42:35 +00009375 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009376 }
9377
John McCall7decc9e2010-11-18 06:31:45 +00009378 QualType ResultType = Method->getResultType();
9379 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9380 ResultType = ResultType.getNonLValueExprType(Context);
9381
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009382 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009383 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009384 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009385 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009386
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009387 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009388 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009389 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009390 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009391
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009392 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009393 // We only need to do this if there was actually an overload; otherwise
9394 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009395 if (!Method->isStatic()) {
9396 ExprResult ObjectArg =
9397 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9398 FoundDecl, Method);
9399 if (ObjectArg.isInvalid())
9400 return ExprError();
9401 MemExpr->setBase(ObjectArg.take());
9402 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009403
9404 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009405 const FunctionProtoType *Proto =
9406 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009407 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009408 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009409 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009410
John McCallb268a282010-08-23 23:25:46 +00009411 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009412 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009413
Anders Carlsson47061ee2011-05-06 14:25:31 +00009414 if ((isa<CXXConstructorDecl>(CurContext) ||
9415 isa<CXXDestructorDecl>(CurContext)) &&
9416 TheCall->getMethodDecl()->isPure()) {
9417 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9418
Chandler Carruth59259262011-06-27 08:31:58 +00009419 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009420 Diag(MemExpr->getLocStart(),
9421 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9422 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9423 << MD->getParent()->getDeclName();
9424
9425 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009426 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009427 }
John McCallb268a282010-08-23 23:25:46 +00009428 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009429}
9430
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009431/// BuildCallToObjectOfClassType - Build a call to an object of class
9432/// type (C++ [over.call.object]), which can end up invoking an
9433/// overloaded function call operator (@c operator()) or performing a
9434/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009435ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009436Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009437 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009438 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009439 SourceLocation RParenLoc) {
John Wiegley01296292011-04-08 18:41:53 +00009440 ExprResult Object = Owned(Obj);
9441 if (Object.get()->getObjectKind() == OK_ObjCProperty) {
9442 Object = ConvertPropertyForRValue(Object.take());
9443 if (Object.isInvalid())
9444 return ExprError();
9445 }
John McCalle26a8722010-12-04 08:14:53 +00009446
John Wiegley01296292011-04-08 18:41:53 +00009447 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9448 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009449
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009450 // C++ [over.call.object]p1:
9451 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009452 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009453 // candidate functions includes at least the function call
9454 // operators of T. The function call operators of T are obtained by
9455 // ordinary lookup of the name operator() in the context of
9456 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009457 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009458 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009459
John Wiegley01296292011-04-08 18:41:53 +00009460 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009461 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009462 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009463 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009464
John McCall27b18f82009-11-17 02:14:36 +00009465 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9466 LookupQualifiedName(R, Record->getDecl());
9467 R.suppressDiagnostics();
9468
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009469 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009470 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009471 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9472 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009473 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009474 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009475
Douglas Gregorab7897a2008-11-19 22:57:39 +00009476 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009477 // In addition, for each (non-explicit in C++0x) conversion function
9478 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +00009479 //
9480 // operator conversion-type-id () cv-qualifier;
9481 //
9482 // where cv-qualifier is the same cv-qualification as, or a
9483 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009484 // denotes the type "pointer to function of (P1,...,Pn) returning
9485 // R", or the type "reference to pointer to function of
9486 // (P1,...,Pn) returning R", or the type "reference to function
9487 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009488 // is also considered as a candidate function. Similarly,
9489 // surrogate call functions are added to the set of candidate
9490 // functions for each conversion function declared in an
9491 // accessible base class provided the function is not hidden
9492 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009493 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009494 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009495 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009496 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009497 NamedDecl *D = *I;
9498 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9499 if (isa<UsingShadowDecl>(D))
9500 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009501
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009502 // Skip over templated conversion functions; they aren't
9503 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009504 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009505 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009506
John McCall6e9f8f62009-12-03 04:06:58 +00009507 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009508 if (!Conv->isExplicit()) {
9509 // Strip the reference type (if any) and then the pointer type (if
9510 // any) to get down to what might be a function type.
9511 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9512 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9513 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +00009514
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009515 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9516 {
9517 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9518 Object.get(), Args, NumArgs, CandidateSet);
9519 }
9520 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00009521 }
Mike Stump11289f42009-09-09 15:08:12 +00009522
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009523 // Perform overload resolution.
9524 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009525 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009526 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009527 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009528 // Overload resolution succeeded; we'll build the appropriate call
9529 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009530 break;
9531
9532 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009533 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009534 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9535 << Object.get()->getType() << /*call*/ 1
9536 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009537 else
John Wiegley01296292011-04-08 18:41:53 +00009538 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009539 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009540 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009541 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009542 break;
9543
9544 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009545 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009546 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009547 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009548 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009549 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009550
9551 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00009552 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00009553 diag::err_ovl_deleted_object_call)
9554 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +00009555 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009556 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +00009557 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009558 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009559 break;
Mike Stump11289f42009-09-09 15:08:12 +00009560 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009561
Douglas Gregorb412e172010-07-25 18:17:45 +00009562 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009563 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009564
Douglas Gregorab7897a2008-11-19 22:57:39 +00009565 if (Best->Function == 0) {
9566 // Since there is no function declaration, this is one of the
9567 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00009568 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00009569 = cast<CXXConversionDecl>(
9570 Best->Conversions[0].UserDefined.ConversionFunction);
9571
John Wiegley01296292011-04-08 18:41:53 +00009572 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009573 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009574
Douglas Gregorab7897a2008-11-19 22:57:39 +00009575 // We selected one of the surrogate functions that converts the
9576 // object parameter to a function pointer. Perform the conversion
9577 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009578
Fariborz Jahanian774cf792009-09-28 18:35:46 +00009579 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00009580 // and then call it.
John Wiegley01296292011-04-08 18:41:53 +00009581 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl, Conv);
Douglas Gregor668443e2011-01-20 00:18:04 +00009582 if (Call.isInvalid())
9583 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009584
Douglas Gregor668443e2011-01-20 00:18:04 +00009585 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00009586 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00009587 }
9588
Chandler Carruth30141632011-02-25 19:41:05 +00009589 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009590 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009591 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009592
Douglas Gregorab7897a2008-11-19 22:57:39 +00009593 // We found an overloaded operator(). Build a CXXOperatorCallExpr
9594 // that calls this method, using Object for the implicit object
9595 // parameter and passing along the remaining arguments.
9596 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00009597 const FunctionProtoType *Proto =
9598 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009599
9600 unsigned NumArgsInProto = Proto->getNumArgs();
9601 unsigned NumArgsToCheck = NumArgs;
9602
9603 // Build the full argument list for the method call (the
9604 // implicit object parameter is placed at the beginning of the
9605 // list).
9606 Expr **MethodArgs;
9607 if (NumArgs < NumArgsInProto) {
9608 NumArgsToCheck = NumArgsInProto;
9609 MethodArgs = new Expr*[NumArgsInProto + 1];
9610 } else {
9611 MethodArgs = new Expr*[NumArgs + 1];
9612 }
John Wiegley01296292011-04-08 18:41:53 +00009613 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009614 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9615 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00009616
John Wiegley01296292011-04-08 18:41:53 +00009617 ExprResult NewFn = CreateFunctionRefExpr(*this, Method);
9618 if (NewFn.isInvalid())
9619 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009620
9621 // Once we've built TheCall, all of the expressions are properly
9622 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00009623 QualType ResultTy = Method->getResultType();
9624 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9625 ResultTy = ResultTy.getNonLValueExprType(Context);
9626
John McCallb268a282010-08-23 23:25:46 +00009627 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009628 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +00009629 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00009630 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009631 delete [] MethodArgs;
9632
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009633 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00009634 Method))
9635 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009636
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009637 // We may have default arguments. If so, we need to allocate more
9638 // slots in the call for them.
9639 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00009640 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009641 else if (NumArgs > NumArgsInProto)
9642 NumArgsToCheck = NumArgsInProto;
9643
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009644 bool IsError = false;
9645
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009646 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +00009647 ExprResult ObjRes =
9648 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9649 Best->FoundDecl, Method);
9650 if (ObjRes.isInvalid())
9651 IsError = true;
9652 else
9653 Object = move(ObjRes);
9654 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009655
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009656 // Check the argument types.
9657 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009658 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009659 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009660 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00009661
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009662 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009663
John McCalldadc5752010-08-24 06:29:42 +00009664 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009665 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009666 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009667 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00009668 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009669
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009670 IsError |= InputInit.isInvalid();
9671 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009672 } else {
John McCalldadc5752010-08-24 06:29:42 +00009673 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009674 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9675 if (DefArg.isInvalid()) {
9676 IsError = true;
9677 break;
9678 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009679
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009680 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009681 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009682
9683 TheCall->setArg(i + 1, Arg);
9684 }
9685
9686 // If this is a variadic call, handle args passed through "...".
9687 if (Proto->isVariadic()) {
9688 // Promote the arguments (C99 6.5.2.2p7).
9689 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +00009690 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9691 IsError |= Arg.isInvalid();
9692 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009693 }
9694 }
9695
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009696 if (IsError) return true;
9697
John McCallb268a282010-08-23 23:25:46 +00009698 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00009699 return true;
9700
John McCalle172be52010-08-24 06:09:16 +00009701 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009702}
9703
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009704/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00009705/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009706/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00009707ExprResult
John McCallb268a282010-08-23 23:25:46 +00009708Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009709 assert(Base->getType()->isRecordType() &&
9710 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00009711
John Wiegley01296292011-04-08 18:41:53 +00009712 if (Base->getObjectKind() == OK_ObjCProperty) {
9713 ExprResult Result = ConvertPropertyForRValue(Base);
9714 if (Result.isInvalid())
9715 return ExprError();
9716 Base = Result.take();
9717 }
John McCalle26a8722010-12-04 08:14:53 +00009718
John McCallbc077cf2010-02-08 23:07:23 +00009719 SourceLocation Loc = Base->getExprLoc();
9720
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009721 // C++ [over.ref]p1:
9722 //
9723 // [...] An expression x->m is interpreted as (x.operator->())->m
9724 // for a class object x of type T if T::operator->() exists and if
9725 // the operator is selected as the best match function by the
9726 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00009727 DeclarationName OpName =
9728 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00009729 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009730 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00009731
John McCallbc077cf2010-02-08 23:07:23 +00009732 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00009733 PDiag(diag::err_typecheck_incomplete_tag)
9734 << Base->getSourceRange()))
9735 return ExprError();
9736
John McCall27b18f82009-11-17 02:14:36 +00009737 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9738 LookupQualifiedName(R, BaseRecord->getDecl());
9739 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00009740
9741 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00009742 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00009743 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9744 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00009745 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009746
9747 // Perform overload resolution.
9748 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009749 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009750 case OR_Success:
9751 // Overload resolution succeeded; we'll build the call below.
9752 break;
9753
9754 case OR_No_Viable_Function:
9755 if (CandidateSet.empty())
9756 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00009757 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009758 else
9759 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00009760 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009761 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009762 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009763
9764 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009765 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9766 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009767 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009768 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009769
9770 case OR_Deleted:
9771 Diag(OpLoc, diag::err_ovl_deleted_oper)
9772 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009773 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009774 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009775 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009776 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009777 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009778 }
9779
Chandler Carruth30141632011-02-25 19:41:05 +00009780 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00009781 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009782 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00009783
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009784 // Convert the object parameter.
9785 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009786 ExprResult BaseResult =
9787 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9788 Best->FoundDecl, Method);
9789 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +00009790 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009791 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +00009792
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009793 // Build the operator call.
John Wiegley01296292011-04-08 18:41:53 +00009794 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method);
9795 if (FnExpr.isInvalid())
9796 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009797
John McCall7decc9e2010-11-18 06:31:45 +00009798 QualType ResultTy = Method->getResultType();
9799 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9800 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00009801 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009802 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009803 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009804
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009805 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009806 Method))
9807 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +00009808
9809 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009810}
9811
Douglas Gregorcd695e52008-11-10 20:40:00 +00009812/// FixOverloadedFunctionReference - E is an expression that refers to
9813/// a C++ overloaded function (possibly with some parentheses and
9814/// perhaps a '&' around it). We have resolved the overloaded function
9815/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00009816/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00009817Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00009818 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00009819 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009820 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9821 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009822 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009823 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009824
Douglas Gregor51c538b2009-11-20 19:42:02 +00009825 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009826 }
9827
Douglas Gregor51c538b2009-11-20 19:42:02 +00009828 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009829 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9830 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009831 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00009832 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00009833 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00009834 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00009835 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009836 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009837
9838 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +00009839 ICE->getCastKind(),
9840 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00009841 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009842 }
9843
Douglas Gregor51c538b2009-11-20 19:42:02 +00009844 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00009845 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00009846 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009847 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9848 if (Method->isStatic()) {
9849 // Do nothing: static member functions aren't any different
9850 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00009851 } else {
John McCalle66edc12009-11-24 19:00:30 +00009852 // Fix the sub expression, which really has to be an
9853 // UnresolvedLookupExpr holding an overloaded member function
9854 // or template.
John McCall16df1e52010-03-30 21:47:33 +00009855 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9856 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00009857 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009858 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00009859
John McCalld14a8642009-11-21 08:51:07 +00009860 assert(isa<DeclRefExpr>(SubExpr)
9861 && "fixed to something other than a decl ref");
9862 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
9863 && "fixed to a member ref with no nested name qualifier");
9864
9865 // We have taken the address of a pointer to member
9866 // function. Perform the computation here so that we get the
9867 // appropriate pointer to member type.
9868 QualType ClassType
9869 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
9870 QualType MemPtrType
9871 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
9872
John McCall7decc9e2010-11-18 06:31:45 +00009873 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
9874 VK_RValue, OK_Ordinary,
9875 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009876 }
9877 }
John McCall16df1e52010-03-30 21:47:33 +00009878 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9879 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009880 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009881 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009882
John McCalle3027922010-08-25 11:45:40 +00009883 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009884 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00009885 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00009886 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009887 }
John McCalld14a8642009-11-21 08:51:07 +00009888
9889 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00009890 // FIXME: avoid copy.
9891 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00009892 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00009893 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
9894 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00009895 }
9896
John McCalld14a8642009-11-21 08:51:07 +00009897 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009898 ULE->getQualifierLoc(),
John McCalld14a8642009-11-21 08:51:07 +00009899 Fn,
9900 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009901 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009902 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009903 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009904 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00009905 }
9906
John McCall10eae182009-11-30 22:42:35 +00009907 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00009908 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00009909 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9910 if (MemExpr->hasExplicitTemplateArgs()) {
9911 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9912 TemplateArgs = &TemplateArgsBuffer;
9913 }
John McCall6b51f282009-11-23 01:53:49 +00009914
John McCall2d74de92009-12-01 22:10:20 +00009915 Expr *Base;
9916
John McCall7decc9e2010-11-18 06:31:45 +00009917 // If we're filling in a static method where we used to have an
9918 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00009919 if (MemExpr->isImplicitAccess()) {
9920 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9921 return DeclRefExpr::Create(Context,
Douglas Gregorea972d32011-02-28 21:54:11 +00009922 MemExpr->getQualifierLoc(),
John McCall2d74de92009-12-01 22:10:20 +00009923 Fn,
9924 MemExpr->getMemberLoc(),
9925 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00009926 VK_LValue,
Chandler Carruth8d26bb02011-05-01 23:48:14 +00009927 Found.getDecl(),
John McCall2d74de92009-12-01 22:10:20 +00009928 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00009929 } else {
9930 SourceLocation Loc = MemExpr->getMemberLoc();
9931 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +00009932 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +00009933 Base = new (Context) CXXThisExpr(Loc,
9934 MemExpr->getBaseType(),
9935 /*isImplicit=*/true);
9936 }
John McCall2d74de92009-12-01 22:10:20 +00009937 } else
John McCallc3007a22010-10-26 07:05:15 +00009938 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00009939
John McCall4adb38c2011-04-27 00:36:17 +00009940 ExprValueKind valueKind;
9941 QualType type;
9942 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
9943 valueKind = VK_LValue;
9944 type = Fn->getType();
9945 } else {
9946 valueKind = VK_RValue;
9947 type = Context.BoundMemberTy;
9948 }
9949
John McCall2d74de92009-12-01 22:10:20 +00009950 return MemberExpr::Create(Context, Base,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009951 MemExpr->isArrow(),
Douglas Gregorea972d32011-02-28 21:54:11 +00009952 MemExpr->getQualifierLoc(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009953 Fn,
John McCall16df1e52010-03-30 21:47:33 +00009954 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009955 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00009956 TemplateArgs,
John McCall4adb38c2011-04-27 00:36:17 +00009957 type, valueKind, OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009958 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009959
John McCallc3007a22010-10-26 07:05:15 +00009960 llvm_unreachable("Invalid reference to overloaded function");
9961 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00009962}
9963
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009964ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +00009965 DeclAccessPair Found,
9966 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00009967 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00009968}
9969
Douglas Gregor5251f1b2008-10-21 16:13:35 +00009970} // end namespace clang