blob: b54f1a30ab1e29f64421cfa33714f29479c059f3 [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
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregore9d62932011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000043 DeclRefExpr *DRE = new (S.Context) DeclRefExpr(Fn, Fn->getType(),
44 VK_LValue, Loc, LocInfo);
45 if (HadMultipleCandidates)
46 DRE->setHadMultipleCandidates(true);
47 ExprResult E = S.Owned(DRE);
John Wiegley01296292011-04-08 18:41:53 +000048 E = S.DefaultFunctionArrayConversion(E.take());
49 if (E.isInvalid())
50 return ExprError();
51 return move(E);
John McCall7decc9e2010-11-18 06:31:45 +000052}
53
John McCall5c32be02010-08-24 20:38:10 +000054static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
55 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +000056 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +000057 bool CStyle,
58 bool AllowObjCWritebackConversion);
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +000059
60static bool IsTransparentUnionStandardConversion(Sema &S, Expr* From,
61 QualType &ToType,
62 bool InOverloadResolution,
63 StandardConversionSequence &SCS,
64 bool CStyle);
John McCall5c32be02010-08-24 20:38:10 +000065static OverloadingResult
66IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
67 UserDefinedConversionSequence& User,
68 OverloadCandidateSet& Conversions,
69 bool AllowExplicit);
70
71
72static ImplicitConversionSequence::CompareKind
73CompareStandardConversionSequences(Sema &S,
74 const StandardConversionSequence& SCS1,
75 const StandardConversionSequence& SCS2);
76
77static ImplicitConversionSequence::CompareKind
78CompareQualificationConversions(Sema &S,
79 const StandardConversionSequence& SCS1,
80 const StandardConversionSequence& SCS2);
81
82static ImplicitConversionSequence::CompareKind
83CompareDerivedToBaseConversions(Sema &S,
84 const StandardConversionSequence& SCS1,
85 const StandardConversionSequence& SCS2);
86
87
88
Douglas Gregor5251f1b2008-10-21 16:13:35 +000089/// GetConversionCategory - Retrieve the implicit conversion
90/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000091ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000092GetConversionCategory(ImplicitConversionKind Kind) {
93 static const ImplicitConversionCategory
94 Category[(int)ICK_Num_Conversion_Kinds] = {
95 ICC_Identity,
96 ICC_Lvalue_Transformation,
97 ICC_Lvalue_Transformation,
98 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000099 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000100 ICC_Qualification_Adjustment,
101 ICC_Promotion,
102 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000103 ICC_Promotion,
104 ICC_Conversion,
105 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000106 ICC_Conversion,
107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000111 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000112 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000113 ICC_Conversion,
114 ICC_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000115 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000116 ICC_Conversion
117 };
118 return Category[(int)Kind];
119}
120
121/// GetConversionRank - Retrieve the implicit conversion rank
122/// corresponding to the given implicit conversion kind.
123ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
124 static const ImplicitConversionRank
125 Rank[(int)ICK_Num_Conversion_Kinds] = {
126 ICR_Exact_Match,
127 ICR_Exact_Match,
128 ICR_Exact_Match,
129 ICR_Exact_Match,
130 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000131 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000132 ICR_Promotion,
133 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000134 ICR_Promotion,
135 ICR_Conversion,
136 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000142 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000143 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000144 ICR_Conversion,
145 ICR_Conversion,
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000146 ICR_Complex_Real_Conversion,
147 ICR_Conversion,
John McCall31168b02011-06-15 23:02:42 +0000148 ICR_Conversion,
149 ICR_Writeback_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000150 };
151 return Rank[(int)Kind];
152}
153
154/// GetImplicitConversionName - Return the name of this kind of
155/// implicit conversion.
156const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000158 "No conversion",
159 "Lvalue-to-rvalue",
160 "Array-to-pointer",
161 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000162 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000163 "Qualification",
164 "Integral promotion",
165 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000166 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000167 "Integral conversion",
168 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000169 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000170 "Floating-integral conversion",
171 "Pointer conversion",
172 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000173 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000174 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000175 "Derived-to-base conversion",
176 "Vector conversion",
177 "Vector splat",
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +0000178 "Complex-real conversion",
179 "Block Pointer conversion",
180 "Transparent Union Conversion"
John McCall31168b02011-06-15 23:02:42 +0000181 "Writeback conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000182 };
183 return Name[Kind];
184}
185
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000186/// StandardConversionSequence - Set the standard conversion
187/// sequence to the identity conversion.
188void StandardConversionSequence::setAsIdentityConversion() {
189 First = ICK_Identity;
190 Second = ICK_Identity;
191 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000192 DeprecatedStringLiteralToCharPtr = false;
John McCall31168b02011-06-15 23:02:42 +0000193 QualificationIncludesObjCLifetime = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000194 ReferenceBinding = false;
195 DirectBinding = false;
Douglas Gregore696ebb2011-01-26 14:52:12 +0000196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +0000199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +0000200 ObjCLifetimeConversionBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000201 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000202}
203
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000204/// getRank - Retrieve the rank of this standard conversion sequence
205/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
206/// implicit conversions.
207ImplicitConversionRank StandardConversionSequence::getRank() const {
208 ImplicitConversionRank Rank = ICR_Exact_Match;
209 if (GetConversionRank(First) > Rank)
210 Rank = GetConversionRank(First);
211 if (GetConversionRank(Second) > Rank)
212 Rank = GetConversionRank(Second);
213 if (GetConversionRank(Third) > Rank)
214 Rank = GetConversionRank(Third);
215 return Rank;
216}
217
218/// isPointerConversionToBool - Determines whether this conversion is
219/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000220/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000221/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000222bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000223 // Note that FromType has not necessarily been transformed by the
224 // array-to-pointer or function-to-pointer implicit conversions, so
225 // check for their presence as well as checking whether FromType is
226 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000227 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000228 (getFromType()->isPointerType() ||
229 getFromType()->isObjCObjectPointerType() ||
230 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000231 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000232 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
233 return true;
234
235 return false;
236}
237
Douglas Gregor5c407d92008-10-23 00:40:37 +0000238/// isPointerConversionToVoidPointer - Determines whether this
239/// conversion is a conversion of a pointer to a void pointer. This is
240/// used as part of the ranking of standard conversion sequences (C++
241/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000242bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000243StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000244isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000245 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000246 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000247
248 // Note that FromType has not necessarily been transformed by the
249 // array-to-pointer implicit conversion, so check for its presence
250 // and redo the conversion to get a pointer.
251 if (First == ICK_Array_To_Pointer)
252 FromType = Context.getArrayDecayedType(FromType);
253
Douglas Gregor5d3d3fa2011-04-15 20:45:44 +0000254 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000255 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000256 return ToPtrType->getPointeeType()->isVoidType();
257
258 return false;
259}
260
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000261/// DebugPrint - Print this standard conversion sequence to standard
262/// error. Useful for debugging overloading issues.
263void StandardConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000264 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 bool PrintedSomething = false;
266 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000267 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000268 PrintedSomething = true;
269 }
270
271 if (Second != ICK_Identity) {
272 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000273 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000274 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000275 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000276
277 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000278 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000279 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000280 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000281 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000282 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000283 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000284 PrintedSomething = true;
285 }
286
287 if (Third != ICK_Identity) {
288 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000289 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000290 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000291 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000292 PrintedSomething = true;
293 }
294
295 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000296 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000297 }
298}
299
300/// DebugPrint - Print this user-defined conversion sequence to standard
301/// error. Useful for debugging overloading issues.
302void UserDefinedConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000303 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000304 if (Before.First || Before.Second || Before.Third) {
305 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000306 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000307 }
Sebastian Redl72ef7bc2011-11-01 15:53:09 +0000308 if (ConversionFunction)
309 OS << '\'' << *ConversionFunction << '\'';
310 else
311 OS << "aggregate initialization";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000312 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000313 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000314 After.DebugPrint();
315 }
316}
317
318/// DebugPrint - Print this implicit conversion sequence to standard
319/// error. Useful for debugging overloading issues.
320void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000321 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000322 switch (ConversionKind) {
323 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000324 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000325 Standard.DebugPrint();
326 break;
327 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000328 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000329 UserDefined.DebugPrint();
330 break;
331 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000332 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000333 break;
John McCall0d1da222010-01-12 00:44:57 +0000334 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000335 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000336 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000337 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000338 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000339 break;
340 }
341
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000342 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000343}
344
John McCall0d1da222010-01-12 00:44:57 +0000345void AmbiguousConversionSequence::construct() {
346 new (&conversions()) ConversionSet();
347}
348
349void AmbiguousConversionSequence::destruct() {
350 conversions().~ConversionSet();
351}
352
353void
354AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
355 FromTypePtr = O.FromTypePtr;
356 ToTypePtr = O.ToTypePtr;
357 new (&conversions()) ConversionSet(O.conversions());
358}
359
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000360namespace {
361 // Structure used by OverloadCandidate::DeductionFailureInfo to store
362 // template parameter and template argument information.
363 struct DFIParamWithArguments {
364 TemplateParameter Param;
365 TemplateArgument FirstArg;
366 TemplateArgument SecondArg;
367 };
368}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000369
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000370/// \brief Convert from Sema's representation of template deduction information
371/// to the form used in overload-candidate information.
372OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000373static MakeDeductionFailureInfo(ASTContext &Context,
374 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000375 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000376 OverloadCandidate::DeductionFailureInfo Result;
377 Result.Result = static_cast<unsigned>(TDK);
378 Result.Data = 0;
379 switch (TDK) {
380 case Sema::TDK_Success:
381 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000382 case Sema::TDK_TooManyArguments:
383 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000384 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000385
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000386 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000387 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000388 Result.Data = Info.Param.getOpaqueValue();
389 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000390
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000391 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000392 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000393 // FIXME: Should allocate from normal heap so that we can free this later.
394 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000395 Saved->Param = Info.Param;
396 Saved->FirstArg = Info.FirstArg;
397 Saved->SecondArg = Info.SecondArg;
398 Result.Data = Saved;
399 break;
400 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000401
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000402 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000403 Result.Data = Info.take();
404 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000405
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000406 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000407 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000408 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000409 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000410
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000411 return Result;
412}
John McCall0d1da222010-01-12 00:44:57 +0000413
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000414void OverloadCandidate::DeductionFailureInfo::Destroy() {
415 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
416 case Sema::TDK_Success:
417 case Sema::TDK_InstantiationDepth:
418 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000419 case Sema::TDK_TooManyArguments:
420 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000421 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000422 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000423
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000424 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000425 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000426 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000427 Data = 0;
428 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000429
430 case Sema::TDK_SubstitutionFailure:
431 // FIXME: Destroy the template arugment list?
432 Data = 0;
433 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000434
Douglas Gregor461761d2010-05-08 18:20:53 +0000435 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000436 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000437 case Sema::TDK_FailedOverloadResolution:
438 break;
439 }
440}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000441
442TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000443OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
444 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
445 case Sema::TDK_Success:
446 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000447 case Sema::TDK_TooManyArguments:
448 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000449 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000450 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000451
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000452 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000453 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000454 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000455
456 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000457 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000458 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000459
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000460 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000461 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000462 case Sema::TDK_FailedOverloadResolution:
463 break;
464 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000465
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000466 return TemplateParameter();
467}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000468
Douglas Gregord09efd42010-05-08 20:07:26 +0000469TemplateArgumentList *
470OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
471 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
472 case Sema::TDK_Success:
473 case Sema::TDK_InstantiationDepth:
474 case Sema::TDK_TooManyArguments:
475 case Sema::TDK_TooFewArguments:
476 case Sema::TDK_Incomplete:
477 case Sema::TDK_InvalidExplicitArguments:
478 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000479 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000480 return 0;
481
482 case Sema::TDK_SubstitutionFailure:
483 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000484
Douglas Gregord09efd42010-05-08 20:07:26 +0000485 // Unhandled
486 case Sema::TDK_NonDeducedMismatch:
487 case Sema::TDK_FailedOverloadResolution:
488 break;
489 }
490
491 return 0;
492}
493
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000494const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
495 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
496 case Sema::TDK_Success:
497 case Sema::TDK_InstantiationDepth:
498 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000499 case Sema::TDK_TooManyArguments:
500 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000501 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000502 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000503 return 0;
504
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000505 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000506 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000507 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000508
Douglas Gregor461761d2010-05-08 18:20:53 +0000509 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000510 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000511 case Sema::TDK_FailedOverloadResolution:
512 break;
513 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000514
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000515 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000516}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000517
518const TemplateArgument *
519OverloadCandidate::DeductionFailureInfo::getSecondArg() {
520 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
521 case Sema::TDK_Success:
522 case Sema::TDK_InstantiationDepth:
523 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000524 case Sema::TDK_TooManyArguments:
525 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000526 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000527 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000528 return 0;
529
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000530 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000531 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000532 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
533
Douglas Gregor461761d2010-05-08 18:20:53 +0000534 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000535 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000536 case Sema::TDK_FailedOverloadResolution:
537 break;
538 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000539
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000540 return 0;
541}
542
543void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000544 inherited::clear();
545 Functions.clear();
546}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000547
John McCall4124c492011-10-17 18:40:02 +0000548namespace {
549 class UnbridgedCastsSet {
550 struct Entry {
551 Expr **Addr;
552 Expr *Saved;
553 };
554 SmallVector<Entry, 2> Entries;
555
556 public:
557 void save(Sema &S, Expr *&E) {
558 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
559 Entry entry = { &E, E };
560 Entries.push_back(entry);
561 E = S.stripARCUnbridgedCast(E);
562 }
563
564 void restore() {
565 for (SmallVectorImpl<Entry>::iterator
566 i = Entries.begin(), e = Entries.end(); i != e; ++i)
567 *i->Addr = i->Saved;
568 }
569 };
570}
571
572/// checkPlaceholderForOverload - Do any interesting placeholder-like
573/// preprocessing on the given expression.
574///
575/// \param unbridgedCasts a collection to which to add unbridged casts;
576/// without this, they will be immediately diagnosed as errors
577///
578/// Return true on unrecoverable error.
579static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
580 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall4124c492011-10-17 18:40:02 +0000581 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
582 // We can't handle overloaded expressions here because overload
583 // resolution might reasonably tweak them.
584 if (placeholder->getKind() == BuiltinType::Overload) return false;
585
586 // If the context potentially accepts unbridged ARC casts, strip
587 // the unbridged cast and add it to the collection for later restoration.
588 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
589 unbridgedCasts) {
590 unbridgedCasts->save(S, E);
591 return false;
592 }
593
594 // Go ahead and check everything else.
595 ExprResult result = S.CheckPlaceholderExpr(E);
596 if (result.isInvalid())
597 return true;
598
599 E = result.take();
600 return false;
601 }
602
603 // Nothing to do.
604 return false;
605}
606
607/// checkArgPlaceholdersForOverload - Check a set of call operands for
608/// placeholders.
609static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
610 unsigned numArgs,
611 UnbridgedCastsSet &unbridged) {
612 for (unsigned i = 0; i != numArgs; ++i)
613 if (checkPlaceholderForOverload(S, args[i], &unbridged))
614 return true;
615
616 return false;
617}
618
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000619// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000620// overload of the declarations in Old. This routine returns false if
621// New and Old cannot be overloaded, e.g., if New has the same
622// signature as some function in Old (C++ 1.3.10) or if the Old
623// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000624// it does return false, MatchedDecl will point to the decl that New
625// cannot be overloaded with. This decl may be a UsingShadowDecl on
626// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000627//
628// Example: Given the following input:
629//
630// void f(int, float); // #1
631// void f(int, int); // #2
632// int f(int, int); // #3
633//
634// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000635// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000636//
John McCall3d988d92009-12-02 08:47:38 +0000637// When we process #2, Old contains only the FunctionDecl for #1. By
638// comparing the parameter types, we see that #1 and #2 are overloaded
639// (since they have different signatures), so this routine returns
640// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000641//
John McCall3d988d92009-12-02 08:47:38 +0000642// When we process #3, Old is an overload set containing #1 and #2. We
643// compare the signatures of #3 to #1 (they're overloaded, so we do
644// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
645// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000646// signature), IsOverload returns false and MatchedDecl will be set to
647// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000648//
649// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
650// into a class by a using declaration. The rules for whether to hide
651// shadow declarations ignore some properties which otherwise figure
652// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000653Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000654Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
655 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000656 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000657 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000658 NamedDecl *OldD = *I;
659
660 bool OldIsUsingDecl = false;
661 if (isa<UsingShadowDecl>(OldD)) {
662 OldIsUsingDecl = true;
663
664 // We can always introduce two using declarations into the same
665 // context, even if they have identical signatures.
666 if (NewIsUsingDecl) continue;
667
668 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
669 }
670
671 // If either declaration was introduced by a using declaration,
672 // we'll need to use slightly different rules for matching.
673 // Essentially, these rules are the normal rules, except that
674 // function templates hide function templates with different
675 // return types or template parameter lists.
676 bool UseMemberUsingDeclRules =
677 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
678
John McCall3d988d92009-12-02 08:47:38 +0000679 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000680 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
681 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
682 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
683 continue;
684 }
685
John McCalldaa3d6b2009-12-09 03:35:25 +0000686 Match = *I;
687 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000688 }
John McCall3d988d92009-12-02 08:47:38 +0000689 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000690 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
691 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
692 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
693 continue;
694 }
695
John McCalldaa3d6b2009-12-09 03:35:25 +0000696 Match = *I;
697 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000698 }
John McCalla8987a2942010-11-10 03:01:53 +0000699 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000700 // We can overload with these, which can show up when doing
701 // redeclaration checks for UsingDecls.
702 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000703 } else if (isa<TagDecl>(OldD)) {
704 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000705 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
706 // Optimistically assume that an unresolved using decl will
707 // overload; if it doesn't, we'll have to diagnose during
708 // template instantiation.
709 } else {
John McCall1f82f242009-11-18 22:49:29 +0000710 // (C++ 13p1):
711 // Only function declarations can be overloaded; object and type
712 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000713 Match = *I;
714 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000715 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000716 }
John McCall1f82f242009-11-18 22:49:29 +0000717
John McCalldaa3d6b2009-12-09 03:35:25 +0000718 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000719}
720
John McCalle9cccd82010-06-16 08:42:20 +0000721bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
722 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000723 // If both of the functions are extern "C", then they are not
724 // overloads.
725 if (Old->isExternC() && New->isExternC())
726 return false;
727
John McCall1f82f242009-11-18 22:49:29 +0000728 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
729 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
730
731 // C++ [temp.fct]p2:
732 // A function template can be overloaded with other function templates
733 // and with normal (non-template) functions.
734 if ((OldTemplate == 0) != (NewTemplate == 0))
735 return true;
736
737 // Is the function New an overload of the function Old?
738 QualType OldQType = Context.getCanonicalType(Old->getType());
739 QualType NewQType = Context.getCanonicalType(New->getType());
740
741 // Compare the signatures (C++ 1.3.10) of the two functions to
742 // determine whether they are overloads. If we find any mismatch
743 // in the signature, they are overloads.
744
745 // If either of these functions is a K&R-style function (no
746 // prototype), then we consider them to have matching signatures.
747 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
748 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
749 return false;
750
John McCall424cec92011-01-19 06:33:43 +0000751 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
752 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000753
754 // The signature of a function includes the types of its
755 // parameters (C++ 1.3.10), which includes the presence or absence
756 // of the ellipsis; see C++ DR 357).
757 if (OldQType != NewQType &&
758 (OldType->getNumArgs() != NewType->getNumArgs() ||
759 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000760 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000761 return true;
762
763 // C++ [temp.over.link]p4:
764 // The signature of a function template consists of its function
765 // signature, its return type and its template parameter list. The names
766 // of the template parameters are significant only for establishing the
767 // relationship between the template parameters and the rest of the
768 // signature.
769 //
770 // We check the return type and template parameter lists for function
771 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000772 //
773 // However, we don't consider either of these when deciding whether
774 // a member introduced by a shadow declaration is hidden.
775 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000776 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
777 OldTemplate->getTemplateParameters(),
778 false, TPL_TemplateMatch) ||
779 OldType->getResultType() != NewType->getResultType()))
780 return true;
781
782 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000783 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000784 //
785 // As part of this, also check whether one of the member functions
786 // is static, in which case they are not overloads (C++
787 // 13.1p2). While not part of the definition of the signature,
788 // this check is important to determine whether these functions
789 // can be overloaded.
790 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
791 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
792 if (OldMethod && NewMethod &&
793 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000794 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000795 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
796 if (!UseUsingDeclRules &&
797 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
798 (OldMethod->getRefQualifier() == RQ_None ||
799 NewMethod->getRefQualifier() == RQ_None)) {
800 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000801 // - Member function declarations with the same name and the same
802 // parameter-type-list as well as member function template
803 // declarations with the same name, the same parameter-type-list, and
804 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000805 // them, but not all, have a ref-qualifier (8.3.5).
806 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
807 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
808 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
809 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000810
John McCall1f82f242009-11-18 22:49:29 +0000811 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000812 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000813
John McCall1f82f242009-11-18 22:49:29 +0000814 // The signatures match; this is not an overload.
815 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000816}
817
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000818/// \brief Checks availability of the function depending on the current
819/// function context. Inside an unavailable function, unavailability is ignored.
820///
821/// \returns true if \arg FD is unavailable and current context is inside
822/// an available function, false otherwise.
823bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
824 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
825}
826
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000827/// TryImplicitConversion - Attempt to perform an implicit conversion
828/// from the given expression (Expr) to the given type (ToType). This
829/// function returns an implicit conversion sequence that can be used
830/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000831///
832/// void f(float f);
833/// void g(int i) { f(i); }
834///
835/// this routine would produce an implicit conversion sequence to
836/// describe the initialization of f from i, which will be a standard
837/// conversion sequence containing an lvalue-to-rvalue conversion (C++
838/// 4.1) followed by a floating-integral conversion (C++ 4.9).
839//
840/// Note that this routine only determines how the conversion can be
841/// performed; it does not actually perform the conversion. As such,
842/// it will not produce any diagnostics if no conversion is available,
843/// but will instead return an implicit conversion sequence of kind
844/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000845///
846/// If @p SuppressUserConversions, then user-defined conversions are
847/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000848/// If @p AllowExplicit, then explicit user-defined conversions are
849/// permitted.
John McCall31168b02011-06-15 23:02:42 +0000850///
851/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
852/// writeback conversion, which allows __autoreleasing id* parameters to
853/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +0000854static ImplicitConversionSequence
855TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
856 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000857 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000858 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000859 bool CStyle,
860 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000861 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000862 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000863 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +0000864 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000865 return ICS;
866 }
867
John McCall5c32be02010-08-24 20:38:10 +0000868 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000869 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000870 return ICS;
871 }
872
Douglas Gregor836a7e82010-08-11 02:15:33 +0000873 // C++ [over.ics.user]p4:
874 // A conversion of an expression of class type to the same class
875 // type is given Exact Match rank, and a conversion of an
876 // expression of class type to a base class of that type is
877 // given Conversion rank, in spite of the fact that a copy/move
878 // constructor (i.e., a user-defined conversion function) is
879 // called for those cases.
880 QualType FromType = From->getType();
881 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000882 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
883 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000884 ICS.setStandard();
885 ICS.Standard.setAsIdentityConversion();
886 ICS.Standard.setFromType(FromType);
887 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000888
Douglas Gregor5ab11652010-04-17 22:01:05 +0000889 // We don't actually check at this point whether there is a valid
890 // copy/move constructor, since overloading just assumes that it
891 // exists. When we actually perform initialization, we'll find the
892 // appropriate constructor to copy the returned object, if needed.
893 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000894
Douglas Gregor5ab11652010-04-17 22:01:05 +0000895 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000896 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000897 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000898
Douglas Gregor836a7e82010-08-11 02:15:33 +0000899 return ICS;
900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000901
Douglas Gregor836a7e82010-08-11 02:15:33 +0000902 if (SuppressUserConversions) {
903 // We're not in the case above, so there is no conversion that
904 // we can perform.
905 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000906 return ICS;
907 }
908
909 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000910 OverloadCandidateSet Conversions(From->getExprLoc());
911 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000912 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000913 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000914
915 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000916 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000917 // C++ [over.ics.user]p4:
918 // A conversion of an expression of class type to the same class
919 // type is given Exact Match rank, and a conversion of an
920 // expression of class type to a base class of that type is
921 // given Conversion rank, in spite of the fact that a copy
922 // constructor (i.e., a user-defined conversion function) is
923 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000924 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000925 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000926 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000927 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
928 QualType ToCanon
929 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000930 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000931 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000932 // Turn this into a "standard" conversion sequence, so that it
933 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000934 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000935 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000936 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000937 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000938 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000939 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000940 ICS.Standard.Second = ICK_Derived_To_Base;
941 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000942 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000943
944 // C++ [over.best.ics]p4:
945 // However, when considering the argument of a user-defined
946 // conversion function that is a candidate by 13.3.1.3 when
947 // invoked for the copying of the temporary in the second step
948 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
949 // 13.3.1.6 in all cases, only standard conversion sequences and
950 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000951 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000952 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000953 }
John McCalle8c8cd22010-01-13 22:30:33 +0000954 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000955 ICS.setAmbiguous();
956 ICS.Ambiguous.setFromType(From->getType());
957 ICS.Ambiguous.setToType(ToType);
958 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
959 Cand != Conversions.end(); ++Cand)
960 if (Cand->Viable)
961 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000962 } else {
John McCall65eb8792010-02-25 01:37:24 +0000963 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000964 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000965
966 return ICS;
967}
968
John McCall31168b02011-06-15 23:02:42 +0000969ImplicitConversionSequence
970Sema::TryImplicitConversion(Expr *From, QualType ToType,
971 bool SuppressUserConversions,
972 bool AllowExplicit,
973 bool InOverloadResolution,
974 bool CStyle,
975 bool AllowObjCWritebackConversion) {
976 return clang::TryImplicitConversion(*this, From, ToType,
977 SuppressUserConversions, AllowExplicit,
978 InOverloadResolution, CStyle,
979 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +0000980}
981
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000982/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +0000983/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000984/// converted expression. Flavor is the kind of conversion we're
985/// performing, used in the error message. If @p AllowExplicit,
986/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +0000987ExprResult
988Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +0000989 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000990 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +0000991 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000992}
993
John Wiegley01296292011-04-08 18:41:53 +0000994ExprResult
995Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000996 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +0000997 ImplicitConversionSequence& ICS) {
John McCall526ab472011-10-25 17:37:35 +0000998 if (checkPlaceholderForOverload(*this, From))
999 return ExprError();
1000
John McCall31168b02011-06-15 23:02:42 +00001001 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1002 bool AllowObjCWritebackConversion
1003 = getLangOptions().ObjCAutoRefCount &&
1004 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001005
John McCall5c32be02010-08-24 20:38:10 +00001006 ICS = clang::TryImplicitConversion(*this, From, ToType,
1007 /*SuppressUserConversions=*/false,
1008 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001009 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001010 /*CStyle=*/false,
1011 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001012 return PerformImplicitConversion(From, ToType, ICS, Action);
1013}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001014
1015/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001016/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001017bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1018 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001019 if (Context.hasSameUnqualifiedType(FromType, ToType))
1020 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001021
John McCall991eb4b2010-12-21 00:44:39 +00001022 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1023 // where F adds one of the following at most once:
1024 // - a pointer
1025 // - a member pointer
1026 // - a block pointer
1027 CanQualType CanTo = Context.getCanonicalType(ToType);
1028 CanQualType CanFrom = Context.getCanonicalType(FromType);
1029 Type::TypeClass TyClass = CanTo->getTypeClass();
1030 if (TyClass != CanFrom->getTypeClass()) return false;
1031 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1032 if (TyClass == Type::Pointer) {
1033 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1034 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1035 } else if (TyClass == Type::BlockPointer) {
1036 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1037 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1038 } else if (TyClass == Type::MemberPointer) {
1039 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1040 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1041 } else {
1042 return false;
1043 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001044
John McCall991eb4b2010-12-21 00:44:39 +00001045 TyClass = CanTo->getTypeClass();
1046 if (TyClass != CanFrom->getTypeClass()) return false;
1047 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1048 return false;
1049 }
1050
1051 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1052 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1053 if (!EInfo.getNoReturn()) return false;
1054
1055 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1056 assert(QualType(FromFn, 0).isCanonical());
1057 if (QualType(FromFn, 0) != CanTo) return false;
1058
1059 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001060 return true;
1061}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001062
Douglas Gregor46188682010-05-18 22:42:18 +00001063/// \brief Determine whether the conversion from FromType to ToType is a valid
1064/// vector conversion.
1065///
1066/// \param ICK Will be set to the vector conversion kind, if this is a vector
1067/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001068static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1069 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001070 // We need at least one of these types to be a vector type to have a vector
1071 // conversion.
1072 if (!ToType->isVectorType() && !FromType->isVectorType())
1073 return false;
1074
1075 // Identical types require no conversions.
1076 if (Context.hasSameUnqualifiedType(FromType, ToType))
1077 return false;
1078
1079 // There are no conversions between extended vector types, only identity.
1080 if (ToType->isExtVectorType()) {
1081 // There are no conversions between extended vector types other than the
1082 // identity conversion.
1083 if (FromType->isExtVectorType())
1084 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001085
Douglas Gregor46188682010-05-18 22:42:18 +00001086 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001087 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001088 ICK = ICK_Vector_Splat;
1089 return true;
1090 }
1091 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001092
1093 // We can perform the conversion between vector types in the following cases:
1094 // 1)vector types are equivalent AltiVec and GCC vector types
1095 // 2)lax vector conversions are permitted and the vector types are of the
1096 // same size
1097 if (ToType->isVectorType() && FromType->isVectorType()) {
1098 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001099 (Context.getLangOptions().LaxVectorConversions &&
1100 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001101 ICK = ICK_Vector_Conversion;
1102 return true;
1103 }
Douglas Gregor46188682010-05-18 22:42:18 +00001104 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001105
Douglas Gregor46188682010-05-18 22:42:18 +00001106 return false;
1107}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001108
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001109/// IsStandardConversion - Determines whether there is a standard
1110/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1111/// expression From to the type ToType. Standard conversion sequences
1112/// only consider non-class types; for conversions that involve class
1113/// types, use TryImplicitConversion. If a conversion exists, SCS will
1114/// contain the standard conversion sequence required to perform this
1115/// conversion and this routine will return true. Otherwise, this
1116/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001117static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1118 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001119 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001120 bool CStyle,
1121 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001122 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001123
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001124 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001125 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001126 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001127 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001128 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001129 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001130
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001131 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001132 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001133 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001134 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001135 return false;
1136
Mike Stump11289f42009-09-09 15:08:12 +00001137 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001138 }
1139
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001140 // The first conversion can be an lvalue-to-rvalue conversion,
1141 // array-to-pointer conversion, or function-to-pointer conversion
1142 // (C++ 4p1).
1143
John McCall5c32be02010-08-24 20:38:10 +00001144 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001145 DeclAccessPair AccessPair;
1146 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001147 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001148 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001149 // We were able to resolve the address of the overloaded function,
1150 // so we can convert to the type of that function.
1151 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001152
1153 // we can sometimes resolve &foo<int> regardless of ToType, so check
1154 // if the type matches (identity) or we are converting to bool
1155 if (!S.Context.hasSameUnqualifiedType(
1156 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1157 QualType resultTy;
1158 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001159 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001160 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1161 // otherwise, only a boolean conversion is standard
1162 if (!ToType->isBooleanType())
1163 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001165
Chandler Carruthffce2452011-03-29 08:08:18 +00001166 // Check if the "from" expression is taking the address of an overloaded
1167 // function and recompute the FromType accordingly. Take advantage of the
1168 // fact that non-static member functions *must* have such an address-of
1169 // expression.
1170 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1171 if (Method && !Method->isStatic()) {
1172 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1173 "Non-unary operator on non-static member address");
1174 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1175 == UO_AddrOf &&
1176 "Non-address-of operator on non-static member address");
1177 const Type *ClassType
1178 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1179 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001180 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1181 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1182 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001183 "Non-address-of operator for overloaded function expression");
1184 FromType = S.Context.getPointerType(FromType);
1185 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001186
Douglas Gregor980fb162010-04-29 18:24:40 +00001187 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001188 assert(S.Context.hasSameType(
1189 FromType,
1190 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001191 } else {
1192 return false;
1193 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001194 }
John McCall154a2fd2011-08-30 00:57:29 +00001195 // Lvalue-to-rvalue conversion (C++11 4.1):
1196 // A glvalue (3.10) of a non-function, non-array type T can
1197 // be converted to a prvalue.
1198 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001199 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001200 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001201 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001202 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001203
1204 // If T is a non-class type, the type of the rvalue is the
1205 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001206 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1207 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001208 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001209 } else if (FromType->isArrayType()) {
1210 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001211 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001212
1213 // An lvalue or rvalue of type "array of N T" or "array of unknown
1214 // bound of T" can be converted to an rvalue of type "pointer to
1215 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001216 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001217
John McCall5c32be02010-08-24 20:38:10 +00001218 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001219 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001220 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001221
1222 // For the purpose of ranking in overload resolution
1223 // (13.3.3.1.1), this conversion is considered an
1224 // array-to-pointer conversion followed by a qualification
1225 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001226 SCS.Second = ICK_Identity;
1227 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001228 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001229 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001230 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001231 }
John McCall086a4642010-11-24 05:12:34 +00001232 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001233 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001234 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001235
1236 // An lvalue of function type T can be converted to an rvalue of
1237 // type "pointer to T." The result is a pointer to the
1238 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001239 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001240 } else {
1241 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001242 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001243 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001244 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001245
1246 // The second conversion can be an integral promotion, floating
1247 // point promotion, integral conversion, floating point conversion,
1248 // floating-integral conversion, pointer conversion,
1249 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001250 // For overloading in C, this can also be a "compatible-type"
1251 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001252 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001253 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001254 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001255 // The unqualified versions of the types are the same: there's no
1256 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001257 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001258 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001259 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001260 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001261 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001262 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001263 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001264 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001265 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001266 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001267 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001268 SCS.Second = ICK_Complex_Promotion;
1269 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001270 } else if (ToType->isBooleanType() &&
1271 (FromType->isArithmeticType() ||
1272 FromType->isAnyPointerType() ||
1273 FromType->isBlockPointerType() ||
1274 FromType->isMemberPointerType() ||
1275 FromType->isNullPtrType())) {
1276 // Boolean conversions (C++ 4.12).
1277 SCS.Second = ICK_Boolean_Conversion;
1278 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001279 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001280 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001281 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001282 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001283 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001284 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001285 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001286 SCS.Second = ICK_Complex_Conversion;
1287 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001288 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1289 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001290 // Complex-real conversions (C99 6.3.1.7)
1291 SCS.Second = ICK_Complex_Real;
1292 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001293 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001294 // Floating point conversions (C++ 4.8).
1295 SCS.Second = ICK_Floating_Conversion;
1296 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001297 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001298 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001299 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001300 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001301 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001302 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001303 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001304 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001305 SCS.Second = ICK_Block_Pointer_Conversion;
1306 } else if (AllowObjCWritebackConversion &&
1307 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1308 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001309 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1310 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001311 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001312 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001313 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001314 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001315 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001316 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001317 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001318 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001319 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001320 SCS.Second = SecondICK;
1321 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001322 } else if (!S.getLangOptions().CPlusPlus &&
1323 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001324 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001325 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001326 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001327 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001328 // Treat a conversion that strips "noreturn" as an identity conversion.
1329 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001330 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1331 InOverloadResolution,
1332 SCS, CStyle)) {
1333 SCS.Second = ICK_TransparentUnionConversion;
1334 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001335 } else {
1336 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001337 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001338 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001339 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001340
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001341 QualType CanonFrom;
1342 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001343 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001344 bool ObjCLifetimeConversion;
1345 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1346 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001347 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001348 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001349 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001350 CanonFrom = S.Context.getCanonicalType(FromType);
1351 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001352 } else {
1353 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001354 SCS.Third = ICK_Identity;
1355
Mike Stump11289f42009-09-09 15:08:12 +00001356 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001357 // [...] Any difference in top-level cv-qualification is
1358 // subsumed by the initialization itself and does not constitute
1359 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001360 CanonFrom = S.Context.getCanonicalType(FromType);
1361 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001362 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001363 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001364 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001365 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1366 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001367 FromType = ToType;
1368 CanonFrom = CanonTo;
1369 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001370 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001371 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001372
1373 // If we have not converted the argument type to the parameter type,
1374 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001375 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001376 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001377
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001378 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001379}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001380
1381static bool
1382IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1383 QualType &ToType,
1384 bool InOverloadResolution,
1385 StandardConversionSequence &SCS,
1386 bool CStyle) {
1387
1388 const RecordType *UT = ToType->getAsUnionType();
1389 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1390 return false;
1391 // The field to initialize within the transparent union.
1392 RecordDecl *UD = UT->getDecl();
1393 // It's compatible if the expression matches any of the fields.
1394 for (RecordDecl::field_iterator it = UD->field_begin(),
1395 itend = UD->field_end();
1396 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001397 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1398 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001399 ToType = it->getType();
1400 return true;
1401 }
1402 }
1403 return false;
1404}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001405
1406/// IsIntegralPromotion - Determines whether the conversion from the
1407/// expression From (whose potentially-adjusted type is FromType) to
1408/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1409/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001410bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001411 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001412 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001413 if (!To) {
1414 return false;
1415 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001416
1417 // An rvalue of type char, signed char, unsigned char, short int, or
1418 // unsigned short int can be converted to an rvalue of type int if
1419 // int can represent all the values of the source type; otherwise,
1420 // the source rvalue can be converted to an rvalue of type unsigned
1421 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001422 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1423 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001424 if (// We can promote any signed, promotable integer type to an int
1425 (FromType->isSignedIntegerType() ||
1426 // We can promote any unsigned integer type whose size is
1427 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001428 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001429 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001430 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001431 }
1432
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001433 return To->getKind() == BuiltinType::UInt;
1434 }
1435
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001436 // C++0x [conv.prom]p3:
1437 // A prvalue of an unscoped enumeration type whose underlying type is not
1438 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1439 // following types that can represent all the values of the enumeration
1440 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1441 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001442 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001443 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001444 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001445 // with lowest integer conversion rank (4.13) greater than the rank of long
1446 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001447 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001448 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1449 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1450 // provided for a scoped enumeration.
1451 if (FromEnumType->getDecl()->isScoped())
1452 return false;
1453
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001454 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001455 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001456 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001457 return Context.hasSameUnqualifiedType(ToType,
1458 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001459 }
John McCall56774992009-12-09 09:09:27 +00001460
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001461 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001462 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1463 // to an rvalue a prvalue of the first of the following types that can
1464 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001465 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001466 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001467 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001468 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001469 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001470 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001471 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001472 // Determine whether the type we're converting from is signed or
1473 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001474 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001475 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001476
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001477 // The types we'll try to promote to, in the appropriate
1478 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001479 QualType PromoteTypes[6] = {
1480 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001481 Context.LongTy, Context.UnsignedLongTy ,
1482 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001483 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001484 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001485 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1486 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001487 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001488 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1489 // We found the type that we can promote to. If this is the
1490 // type we wanted, we have a promotion. Otherwise, no
1491 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001492 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001493 }
1494 }
1495 }
1496
1497 // An rvalue for an integral bit-field (9.6) can be converted to an
1498 // rvalue of type int if int can represent all the values of the
1499 // bit-field; otherwise, it can be converted to unsigned int if
1500 // unsigned int can represent all the values of the bit-field. If
1501 // the bit-field is larger yet, no integral promotion applies to
1502 // it. If the bit-field has an enumerated type, it is treated as any
1503 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001504 // FIXME: We should delay checking of bit-fields until we actually perform the
1505 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001506 using llvm::APSInt;
1507 if (From)
1508 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001509 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001510 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001511 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1512 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1513 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001514
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001515 // Are we promoting to an int from a bitfield that fits in an int?
1516 if (BitWidth < ToSize ||
1517 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1518 return To->getKind() == BuiltinType::Int;
1519 }
Mike Stump11289f42009-09-09 15:08:12 +00001520
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001521 // Are we promoting to an unsigned int from an unsigned bitfield
1522 // that fits into an unsigned int?
1523 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1524 return To->getKind() == BuiltinType::UInt;
1525 }
Mike Stump11289f42009-09-09 15:08:12 +00001526
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001527 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001528 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001529 }
Mike Stump11289f42009-09-09 15:08:12 +00001530
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001531 // An rvalue of type bool can be converted to an rvalue of type int,
1532 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001533 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001534 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001535 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001536
1537 return false;
1538}
1539
1540/// IsFloatingPointPromotion - Determines whether the conversion from
1541/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1542/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001543bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001544 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1545 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001546 /// An rvalue of type float can be converted to an rvalue of type
1547 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001548 if (FromBuiltin->getKind() == BuiltinType::Float &&
1549 ToBuiltin->getKind() == BuiltinType::Double)
1550 return true;
1551
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001552 // C99 6.3.1.5p1:
1553 // When a float is promoted to double or long double, or a
1554 // double is promoted to long double [...].
1555 if (!getLangOptions().CPlusPlus &&
1556 (FromBuiltin->getKind() == BuiltinType::Float ||
1557 FromBuiltin->getKind() == BuiltinType::Double) &&
1558 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1559 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001560
1561 // Half can be promoted to float.
1562 if (FromBuiltin->getKind() == BuiltinType::Half &&
1563 ToBuiltin->getKind() == BuiltinType::Float)
1564 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001565 }
1566
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001567 return false;
1568}
1569
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001570/// \brief Determine if a conversion is a complex promotion.
1571///
1572/// A complex promotion is defined as a complex -> complex conversion
1573/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001574/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001575bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001576 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001577 if (!FromComplex)
1578 return false;
1579
John McCall9dd450b2009-09-21 23:43:11 +00001580 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001581 if (!ToComplex)
1582 return false;
1583
1584 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001585 ToComplex->getElementType()) ||
1586 IsIntegralPromotion(0, FromComplex->getElementType(),
1587 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001588}
1589
Douglas Gregor237f96c2008-11-26 23:31:11 +00001590/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1591/// the pointer type FromPtr to a pointer to type ToPointee, with the
1592/// same type qualifiers as FromPtr has on its pointee type. ToType,
1593/// if non-empty, will be a pointer to ToType that may or may not have
1594/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001595///
Mike Stump11289f42009-09-09 15:08:12 +00001596static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001597BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001598 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001599 ASTContext &Context,
1600 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001601 assert((FromPtr->getTypeClass() == Type::Pointer ||
1602 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1603 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001604
John McCall31168b02011-06-15 23:02:42 +00001605 /// Conversions to 'id' subsume cv-qualifier conversions.
1606 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001607 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001608
1609 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001610 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001611 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001612 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001613
John McCall31168b02011-06-15 23:02:42 +00001614 if (StripObjCLifetime)
1615 Quals.removeObjCLifetime();
1616
Mike Stump11289f42009-09-09 15:08:12 +00001617 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001618 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001619 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001620 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001621 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001622
1623 // Build a pointer to ToPointee. It has the right qualifiers
1624 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001625 if (isa<ObjCObjectPointerType>(ToType))
1626 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001627 return Context.getPointerType(ToPointee);
1628 }
1629
1630 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001631 QualType QualifiedCanonToPointee
1632 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001633
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001634 if (isa<ObjCObjectPointerType>(ToType))
1635 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1636 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001637}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001638
Mike Stump11289f42009-09-09 15:08:12 +00001639static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001640 bool InOverloadResolution,
1641 ASTContext &Context) {
1642 // Handle value-dependent integral null pointer constants correctly.
1643 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1644 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001645 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001646 return !InOverloadResolution;
1647
Douglas Gregor56751b52009-09-25 04:25:58 +00001648 return Expr->isNullPointerConstant(Context,
1649 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1650 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001651}
Mike Stump11289f42009-09-09 15:08:12 +00001652
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001653/// IsPointerConversion - Determines whether the conversion of the
1654/// expression From, which has the (possibly adjusted) type FromType,
1655/// can be converted to the type ToType via a pointer conversion (C++
1656/// 4.10). If so, returns true and places the converted type (that
1657/// might differ from ToType in its cv-qualifiers at some level) into
1658/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001659///
Douglas Gregora29dc052008-11-27 01:19:21 +00001660/// This routine also supports conversions to and from block pointers
1661/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1662/// pointers to interfaces. FIXME: Once we've determined the
1663/// appropriate overloading rules for Objective-C, we may want to
1664/// split the Objective-C checks into a different routine; however,
1665/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001666/// conversions, so for now they live here. IncompatibleObjC will be
1667/// set if the conversion is an allowed Objective-C conversion that
1668/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001669bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001670 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001671 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001672 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001673 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001674 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1675 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001676 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001677
Mike Stump11289f42009-09-09 15:08:12 +00001678 // Conversion from a null pointer constant to any Objective-C pointer type.
1679 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001680 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001681 ConvertedType = ToType;
1682 return true;
1683 }
1684
Douglas Gregor231d1c62008-11-27 00:15:41 +00001685 // Blocks: Block pointers can be converted to void*.
1686 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001687 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001688 ConvertedType = ToType;
1689 return true;
1690 }
1691 // Blocks: A null pointer constant can be converted to a block
1692 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001693 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001694 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001695 ConvertedType = ToType;
1696 return true;
1697 }
1698
Sebastian Redl576fd422009-05-10 18:38:11 +00001699 // If the left-hand-side is nullptr_t, the right side can be a null
1700 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001701 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001702 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001703 ConvertedType = ToType;
1704 return true;
1705 }
1706
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001707 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001708 if (!ToTypePtr)
1709 return false;
1710
1711 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001712 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001713 ConvertedType = ToType;
1714 return true;
1715 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001716
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001717 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001718 // , including objective-c pointers.
1719 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001720 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1721 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001722 ConvertedType = BuildSimilarlyQualifiedPointerType(
1723 FromType->getAs<ObjCObjectPointerType>(),
1724 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001725 ToType, Context);
1726 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001727 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001728 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001729 if (!FromTypePtr)
1730 return false;
1731
1732 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001733
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001734 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001735 // pointer conversion, so don't do all of the work below.
1736 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1737 return false;
1738
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001739 // An rvalue of type "pointer to cv T," where T is an object type,
1740 // can be converted to an rvalue of type "pointer to cv void" (C++
1741 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001742 if (FromPointeeType->isIncompleteOrObjectType() &&
1743 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001744 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001745 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001746 ToType, Context,
1747 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001748 return true;
1749 }
1750
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001751 // MSVC allows implicit function to void* type conversion.
Francois Pichet0706d202011-09-17 17:15:52 +00001752 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001753 ToPointeeType->isVoidType()) {
1754 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1755 ToPointeeType,
1756 ToType, Context);
1757 return true;
1758 }
1759
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001760 // When we're overloading in C, we allow a special kind of pointer
1761 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001762 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001763 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001764 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001765 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001766 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001767 return true;
1768 }
1769
Douglas Gregor5c407d92008-10-23 00:40:37 +00001770 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001771 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001772 // An rvalue of type "pointer to cv D," where D is a class type,
1773 // can be converted to an rvalue of type "pointer to cv B," where
1774 // B is a base class (clause 10) of D. If B is an inaccessible
1775 // (clause 11) or ambiguous (10.2) base class of D, a program that
1776 // necessitates this conversion is ill-formed. The result of the
1777 // conversion is a pointer to the base class sub-object of the
1778 // derived class object. The null pointer value is converted to
1779 // the null pointer value of the destination type.
1780 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001781 // Note that we do not check for ambiguity or inaccessibility
1782 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001783 if (getLangOptions().CPlusPlus &&
1784 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001785 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001786 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001787 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001788 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001789 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001790 ToType, Context);
1791 return true;
1792 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001793
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001794 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1795 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1796 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1797 ToPointeeType,
1798 ToType, Context);
1799 return true;
1800 }
1801
Douglas Gregora119f102008-12-19 19:13:09 +00001802 return false;
1803}
Douglas Gregoraec25842011-04-26 23:16:46 +00001804
1805/// \brief Adopt the given qualifiers for the given type.
1806static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1807 Qualifiers TQs = T.getQualifiers();
1808
1809 // Check whether qualifiers already match.
1810 if (TQs == Qs)
1811 return T;
1812
1813 if (Qs.compatiblyIncludes(TQs))
1814 return Context.getQualifiedType(T, Qs);
1815
1816 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1817}
Douglas Gregora119f102008-12-19 19:13:09 +00001818
1819/// isObjCPointerConversion - Determines whether this is an
1820/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1821/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001822bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001823 QualType& ConvertedType,
1824 bool &IncompatibleObjC) {
1825 if (!getLangOptions().ObjC1)
1826 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001827
Douglas Gregoraec25842011-04-26 23:16:46 +00001828 // The set of qualifiers on the type we're converting from.
1829 Qualifiers FromQualifiers = FromType.getQualifiers();
1830
Steve Naroff7cae42b2009-07-10 23:34:53 +00001831 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001832 const ObjCObjectPointerType* ToObjCPtr =
1833 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001834 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001835 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001836
Steve Naroff7cae42b2009-07-10 23:34:53 +00001837 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001838 // If the pointee types are the same (ignoring qualifications),
1839 // then this is not a pointer conversion.
1840 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1841 FromObjCPtr->getPointeeType()))
1842 return false;
1843
Douglas Gregoraec25842011-04-26 23:16:46 +00001844 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00001845 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001846 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001847 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001848 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001849 return true;
1850 }
1851 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001852 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001853 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001854 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001855 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001856 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001857 return true;
1858 }
1859 // Objective C++: We're able to convert from a pointer to an
1860 // interface to a pointer to a different interface.
1861 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001862 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1863 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1864 if (getLangOptions().CPlusPlus && LHS && RHS &&
1865 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1866 FromObjCPtr->getPointeeType()))
1867 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001868 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001869 ToObjCPtr->getPointeeType(),
1870 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001871 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001872 return true;
1873 }
1874
1875 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1876 // Okay: this is some kind of implicit downcast of Objective-C
1877 // interfaces, which is permitted. However, we're going to
1878 // complain about it.
1879 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001880 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001881 ToObjCPtr->getPointeeType(),
1882 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001883 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001884 return true;
1885 }
Mike Stump11289f42009-09-09 15:08:12 +00001886 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001887 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001888 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001889 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001890 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001891 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001892 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001893 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001894 // to a block pointer type.
1895 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001896 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001897 return true;
1898 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001899 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001901 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001902 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001903 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001904 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00001905 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001906 return true;
1907 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001908 else
Douglas Gregora119f102008-12-19 19:13:09 +00001909 return false;
1910
Douglas Gregor033f56d2008-12-23 00:53:59 +00001911 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001912 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001913 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001914 else if (const BlockPointerType *FromBlockPtr =
1915 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001916 FromPointeeType = FromBlockPtr->getPointeeType();
1917 else
Douglas Gregora119f102008-12-19 19:13:09 +00001918 return false;
1919
Douglas Gregora119f102008-12-19 19:13:09 +00001920 // If we have pointers to pointers, recursively check whether this
1921 // is an Objective-C conversion.
1922 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1923 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1924 IncompatibleObjC)) {
1925 // We always complain about this conversion.
1926 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001927 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001928 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001929 return true;
1930 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001931 // Allow conversion of pointee being objective-c pointer to another one;
1932 // as in I* to id.
1933 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1934 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1935 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1936 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00001937
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001938 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001939 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001940 return true;
1941 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001942
Douglas Gregor033f56d2008-12-23 00:53:59 +00001943 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001944 // differences in the argument and result types are in Objective-C
1945 // pointer conversions. If so, we permit the conversion (but
1946 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001947 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001948 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001949 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001950 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001951 if (FromFunctionType && ToFunctionType) {
1952 // If the function types are exactly the same, this isn't an
1953 // Objective-C pointer conversion.
1954 if (Context.getCanonicalType(FromPointeeType)
1955 == Context.getCanonicalType(ToPointeeType))
1956 return false;
1957
1958 // Perform the quick checks that will tell us whether these
1959 // function types are obviously different.
1960 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1961 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1962 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1963 return false;
1964
1965 bool HasObjCConversion = false;
1966 if (Context.getCanonicalType(FromFunctionType->getResultType())
1967 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1968 // Okay, the types match exactly. Nothing to do.
1969 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1970 ToFunctionType->getResultType(),
1971 ConvertedType, IncompatibleObjC)) {
1972 // Okay, we have an Objective-C pointer conversion.
1973 HasObjCConversion = true;
1974 } else {
1975 // Function types are too different. Abort.
1976 return false;
1977 }
Mike Stump11289f42009-09-09 15:08:12 +00001978
Douglas Gregora119f102008-12-19 19:13:09 +00001979 // Check argument types.
1980 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1981 ArgIdx != NumArgs; ++ArgIdx) {
1982 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1983 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1984 if (Context.getCanonicalType(FromArgType)
1985 == Context.getCanonicalType(ToArgType)) {
1986 // Okay, the types match exactly. Nothing to do.
1987 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1988 ConvertedType, IncompatibleObjC)) {
1989 // Okay, we have an Objective-C pointer conversion.
1990 HasObjCConversion = true;
1991 } else {
1992 // Argument types are too different. Abort.
1993 return false;
1994 }
1995 }
1996
1997 if (HasObjCConversion) {
1998 // We had an Objective-C conversion. Allow this pointer
1999 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002000 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002001 IncompatibleObjC = true;
2002 return true;
2003 }
2004 }
2005
Sebastian Redl72b597d2009-01-25 19:43:20 +00002006 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002007}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002008
John McCall31168b02011-06-15 23:02:42 +00002009/// \brief Determine whether this is an Objective-C writeback conversion,
2010/// used for parameter passing when performing automatic reference counting.
2011///
2012/// \param FromType The type we're converting form.
2013///
2014/// \param ToType The type we're converting to.
2015///
2016/// \param ConvertedType The type that will be produced after applying
2017/// this conversion.
2018bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2019 QualType &ConvertedType) {
2020 if (!getLangOptions().ObjCAutoRefCount ||
2021 Context.hasSameUnqualifiedType(FromType, ToType))
2022 return false;
2023
2024 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2025 QualType ToPointee;
2026 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2027 ToPointee = ToPointer->getPointeeType();
2028 else
2029 return false;
2030
2031 Qualifiers ToQuals = ToPointee.getQualifiers();
2032 if (!ToPointee->isObjCLifetimeType() ||
2033 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2034 !ToQuals.withoutObjCGLifetime().empty())
2035 return false;
2036
2037 // Argument must be a pointer to __strong to __weak.
2038 QualType FromPointee;
2039 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2040 FromPointee = FromPointer->getPointeeType();
2041 else
2042 return false;
2043
2044 Qualifiers FromQuals = FromPointee.getQualifiers();
2045 if (!FromPointee->isObjCLifetimeType() ||
2046 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2047 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2048 return false;
2049
2050 // Make sure that we have compatible qualifiers.
2051 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2052 if (!ToQuals.compatiblyIncludes(FromQuals))
2053 return false;
2054
2055 // Remove qualifiers from the pointee type we're converting from; they
2056 // aren't used in the compatibility check belong, and we'll be adding back
2057 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2058 FromPointee = FromPointee.getUnqualifiedType();
2059
2060 // The unqualified form of the pointee types must be compatible.
2061 ToPointee = ToPointee.getUnqualifiedType();
2062 bool IncompatibleObjC;
2063 if (Context.typesAreCompatible(FromPointee, ToPointee))
2064 FromPointee = ToPointee;
2065 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2066 IncompatibleObjC))
2067 return false;
2068
2069 /// \brief Construct the type we're converting to, which is a pointer to
2070 /// __autoreleasing pointee.
2071 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2072 ConvertedType = Context.getPointerType(FromPointee);
2073 return true;
2074}
2075
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002076bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2077 QualType& ConvertedType) {
2078 QualType ToPointeeType;
2079 if (const BlockPointerType *ToBlockPtr =
2080 ToType->getAs<BlockPointerType>())
2081 ToPointeeType = ToBlockPtr->getPointeeType();
2082 else
2083 return false;
2084
2085 QualType FromPointeeType;
2086 if (const BlockPointerType *FromBlockPtr =
2087 FromType->getAs<BlockPointerType>())
2088 FromPointeeType = FromBlockPtr->getPointeeType();
2089 else
2090 return false;
2091 // We have pointer to blocks, check whether the only
2092 // differences in the argument and result types are in Objective-C
2093 // pointer conversions. If so, we permit the conversion.
2094
2095 const FunctionProtoType *FromFunctionType
2096 = FromPointeeType->getAs<FunctionProtoType>();
2097 const FunctionProtoType *ToFunctionType
2098 = ToPointeeType->getAs<FunctionProtoType>();
2099
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002100 if (!FromFunctionType || !ToFunctionType)
2101 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002102
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002103 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002104 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002105
2106 // Perform the quick checks that will tell us whether these
2107 // function types are obviously different.
2108 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2109 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2110 return false;
2111
2112 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2113 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2114 if (FromEInfo != ToEInfo)
2115 return false;
2116
2117 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002118 if (Context.hasSameType(FromFunctionType->getResultType(),
2119 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002120 // Okay, the types match exactly. Nothing to do.
2121 } else {
2122 QualType RHS = FromFunctionType->getResultType();
2123 QualType LHS = ToFunctionType->getResultType();
2124 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2125 !RHS.hasQualifiers() && LHS.hasQualifiers())
2126 LHS = LHS.getUnqualifiedType();
2127
2128 if (Context.hasSameType(RHS,LHS)) {
2129 // OK exact match.
2130 } else if (isObjCPointerConversion(RHS, LHS,
2131 ConvertedType, IncompatibleObjC)) {
2132 if (IncompatibleObjC)
2133 return false;
2134 // Okay, we have an Objective-C pointer conversion.
2135 }
2136 else
2137 return false;
2138 }
2139
2140 // Check argument types.
2141 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2142 ArgIdx != NumArgs; ++ArgIdx) {
2143 IncompatibleObjC = false;
2144 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2145 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2146 if (Context.hasSameType(FromArgType, ToArgType)) {
2147 // Okay, the types match exactly. Nothing to do.
2148 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2149 ConvertedType, IncompatibleObjC)) {
2150 if (IncompatibleObjC)
2151 return false;
2152 // Okay, we have an Objective-C pointer conversion.
2153 } else
2154 // Argument types are too different. Abort.
2155 return false;
2156 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002157 if (LangOpts.ObjCAutoRefCount &&
2158 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2159 ToFunctionType))
2160 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002161
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002162 ConvertedType = ToType;
2163 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002164}
2165
Richard Trieucaff2472011-11-23 22:32:32 +00002166enum {
2167 ft_default,
2168 ft_different_class,
2169 ft_parameter_arity,
2170 ft_parameter_mismatch,
2171 ft_return_type,
2172 ft_qualifer_mismatch
2173};
2174
2175/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2176/// function types. Catches different number of parameter, mismatch in
2177/// parameter types, and different return types.
2178void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2179 QualType FromType, QualType ToType) {
2180 // Get the function type from the pointers.
2181 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2182 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2183 *ToMember = ToType->getAs<MemberPointerType>();
2184 if (FromMember->getClass() != ToMember->getClass()) {
2185 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2186 << QualType(FromMember->getClass(), 0);
2187 return;
2188 }
2189 FromType = FromMember->getPointeeType();
2190 ToType = ToMember->getPointeeType();
2191 } else if (FromType->isPointerType() && ToType->isPointerType()) {
2192 FromType = FromType->getPointeeType();
2193 ToType = ToType->getPointeeType();
2194 } else {
2195 PDiag << ft_default;
2196 return;
2197 }
2198
2199 FromType = FromType.getNonReferenceType();
2200 ToType = ToType.getNonReferenceType();
2201
2202 // If either type is not valid, of the types are the same, no extra info.
2203 if (FromType.isNull() || ToType.isNull() ||
2204 Context.hasSameType(FromType, ToType)) {
2205 PDiag << ft_default;
2206 return;
2207 }
2208
2209 // Don't print extra info for non-specialized template functions.
2210 if (FromType->isInstantiationDependentType() &&
2211 !FromType->getAs<TemplateSpecializationType>()) {
2212 PDiag << ft_default;
2213 return;
2214 }
2215
2216 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2217 *ToFunction = ToType->getAs<FunctionProtoType>();
2218
2219 // Both types need to be function types.
2220 if (!FromFunction || !ToFunction) {
2221 PDiag << ft_default;
2222 return;
2223 }
2224
2225 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2226 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2227 << FromFunction->getNumArgs();
2228 return;
2229 }
2230
2231 // Handle different parameter types.
2232 unsigned ArgPos;
2233 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2234 PDiag << ft_parameter_mismatch << ArgPos + 1
2235 << ToFunction->getArgType(ArgPos)
2236 << FromFunction->getArgType(ArgPos);
2237 return;
2238 }
2239
2240 // Handle different return type.
2241 if (!Context.hasSameType(FromFunction->getResultType(),
2242 ToFunction->getResultType())) {
2243 PDiag << ft_return_type << ToFunction->getResultType()
2244 << FromFunction->getResultType();
2245 return;
2246 }
2247
2248 unsigned FromQuals = FromFunction->getTypeQuals(),
2249 ToQuals = ToFunction->getTypeQuals();
2250 if (FromQuals != ToQuals) {
2251 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2252 return;
2253 }
2254
2255 // Unable to find a difference, so add no extra info.
2256 PDiag << ft_default;
2257}
2258
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002259/// FunctionArgTypesAreEqual - This routine checks two function proto types
2260/// for equlity of their argument types. Caller has already checked that
2261/// they have same number of arguments. This routine assumes that Objective-C
2262/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieucaff2472011-11-23 22:32:32 +00002263/// If the parameters are different, ArgPos will have the the parameter index
2264/// of the first different parameter.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002265bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieucaff2472011-11-23 22:32:32 +00002266 const FunctionProtoType *NewType,
2267 unsigned *ArgPos) {
2268 if (!getLangOptions().ObjC1) {
2269 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2270 N = NewType->arg_type_begin(),
2271 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2272 if (!Context.hasSameType(*O, *N)) {
2273 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2274 return false;
2275 }
2276 }
2277 return true;
2278 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002279
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002280 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2281 N = NewType->arg_type_begin(),
2282 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2283 QualType ToType = (*O);
2284 QualType FromType = (*N);
Richard Trieucaff2472011-11-23 22:32:32 +00002285 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002286 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2287 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002288 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2289 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2290 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2291 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002292 continue;
2293 }
John McCall8b07ec22010-05-15 11:32:37 +00002294 else if (const ObjCObjectPointerType *PTTo =
2295 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002296 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002297 FromType->getAs<ObjCObjectPointerType>())
2298 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2299 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002300 }
Richard Trieucaff2472011-11-23 22:32:32 +00002301 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002302 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002303 }
2304 }
2305 return true;
2306}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002307
Douglas Gregor39c16d42008-10-24 04:54:22 +00002308/// CheckPointerConversion - Check the pointer conversion from the
2309/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002310/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002311/// conversions for which IsPointerConversion has already returned
2312/// true. It returns true and produces a diagnostic if there was an
2313/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002314bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002315 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002316 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002317 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002318 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002319 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002320
John McCall8cb679e2010-11-15 09:13:47 +00002321 Kind = CK_BitCast;
2322
Chandler Carruthffab8732011-04-09 07:32:05 +00002323 if (!IsCStyleOrFunctionalCast &&
2324 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2325 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2326 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002327 PDiag(diag::warn_impcast_bool_to_null_pointer)
2328 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002329
John McCall9320b872011-09-09 05:25:32 +00002330 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2331 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002332 QualType FromPointeeType = FromPtrType->getPointeeType(),
2333 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002334
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002335 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2336 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002337 // We must have a derived-to-base conversion. Check an
2338 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002339 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2340 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002341 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002342 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002343 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002344
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002345 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002346 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002347 }
2348 }
John McCall9320b872011-09-09 05:25:32 +00002349 } else if (const ObjCObjectPointerType *ToPtrType =
2350 ToType->getAs<ObjCObjectPointerType>()) {
2351 if (const ObjCObjectPointerType *FromPtrType =
2352 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002353 // Objective-C++ conversions are always okay.
2354 // FIXME: We should have a different class of conversions for the
2355 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002356 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002357 return false;
John McCall9320b872011-09-09 05:25:32 +00002358 } else if (FromType->isBlockPointerType()) {
2359 Kind = CK_BlockPointerToObjCPointerCast;
2360 } else {
2361 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002362 }
John McCall9320b872011-09-09 05:25:32 +00002363 } else if (ToType->isBlockPointerType()) {
2364 if (!FromType->isBlockPointerType())
2365 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002366 }
John McCall8cb679e2010-11-15 09:13:47 +00002367
2368 // We shouldn't fall into this case unless it's valid for other
2369 // reasons.
2370 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2371 Kind = CK_NullToPointer;
2372
Douglas Gregor39c16d42008-10-24 04:54:22 +00002373 return false;
2374}
2375
Sebastian Redl72b597d2009-01-25 19:43:20 +00002376/// IsMemberPointerConversion - Determines whether the conversion of the
2377/// expression From, which has the (possibly adjusted) type FromType, can be
2378/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2379/// If so, returns true and places the converted type (that might differ from
2380/// ToType in its cv-qualifiers at some level) into ConvertedType.
2381bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002382 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002383 bool InOverloadResolution,
2384 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002385 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002386 if (!ToTypePtr)
2387 return false;
2388
2389 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002390 if (From->isNullPointerConstant(Context,
2391 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2392 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002393 ConvertedType = ToType;
2394 return true;
2395 }
2396
2397 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002398 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002399 if (!FromTypePtr)
2400 return false;
2401
2402 // A pointer to member of B can be converted to a pointer to member of D,
2403 // where D is derived from B (C++ 4.11p2).
2404 QualType FromClass(FromTypePtr->getClass(), 0);
2405 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002406
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002407 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2408 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2409 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002410 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2411 ToClass.getTypePtr());
2412 return true;
2413 }
2414
2415 return false;
2416}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002417
Sebastian Redl72b597d2009-01-25 19:43:20 +00002418/// CheckMemberPointerConversion - Check the member pointer conversion from the
2419/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002420/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002421/// for which IsMemberPointerConversion has already returned true. It returns
2422/// true and produces a diagnostic if there was an error, or returns false
2423/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002424bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002425 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002426 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002427 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002428 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002429 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002430 if (!FromPtrType) {
2431 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002432 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002433 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002434 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002435 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002436 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002437 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002438
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002439 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002440 assert(ToPtrType && "No member pointer cast has a target type "
2441 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002442
Sebastian Redled8f2002009-01-28 18:33:18 +00002443 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2444 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002445
Sebastian Redled8f2002009-01-28 18:33:18 +00002446 // FIXME: What about dependent types?
2447 assert(FromClass->isRecordType() && "Pointer into non-class.");
2448 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002449
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002450 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002451 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002452 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2453 assert(DerivationOkay &&
2454 "Should not have been called if derivation isn't OK.");
2455 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002456
Sebastian Redled8f2002009-01-28 18:33:18 +00002457 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2458 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002459 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2460 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2461 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2462 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002463 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002464
Douglas Gregor89ee6822009-02-28 01:32:25 +00002465 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002466 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2467 << FromClass << ToClass << QualType(VBase, 0)
2468 << From->getSourceRange();
2469 return true;
2470 }
2471
John McCall5b0829a2010-02-10 09:31:12 +00002472 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002473 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2474 Paths.front(),
2475 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002476
Anders Carlssond7923c62009-08-22 23:33:40 +00002477 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002478 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002479 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002480 return false;
2481}
2482
Douglas Gregor9a657932008-10-21 23:43:52 +00002483/// IsQualificationConversion - Determines whether the conversion from
2484/// an rvalue of type FromType to ToType is a qualification conversion
2485/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002486///
2487/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2488/// when the qualification conversion involves a change in the Objective-C
2489/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002490bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002491Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002492 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002493 FromType = Context.getCanonicalType(FromType);
2494 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002495 ObjCLifetimeConversion = false;
2496
Douglas Gregor9a657932008-10-21 23:43:52 +00002497 // If FromType and ToType are the same type, this is not a
2498 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002499 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002500 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002501
Douglas Gregor9a657932008-10-21 23:43:52 +00002502 // (C++ 4.4p4):
2503 // A conversion can add cv-qualifiers at levels other than the first
2504 // in multi-level pointers, subject to the following rules: [...]
2505 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002506 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002507 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002508 // Within each iteration of the loop, we check the qualifiers to
2509 // determine if this still looks like a qualification
2510 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002511 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002512 // until there are no more pointers or pointers-to-members left to
2513 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002514 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002515
Douglas Gregor90609aa2011-04-25 18:40:17 +00002516 Qualifiers FromQuals = FromType.getQualifiers();
2517 Qualifiers ToQuals = ToType.getQualifiers();
2518
John McCall31168b02011-06-15 23:02:42 +00002519 // Objective-C ARC:
2520 // Check Objective-C lifetime conversions.
2521 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2522 UnwrappedAnyPointer) {
2523 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2524 ObjCLifetimeConversion = true;
2525 FromQuals.removeObjCLifetime();
2526 ToQuals.removeObjCLifetime();
2527 } else {
2528 // Qualification conversions cannot cast between different
2529 // Objective-C lifetime qualifiers.
2530 return false;
2531 }
2532 }
2533
Douglas Gregorf30053d2011-05-08 06:09:53 +00002534 // Allow addition/removal of GC attributes but not changing GC attributes.
2535 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2536 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2537 FromQuals.removeObjCGCAttr();
2538 ToQuals.removeObjCGCAttr();
2539 }
2540
Douglas Gregor9a657932008-10-21 23:43:52 +00002541 // -- for every j > 0, if const is in cv 1,j then const is in cv
2542 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002543 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002544 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002545
Douglas Gregor9a657932008-10-21 23:43:52 +00002546 // -- if the cv 1,j and cv 2,j are different, then const is in
2547 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002548 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002549 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002550 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002551
Douglas Gregor9a657932008-10-21 23:43:52 +00002552 // Keep track of whether all prior cv-qualifiers in the "to" type
2553 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002554 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002555 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002556 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002557
2558 // We are left with FromType and ToType being the pointee types
2559 // after unwrapping the original FromType and ToType the same number
2560 // of types. If we unwrapped any pointers, and if FromType and
2561 // ToType have the same unqualified type (since we checked
2562 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002563 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002564}
2565
Douglas Gregor576e98c2009-01-30 23:27:23 +00002566/// Determines whether there is a user-defined conversion sequence
2567/// (C++ [over.ics.user]) that converts expression From to the type
2568/// ToType. If such a conversion exists, User will contain the
2569/// user-defined conversion sequence that performs such a conversion
2570/// and this routine will return true. Otherwise, this routine returns
2571/// false and User is unspecified.
2572///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002573/// \param AllowExplicit true if the conversion should consider C++0x
2574/// "explicit" conversion functions as well as non-explicit conversion
2575/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002576static OverloadingResult
2577IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2578 UserDefinedConversionSequence& User,
2579 OverloadCandidateSet& CandidateSet,
2580 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002581 // Whether we will only visit constructors.
2582 bool ConstructorsOnly = false;
2583
2584 // If the type we are conversion to is a class type, enumerate its
2585 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002586 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002587 // C++ [over.match.ctor]p1:
2588 // When objects of class type are direct-initialized (8.5), or
2589 // copy-initialized from an expression of the same or a
2590 // derived class type (8.5), overload resolution selects the
2591 // constructor. [...] For copy-initialization, the candidate
2592 // functions are all the converting constructors (12.3.1) of
2593 // that class. The argument list is the expression-list within
2594 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002595 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002596 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002597 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002598 ConstructorsOnly = true;
2599
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002600 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2601 // RequireCompleteType may have returned true due to some invalid decl
2602 // during template instantiation, but ToType may be complete enough now
2603 // to try to recover.
2604 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002605 // We're not going to find any constructors.
2606 } else if (CXXRecordDecl *ToRecordDecl
2607 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002608 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002609 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002610 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002611 NamedDecl *D = *Con;
2612 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2613
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002614 // Find the constructor (which may be a template).
2615 CXXConstructorDecl *Constructor = 0;
2616 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002617 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002618 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002619 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002620 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2621 else
John McCalla0296f72010-03-19 07:35:19 +00002622 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002623
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002624 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002625 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002626 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002627 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2628 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002629 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002630 /*SuppressUserConversions=*/
2631 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002632 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002633 // Allow one user-defined conversion when user specifies a
2634 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002635 S.AddOverloadCandidate(Constructor, FoundDecl,
2636 &From, 1, CandidateSet,
2637 /*SuppressUserConversions=*/
2638 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002639 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002640 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002641 }
2642 }
2643
Douglas Gregor5ab11652010-04-17 22:01:05 +00002644 // Enumerate conversion functions, if we're allowed to.
2645 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002646 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2647 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002648 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002649 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002650 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002651 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002652 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2653 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002654 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002655 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002656 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002657 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002658 DeclAccessPair FoundDecl = I.getPair();
2659 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002660 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2661 if (isa<UsingShadowDecl>(D))
2662 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2663
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002664 CXXConversionDecl *Conv;
2665 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002666 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2667 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002668 else
John McCallda4458e2010-03-31 01:36:47 +00002669 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002670
2671 if (AllowExplicit || !Conv->isExplicit()) {
2672 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002673 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2674 ActingContext, From, ToType,
2675 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002676 else
John McCall5c32be02010-08-24 20:38:10 +00002677 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2678 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002679 }
2680 }
2681 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002682 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002683
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002684 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2685
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002686 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002687 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002688 case OR_Success:
2689 // Record the standard conversion we used and the conversion function.
2690 if (CXXConstructorDecl *Constructor
2691 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002692 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2693
John McCall5c32be02010-08-24 20:38:10 +00002694 // C++ [over.ics.user]p1:
2695 // If the user-defined conversion is specified by a
2696 // constructor (12.3.1), the initial standard conversion
2697 // sequence converts the source type to the type required by
2698 // the argument of the constructor.
2699 //
2700 QualType ThisType = Constructor->getThisType(S.Context);
2701 if (Best->Conversions[0].isEllipsis())
2702 User.EllipsisConversion = true;
2703 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002704 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002705 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002706 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002707 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002708 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00002709 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002710 User.After.setAsIdentityConversion();
2711 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2712 User.After.setAllToTypes(ToType);
2713 return OR_Success;
2714 } else if (CXXConversionDecl *Conversion
2715 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002716 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2717
John McCall5c32be02010-08-24 20:38:10 +00002718 // C++ [over.ics.user]p1:
2719 //
2720 // [...] If the user-defined conversion is specified by a
2721 // conversion function (12.3.2), the initial standard
2722 // conversion sequence converts the source type to the
2723 // implicit object parameter of the conversion function.
2724 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002725 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002726 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00002727 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002728 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002729
John McCall5c32be02010-08-24 20:38:10 +00002730 // C++ [over.ics.user]p2:
2731 // The second standard conversion sequence converts the
2732 // result of the user-defined conversion to the target type
2733 // for the sequence. Since an implicit conversion sequence
2734 // is an initialization, the special rules for
2735 // initialization by user-defined conversion apply when
2736 // selecting the best user-defined conversion for a
2737 // user-defined conversion sequence (see 13.3.3 and
2738 // 13.3.3.1).
2739 User.After = Best->FinalConversion;
2740 return OR_Success;
2741 } else {
2742 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002743 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002744 }
2745
John McCall5c32be02010-08-24 20:38:10 +00002746 case OR_No_Viable_Function:
2747 return OR_No_Viable_Function;
2748 case OR_Deleted:
2749 // No conversion here! We're done.
2750 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002751
John McCall5c32be02010-08-24 20:38:10 +00002752 case OR_Ambiguous:
2753 return OR_Ambiguous;
2754 }
2755
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002756 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002757}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002758
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002759bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002760Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002761 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002762 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002763 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002764 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002765 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002766 if (OvResult == OR_Ambiguous)
2767 Diag(From->getSourceRange().getBegin(),
2768 diag::err_typecheck_ambiguous_condition)
2769 << From->getType() << ToType << From->getSourceRange();
2770 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2771 Diag(From->getSourceRange().getBegin(),
2772 diag::err_typecheck_nonviable_condition)
2773 << From->getType() << ToType << From->getSourceRange();
2774 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002775 return false;
John McCall5c32be02010-08-24 20:38:10 +00002776 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002777 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002778}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002779
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002780/// CompareImplicitConversionSequences - Compare two implicit
2781/// conversion sequences to determine whether one is better than the
2782/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002783static ImplicitConversionSequence::CompareKind
2784CompareImplicitConversionSequences(Sema &S,
2785 const ImplicitConversionSequence& ICS1,
2786 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002787{
2788 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2789 // conversion sequences (as defined in 13.3.3.1)
2790 // -- a standard conversion sequence (13.3.3.1.1) is a better
2791 // conversion sequence than a user-defined conversion sequence or
2792 // an ellipsis conversion sequence, and
2793 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2794 // conversion sequence than an ellipsis conversion sequence
2795 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002796 //
John McCall0d1da222010-01-12 00:44:57 +00002797 // C++0x [over.best.ics]p10:
2798 // For the purpose of ranking implicit conversion sequences as
2799 // described in 13.3.3.2, the ambiguous conversion sequence is
2800 // treated as a user-defined sequence that is indistinguishable
2801 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002802 if (ICS1.getKindRank() < ICS2.getKindRank())
2803 return ImplicitConversionSequence::Better;
2804 else if (ICS2.getKindRank() < ICS1.getKindRank())
2805 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002806
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002807 // The following checks require both conversion sequences to be of
2808 // the same kind.
2809 if (ICS1.getKind() != ICS2.getKind())
2810 return ImplicitConversionSequence::Indistinguishable;
2811
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002812 ImplicitConversionSequence::CompareKind Result =
2813 ImplicitConversionSequence::Indistinguishable;
2814
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002815 // Two implicit conversion sequences of the same form are
2816 // indistinguishable conversion sequences unless one of the
2817 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002818 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002819 Result = CompareStandardConversionSequences(S,
2820 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002821 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002822 // User-defined conversion sequence U1 is a better conversion
2823 // sequence than another user-defined conversion sequence U2 if
2824 // they contain the same user-defined conversion function or
2825 // constructor and if the second standard conversion sequence of
2826 // U1 is better than the second standard conversion sequence of
2827 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002828 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002829 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002830 Result = CompareStandardConversionSequences(S,
2831 ICS1.UserDefined.After,
2832 ICS2.UserDefined.After);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002833 }
2834
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002835 // List-initialization sequence L1 is a better conversion sequence than
2836 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
2837 // for some X and L2 does not.
2838 if (Result == ImplicitConversionSequence::Indistinguishable &&
2839 ICS1.isListInitializationSequence() &&
2840 ICS2.isListInitializationSequence()) {
2841 // FIXME: Find out if ICS1 converts to initializer_list and ICS2 doesn't.
2842 }
2843
2844 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002845}
2846
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002847static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2848 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2849 Qualifiers Quals;
2850 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002851 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002852 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002853
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002854 return Context.hasSameUnqualifiedType(T1, T2);
2855}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002856
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002857// Per 13.3.3.2p3, compare the given standard conversion sequences to
2858// determine if one is a proper subset of the other.
2859static ImplicitConversionSequence::CompareKind
2860compareStandardConversionSubsets(ASTContext &Context,
2861 const StandardConversionSequence& SCS1,
2862 const StandardConversionSequence& SCS2) {
2863 ImplicitConversionSequence::CompareKind Result
2864 = ImplicitConversionSequence::Indistinguishable;
2865
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002866 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002867 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00002868 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2869 return ImplicitConversionSequence::Better;
2870 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2871 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002872
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002873 if (SCS1.Second != SCS2.Second) {
2874 if (SCS1.Second == ICK_Identity)
2875 Result = ImplicitConversionSequence::Better;
2876 else if (SCS2.Second == ICK_Identity)
2877 Result = ImplicitConversionSequence::Worse;
2878 else
2879 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002880 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002881 return ImplicitConversionSequence::Indistinguishable;
2882
2883 if (SCS1.Third == SCS2.Third) {
2884 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2885 : ImplicitConversionSequence::Indistinguishable;
2886 }
2887
2888 if (SCS1.Third == ICK_Identity)
2889 return Result == ImplicitConversionSequence::Worse
2890 ? ImplicitConversionSequence::Indistinguishable
2891 : ImplicitConversionSequence::Better;
2892
2893 if (SCS2.Third == ICK_Identity)
2894 return Result == ImplicitConversionSequence::Better
2895 ? ImplicitConversionSequence::Indistinguishable
2896 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002897
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002898 return ImplicitConversionSequence::Indistinguishable;
2899}
2900
Douglas Gregore696ebb2011-01-26 14:52:12 +00002901/// \brief Determine whether one of the given reference bindings is better
2902/// than the other based on what kind of bindings they are.
2903static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2904 const StandardConversionSequence &SCS2) {
2905 // C++0x [over.ics.rank]p3b4:
2906 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2907 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002908 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002909 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002910 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002911 // reference*.
2912 //
2913 // FIXME: Rvalue references. We're going rogue with the above edits,
2914 // because the semantics in the current C++0x working paper (N3225 at the
2915 // time of this writing) break the standard definition of std::forward
2916 // and std::reference_wrapper when dealing with references to functions.
2917 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002918 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2919 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2920 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002921
Douglas Gregore696ebb2011-01-26 14:52:12 +00002922 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2923 SCS2.IsLvalueReference) ||
2924 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2925 !SCS2.IsLvalueReference);
2926}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002927
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002928/// CompareStandardConversionSequences - Compare two standard
2929/// conversion sequences to determine whether one is better than the
2930/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002931static ImplicitConversionSequence::CompareKind
2932CompareStandardConversionSequences(Sema &S,
2933 const StandardConversionSequence& SCS1,
2934 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002935{
2936 // Standard conversion sequence S1 is a better conversion sequence
2937 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2938
2939 // -- S1 is a proper subsequence of S2 (comparing the conversion
2940 // sequences in the canonical form defined by 13.3.3.1.1,
2941 // excluding any Lvalue Transformation; the identity conversion
2942 // sequence is considered to be a subsequence of any
2943 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002944 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002945 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002946 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002947
2948 // -- the rank of S1 is better than the rank of S2 (by the rules
2949 // defined below), or, if not that,
2950 ImplicitConversionRank Rank1 = SCS1.getRank();
2951 ImplicitConversionRank Rank2 = SCS2.getRank();
2952 if (Rank1 < Rank2)
2953 return ImplicitConversionSequence::Better;
2954 else if (Rank2 < Rank1)
2955 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002956
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002957 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2958 // are indistinguishable unless one of the following rules
2959 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002960
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002961 // A conversion that is not a conversion of a pointer, or
2962 // pointer to member, to bool is better than another conversion
2963 // that is such a conversion.
2964 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2965 return SCS2.isPointerConversionToBool()
2966 ? ImplicitConversionSequence::Better
2967 : ImplicitConversionSequence::Worse;
2968
Douglas Gregor5c407d92008-10-23 00:40:37 +00002969 // C++ [over.ics.rank]p4b2:
2970 //
2971 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002972 // conversion of B* to A* is better than conversion of B* to
2973 // void*, and conversion of A* to void* is better than conversion
2974 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002975 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002976 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002977 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002978 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002979 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2980 // Exactly one of the conversion sequences is a conversion to
2981 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002982 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2983 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002984 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2985 // Neither conversion sequence converts to a void pointer; compare
2986 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002987 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002988 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002989 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002990 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2991 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002992 // Both conversion sequences are conversions to void
2993 // pointers. Compare the source types to determine if there's an
2994 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002995 QualType FromType1 = SCS1.getFromType();
2996 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002997
2998 // Adjust the types we're converting from via the array-to-pointer
2999 // conversion, if we need to.
3000 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003001 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003002 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003003 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003004
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003005 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3006 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003007
John McCall5c32be02010-08-24 20:38:10 +00003008 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003009 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003010 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003011 return ImplicitConversionSequence::Worse;
3012
3013 // Objective-C++: If one interface is more specific than the
3014 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00003015 const ObjCObjectPointerType* FromObjCPtr1
3016 = FromType1->getAs<ObjCObjectPointerType>();
3017 const ObjCObjectPointerType* FromObjCPtr2
3018 = FromType2->getAs<ObjCObjectPointerType>();
3019 if (FromObjCPtr1 && FromObjCPtr2) {
3020 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3021 FromObjCPtr2);
3022 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3023 FromObjCPtr1);
3024 if (AssignLeft != AssignRight) {
3025 return AssignLeft? ImplicitConversionSequence::Better
3026 : ImplicitConversionSequence::Worse;
3027 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00003028 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003029 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003030
3031 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3032 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00003033 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00003034 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003035 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003036
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003037 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00003038 // Check for a better reference binding based on the kind of bindings.
3039 if (isBetterReferenceBindingKind(SCS1, SCS2))
3040 return ImplicitConversionSequence::Better;
3041 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3042 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003043
Sebastian Redlb28b4072009-03-22 23:49:27 +00003044 // C++ [over.ics.rank]p3b4:
3045 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3046 // which the references refer are the same type except for
3047 // top-level cv-qualifiers, and the type to which the reference
3048 // initialized by S2 refers is more cv-qualified than the type
3049 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003050 QualType T1 = SCS1.getToType(2);
3051 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003052 T1 = S.Context.getCanonicalType(T1);
3053 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003054 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003055 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3056 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003057 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00003058 // Objective-C++ ARC: If the references refer to objects with different
3059 // lifetimes, prefer bindings that don't change lifetime.
3060 if (SCS1.ObjCLifetimeConversionBinding !=
3061 SCS2.ObjCLifetimeConversionBinding) {
3062 return SCS1.ObjCLifetimeConversionBinding
3063 ? ImplicitConversionSequence::Worse
3064 : ImplicitConversionSequence::Better;
3065 }
3066
Chandler Carruth8e543b32010-12-12 08:17:55 +00003067 // If the type is an array type, promote the element qualifiers to the
3068 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003069 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003070 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003071 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003072 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003073 if (T2.isMoreQualifiedThan(T1))
3074 return ImplicitConversionSequence::Better;
3075 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00003076 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003077 }
3078 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003079
Francois Pichet08d2fa02011-09-18 21:37:37 +00003080 // In Microsoft mode, prefer an integral conversion to a
3081 // floating-to-integral conversion if the integral conversion
3082 // is between types of the same size.
3083 // For example:
3084 // void f(float);
3085 // void f(int);
3086 // int main {
3087 // long a;
3088 // f(a);
3089 // }
3090 // Here, MSVC will call f(int) instead of generating a compile error
3091 // as clang will do in standard mode.
3092 if (S.getLangOptions().MicrosoftMode &&
3093 SCS1.Second == ICK_Integral_Conversion &&
3094 SCS2.Second == ICK_Floating_Integral &&
3095 S.Context.getTypeSize(SCS1.getFromType()) ==
3096 S.Context.getTypeSize(SCS1.getToType(2)))
3097 return ImplicitConversionSequence::Better;
3098
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003099 return ImplicitConversionSequence::Indistinguishable;
3100}
3101
3102/// CompareQualificationConversions - Compares two standard conversion
3103/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00003104/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3105ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003106CompareQualificationConversions(Sema &S,
3107 const StandardConversionSequence& SCS1,
3108 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003109 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003110 // -- S1 and S2 differ only in their qualification conversion and
3111 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3112 // cv-qualification signature of type T1 is a proper subset of
3113 // the cv-qualification signature of type T2, and S1 is not the
3114 // deprecated string literal array-to-pointer conversion (4.2).
3115 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3116 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3117 return ImplicitConversionSequence::Indistinguishable;
3118
3119 // FIXME: the example in the standard doesn't use a qualification
3120 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003121 QualType T1 = SCS1.getToType(2);
3122 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003123 T1 = S.Context.getCanonicalType(T1);
3124 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003125 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003126 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3127 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003128
3129 // If the types are the same, we won't learn anything by unwrapped
3130 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003131 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003132 return ImplicitConversionSequence::Indistinguishable;
3133
Chandler Carruth607f38e2009-12-29 07:16:59 +00003134 // If the type is an array type, promote the element qualifiers to the type
3135 // for comparison.
3136 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003137 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003138 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003139 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003140
Mike Stump11289f42009-09-09 15:08:12 +00003141 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003142 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003143
3144 // Objective-C++ ARC:
3145 // Prefer qualification conversions not involving a change in lifetime
3146 // to qualification conversions that do not change lifetime.
3147 if (SCS1.QualificationIncludesObjCLifetime !=
3148 SCS2.QualificationIncludesObjCLifetime) {
3149 Result = SCS1.QualificationIncludesObjCLifetime
3150 ? ImplicitConversionSequence::Worse
3151 : ImplicitConversionSequence::Better;
3152 }
3153
John McCall5c32be02010-08-24 20:38:10 +00003154 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003155 // Within each iteration of the loop, we check the qualifiers to
3156 // determine if this still looks like a qualification
3157 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003158 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003159 // until there are no more pointers or pointers-to-members left
3160 // to unwrap. This essentially mimics what
3161 // IsQualificationConversion does, but here we're checking for a
3162 // strict subset of qualifiers.
3163 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3164 // The qualifiers are the same, so this doesn't tell us anything
3165 // about how the sequences rank.
3166 ;
3167 else if (T2.isMoreQualifiedThan(T1)) {
3168 // T1 has fewer qualifiers, so it could be the better sequence.
3169 if (Result == ImplicitConversionSequence::Worse)
3170 // Neither has qualifiers that are a subset of the other's
3171 // qualifiers.
3172 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003173
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003174 Result = ImplicitConversionSequence::Better;
3175 } else if (T1.isMoreQualifiedThan(T2)) {
3176 // T2 has fewer qualifiers, so it could be the better sequence.
3177 if (Result == ImplicitConversionSequence::Better)
3178 // Neither has qualifiers that are a subset of the other's
3179 // qualifiers.
3180 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003181
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003182 Result = ImplicitConversionSequence::Worse;
3183 } else {
3184 // Qualifiers are disjoint.
3185 return ImplicitConversionSequence::Indistinguishable;
3186 }
3187
3188 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003189 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003190 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003191 }
3192
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003193 // Check that the winning standard conversion sequence isn't using
3194 // the deprecated string literal array to pointer conversion.
3195 switch (Result) {
3196 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003197 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003198 Result = ImplicitConversionSequence::Indistinguishable;
3199 break;
3200
3201 case ImplicitConversionSequence::Indistinguishable:
3202 break;
3203
3204 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003205 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003206 Result = ImplicitConversionSequence::Indistinguishable;
3207 break;
3208 }
3209
3210 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003211}
3212
Douglas Gregor5c407d92008-10-23 00:40:37 +00003213/// CompareDerivedToBaseConversions - Compares two standard conversion
3214/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003215/// various kinds of derived-to-base conversions (C++
3216/// [over.ics.rank]p4b3). As part of these checks, we also look at
3217/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003218ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003219CompareDerivedToBaseConversions(Sema &S,
3220 const StandardConversionSequence& SCS1,
3221 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003222 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003223 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003224 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003225 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003226
3227 // Adjust the types we're converting from via the array-to-pointer
3228 // conversion, if we need to.
3229 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003230 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003231 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003232 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003233
3234 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003235 FromType1 = S.Context.getCanonicalType(FromType1);
3236 ToType1 = S.Context.getCanonicalType(ToType1);
3237 FromType2 = S.Context.getCanonicalType(FromType2);
3238 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003239
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003240 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003241 //
3242 // If class B is derived directly or indirectly from class A and
3243 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003244 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003245 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003246 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003247 SCS2.Second == ICK_Pointer_Conversion &&
3248 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3249 FromType1->isPointerType() && FromType2->isPointerType() &&
3250 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003251 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003252 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003253 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003254 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003255 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003256 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003257 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003258 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003259
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003260 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003261 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003262 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003263 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003264 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003265 return ImplicitConversionSequence::Worse;
3266 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003267
3268 // -- conversion of B* to A* is better than conversion of C* to A*,
3269 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003270 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003271 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003272 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003273 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003274 }
3275 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3276 SCS2.Second == ICK_Pointer_Conversion) {
3277 const ObjCObjectPointerType *FromPtr1
3278 = FromType1->getAs<ObjCObjectPointerType>();
3279 const ObjCObjectPointerType *FromPtr2
3280 = FromType2->getAs<ObjCObjectPointerType>();
3281 const ObjCObjectPointerType *ToPtr1
3282 = ToType1->getAs<ObjCObjectPointerType>();
3283 const ObjCObjectPointerType *ToPtr2
3284 = ToType2->getAs<ObjCObjectPointerType>();
3285
3286 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3287 // Apply the same conversion ranking rules for Objective-C pointer types
3288 // that we do for C++ pointers to class types. However, we employ the
3289 // Objective-C pseudo-subtyping relationship used for assignment of
3290 // Objective-C pointer types.
3291 bool FromAssignLeft
3292 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3293 bool FromAssignRight
3294 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3295 bool ToAssignLeft
3296 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3297 bool ToAssignRight
3298 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3299
3300 // A conversion to an a non-id object pointer type or qualified 'id'
3301 // type is better than a conversion to 'id'.
3302 if (ToPtr1->isObjCIdType() &&
3303 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3304 return ImplicitConversionSequence::Worse;
3305 if (ToPtr2->isObjCIdType() &&
3306 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3307 return ImplicitConversionSequence::Better;
3308
3309 // A conversion to a non-id object pointer type is better than a
3310 // conversion to a qualified 'id' type
3311 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3312 return ImplicitConversionSequence::Worse;
3313 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3314 return ImplicitConversionSequence::Better;
3315
3316 // A conversion to an a non-Class object pointer type or qualified 'Class'
3317 // type is better than a conversion to 'Class'.
3318 if (ToPtr1->isObjCClassType() &&
3319 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3320 return ImplicitConversionSequence::Worse;
3321 if (ToPtr2->isObjCClassType() &&
3322 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3323 return ImplicitConversionSequence::Better;
3324
3325 // A conversion to a non-Class object pointer type is better than a
3326 // conversion to a qualified 'Class' type.
3327 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3328 return ImplicitConversionSequence::Worse;
3329 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3330 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003331
Douglas Gregor058d3de2011-01-31 18:51:41 +00003332 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3333 if (S.Context.hasSameType(FromType1, FromType2) &&
3334 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3335 (ToAssignLeft != ToAssignRight))
3336 return ToAssignLeft? ImplicitConversionSequence::Worse
3337 : ImplicitConversionSequence::Better;
3338
3339 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3340 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3341 (FromAssignLeft != FromAssignRight))
3342 return FromAssignLeft? ImplicitConversionSequence::Better
3343 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003344 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003345 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003346
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003347 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003348 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3349 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3350 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003351 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003352 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003353 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003354 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003355 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003356 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003357 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003358 ToType2->getAs<MemberPointerType>();
3359 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3360 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3361 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3362 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3363 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3364 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3365 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3366 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003367 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003368 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003369 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003370 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003371 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003372 return ImplicitConversionSequence::Better;
3373 }
3374 // conversion of B::* to C::* is better than conversion of A::* to C::*
3375 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003376 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003377 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003378 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003379 return ImplicitConversionSequence::Worse;
3380 }
3381 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003382
Douglas Gregor5ab11652010-04-17 22:01:05 +00003383 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003384 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003385 // -- binding of an expression of type C to a reference of type
3386 // B& is better than binding an expression of type C to a
3387 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003388 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3389 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3390 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003391 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003392 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003393 return ImplicitConversionSequence::Worse;
3394 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003395
Douglas Gregor2fe98832008-11-03 19:09:14 +00003396 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003397 // -- binding of an expression of type B to a reference of type
3398 // A& is better than binding an expression of type C to a
3399 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003400 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3401 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3402 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003403 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003404 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003405 return ImplicitConversionSequence::Worse;
3406 }
3407 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003408
Douglas Gregor5c407d92008-10-23 00:40:37 +00003409 return ImplicitConversionSequence::Indistinguishable;
3410}
3411
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003412/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3413/// determine whether they are reference-related,
3414/// reference-compatible, reference-compatible with added
3415/// qualification, or incompatible, for use in C++ initialization by
3416/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3417/// type, and the first type (T1) is the pointee type of the reference
3418/// type being initialized.
3419Sema::ReferenceCompareResult
3420Sema::CompareReferenceRelationship(SourceLocation Loc,
3421 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003422 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003423 bool &ObjCConversion,
3424 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003425 assert(!OrigT1->isReferenceType() &&
3426 "T1 must be the pointee type of the reference type");
3427 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3428
3429 QualType T1 = Context.getCanonicalType(OrigT1);
3430 QualType T2 = Context.getCanonicalType(OrigT2);
3431 Qualifiers T1Quals, T2Quals;
3432 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3433 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3434
3435 // C++ [dcl.init.ref]p4:
3436 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3437 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3438 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003439 DerivedToBase = false;
3440 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003441 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003442 if (UnqualT1 == UnqualT2) {
3443 // Nothing to do.
3444 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003445 IsDerivedFrom(UnqualT2, UnqualT1))
3446 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003447 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3448 UnqualT2->isObjCObjectOrInterfaceType() &&
3449 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3450 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003451 else
3452 return Ref_Incompatible;
3453
3454 // At this point, we know that T1 and T2 are reference-related (at
3455 // least).
3456
3457 // If the type is an array type, promote the element qualifiers to the type
3458 // for comparison.
3459 if (isa<ArrayType>(T1) && T1Quals)
3460 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3461 if (isa<ArrayType>(T2) && T2Quals)
3462 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3463
3464 // C++ [dcl.init.ref]p4:
3465 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3466 // reference-related to T2 and cv1 is the same cv-qualification
3467 // as, or greater cv-qualification than, cv2. For purposes of
3468 // overload resolution, cases for which cv1 is greater
3469 // cv-qualification than cv2 are identified as
3470 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003471 //
3472 // Note that we also require equivalence of Objective-C GC and address-space
3473 // qualifiers when performing these computations, so that e.g., an int in
3474 // address space 1 is not reference-compatible with an int in address
3475 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003476 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3477 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3478 T1Quals.removeObjCLifetime();
3479 T2Quals.removeObjCLifetime();
3480 ObjCLifetimeConversion = true;
3481 }
3482
Douglas Gregord517d552011-04-28 17:56:11 +00003483 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003484 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003485 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003486 return Ref_Compatible_With_Added_Qualification;
3487 else
3488 return Ref_Related;
3489}
3490
Douglas Gregor836a7e82010-08-11 02:15:33 +00003491/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003492/// with DeclType. Return true if something definite is found.
3493static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003494FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3495 QualType DeclType, SourceLocation DeclLoc,
3496 Expr *Init, QualType T2, bool AllowRvalues,
3497 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003498 assert(T2->isRecordType() && "Can only find conversions of record types.");
3499 CXXRecordDecl *T2RecordDecl
3500 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3501
3502 OverloadCandidateSet CandidateSet(DeclLoc);
3503 const UnresolvedSetImpl *Conversions
3504 = T2RecordDecl->getVisibleConversionFunctions();
3505 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3506 E = Conversions->end(); I != E; ++I) {
3507 NamedDecl *D = *I;
3508 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3509 if (isa<UsingShadowDecl>(D))
3510 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3511
3512 FunctionTemplateDecl *ConvTemplate
3513 = dyn_cast<FunctionTemplateDecl>(D);
3514 CXXConversionDecl *Conv;
3515 if (ConvTemplate)
3516 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3517 else
3518 Conv = cast<CXXConversionDecl>(D);
3519
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003520 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003521 // explicit conversions, skip it.
3522 if (!AllowExplicit && Conv->isExplicit())
3523 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003524
Douglas Gregor836a7e82010-08-11 02:15:33 +00003525 if (AllowRvalues) {
3526 bool DerivedToBase = false;
3527 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003528 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003529
3530 // If we are initializing an rvalue reference, don't permit conversion
3531 // functions that return lvalues.
3532 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3533 const ReferenceType *RefType
3534 = Conv->getConversionType()->getAs<LValueReferenceType>();
3535 if (RefType && !RefType->getPointeeType()->isFunctionType())
3536 continue;
3537 }
3538
Douglas Gregor836a7e82010-08-11 02:15:33 +00003539 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003540 S.CompareReferenceRelationship(
3541 DeclLoc,
3542 Conv->getConversionType().getNonReferenceType()
3543 .getUnqualifiedType(),
3544 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003545 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003546 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003547 continue;
3548 } else {
3549 // If the conversion function doesn't return a reference type,
3550 // it can't be considered for this conversion. An rvalue reference
3551 // is only acceptable if its referencee is a function type.
3552
3553 const ReferenceType *RefType =
3554 Conv->getConversionType()->getAs<ReferenceType>();
3555 if (!RefType ||
3556 (!RefType->isLValueReferenceType() &&
3557 !RefType->getPointeeType()->isFunctionType()))
3558 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003559 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003560
Douglas Gregor836a7e82010-08-11 02:15:33 +00003561 if (ConvTemplate)
3562 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003563 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003564 else
3565 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003566 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003567 }
3568
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003569 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3570
Sebastian Redld92badf2010-06-30 18:13:39 +00003571 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003572 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003573 case OR_Success:
3574 // C++ [over.ics.ref]p1:
3575 //
3576 // [...] If the parameter binds directly to the result of
3577 // applying a conversion function to the argument
3578 // expression, the implicit conversion sequence is a
3579 // user-defined conversion sequence (13.3.3.1.2), with the
3580 // second standard conversion sequence either an identity
3581 // conversion or, if the conversion function returns an
3582 // entity of a type that is a derived class of the parameter
3583 // type, a derived-to-base Conversion.
3584 if (!Best->FinalConversion.DirectBinding)
3585 return false;
3586
Chandler Carruth30141632011-02-25 19:41:05 +00003587 if (Best->Function)
3588 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003589 ICS.setUserDefined();
3590 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3591 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003592 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003593 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003594 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003595 ICS.UserDefined.EllipsisConversion = false;
3596 assert(ICS.UserDefined.After.ReferenceBinding &&
3597 ICS.UserDefined.After.DirectBinding &&
3598 "Expected a direct reference binding!");
3599 return true;
3600
3601 case OR_Ambiguous:
3602 ICS.setAmbiguous();
3603 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3604 Cand != CandidateSet.end(); ++Cand)
3605 if (Cand->Viable)
3606 ICS.Ambiguous.addConversion(Cand->Function);
3607 return true;
3608
3609 case OR_No_Viable_Function:
3610 case OR_Deleted:
3611 // There was no suitable conversion, or we found a deleted
3612 // conversion; continue with other checks.
3613 return false;
3614 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003615
Eric Christopheraba9fb22010-06-30 18:36:32 +00003616 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003617}
3618
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003619/// \brief Compute an implicit conversion sequence for reference
3620/// initialization.
3621static ImplicitConversionSequence
3622TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3623 SourceLocation DeclLoc,
3624 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003625 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003626 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3627
3628 // Most paths end in a failed conversion.
3629 ImplicitConversionSequence ICS;
3630 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3631
3632 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3633 QualType T2 = Init->getType();
3634
3635 // If the initializer is the address of an overloaded function, try
3636 // to resolve the overloaded function. If all goes well, T2 is the
3637 // type of the resulting function.
3638 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3639 DeclAccessPair Found;
3640 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3641 false, Found))
3642 T2 = Fn->getType();
3643 }
3644
3645 // Compute some basic properties of the types and the initializer.
3646 bool isRValRef = DeclType->isRValueReferenceType();
3647 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003648 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003649 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003650 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003651 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003652 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003653 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003654
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003655
Sebastian Redld92badf2010-06-30 18:13:39 +00003656 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003657 // A reference to type "cv1 T1" is initialized by an expression
3658 // of type "cv2 T2" as follows:
3659
Sebastian Redld92badf2010-06-30 18:13:39 +00003660 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003661 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003662 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3663 // reference-compatible with "cv2 T2," or
3664 //
3665 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3666 if (InitCategory.isLValue() &&
3667 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003668 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003669 // When a parameter of reference type binds directly (8.5.3)
3670 // to an argument expression, the implicit conversion sequence
3671 // is the identity conversion, unless the argument expression
3672 // has a type that is a derived class of the parameter type,
3673 // in which case the implicit conversion sequence is a
3674 // derived-to-base Conversion (13.3.3.1).
3675 ICS.setStandard();
3676 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003677 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3678 : ObjCConversion? ICK_Compatible_Conversion
3679 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003680 ICS.Standard.Third = ICK_Identity;
3681 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3682 ICS.Standard.setToType(0, T2);
3683 ICS.Standard.setToType(1, T1);
3684 ICS.Standard.setToType(2, T1);
3685 ICS.Standard.ReferenceBinding = true;
3686 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003687 ICS.Standard.IsLvalueReference = !isRValRef;
3688 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3689 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003690 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003691 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003692 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003693
Sebastian Redld92badf2010-06-30 18:13:39 +00003694 // Nothing more to do: the inaccessibility/ambiguity check for
3695 // derived-to-base conversions is suppressed when we're
3696 // computing the implicit conversion sequence (C++
3697 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003698 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003699 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003700
Sebastian Redld92badf2010-06-30 18:13:39 +00003701 // -- has a class type (i.e., T2 is a class type), where T1 is
3702 // not reference-related to T2, and can be implicitly
3703 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3704 // is reference-compatible with "cv3 T3" 92) (this
3705 // conversion is selected by enumerating the applicable
3706 // conversion functions (13.3.1.6) and choosing the best
3707 // one through overload resolution (13.3)),
3708 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003709 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003710 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003711 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3712 Init, T2, /*AllowRvalues=*/false,
3713 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003714 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003715 }
3716 }
3717
Sebastian Redld92badf2010-06-30 18:13:39 +00003718 // -- Otherwise, the reference shall be an lvalue reference to a
3719 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003720 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003721 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003722 // We actually handle one oddity of C++ [over.ics.ref] at this
3723 // point, which is that, due to p2 (which short-circuits reference
3724 // binding by only attempting a simple conversion for non-direct
3725 // bindings) and p3's strange wording, we allow a const volatile
3726 // reference to bind to an rvalue. Hence the check for the presence
3727 // of "const" rather than checking for "const" being the only
3728 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003729 // This is also the point where rvalue references and lvalue inits no longer
3730 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003731 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003732 return ICS;
3733
Douglas Gregorf143cd52011-01-24 16:14:37 +00003734 // -- If the initializer expression
3735 //
3736 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003737 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003738 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3739 (InitCategory.isXValue() ||
3740 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3741 (InitCategory.isLValue() && T2->isFunctionType()))) {
3742 ICS.setStandard();
3743 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003744 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003745 : ObjCConversion? ICK_Compatible_Conversion
3746 : ICK_Identity;
3747 ICS.Standard.Third = ICK_Identity;
3748 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3749 ICS.Standard.setToType(0, T2);
3750 ICS.Standard.setToType(1, T1);
3751 ICS.Standard.setToType(2, T1);
3752 ICS.Standard.ReferenceBinding = true;
3753 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3754 // binding unless we're binding to a class prvalue.
3755 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3756 // allow the use of rvalue references in C++98/03 for the benefit of
3757 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003758 ICS.Standard.DirectBinding =
3759 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003760 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003761 ICS.Standard.IsLvalueReference = !isRValRef;
3762 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003763 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003764 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003765 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003766 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003767 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003768 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003769
Douglas Gregorf143cd52011-01-24 16:14:37 +00003770 // -- has a class type (i.e., T2 is a class type), where T1 is not
3771 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003772 // an xvalue, class prvalue, or function lvalue of type
3773 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003774 // "cv3 T3",
3775 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003776 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003777 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003778 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003779 // class subobject).
3780 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003781 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003782 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3783 Init, T2, /*AllowRvalues=*/true,
3784 AllowExplicit)) {
3785 // In the second case, if the reference is an rvalue reference
3786 // and the second standard conversion sequence of the
3787 // user-defined conversion sequence includes an lvalue-to-rvalue
3788 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003789 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003790 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3791 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3792
Douglas Gregor95273c32011-01-21 16:36:05 +00003793 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003794 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003795
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003796 // -- Otherwise, a temporary of type "cv1 T1" is created and
3797 // initialized from the initializer expression using the
3798 // rules for a non-reference copy initialization (8.5). The
3799 // reference is then bound to the temporary. If T1 is
3800 // reference-related to T2, cv1 must be the same
3801 // cv-qualification as, or greater cv-qualification than,
3802 // cv2; otherwise, the program is ill-formed.
3803 if (RefRelationship == Sema::Ref_Related) {
3804 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3805 // we would be reference-compatible or reference-compatible with
3806 // added qualification. But that wasn't the case, so the reference
3807 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00003808 //
3809 // Note that we only want to check address spaces and cvr-qualifiers here.
3810 // ObjC GC and lifetime qualifiers aren't important.
3811 Qualifiers T1Quals = T1.getQualifiers();
3812 Qualifiers T2Quals = T2.getQualifiers();
3813 T1Quals.removeObjCGCAttr();
3814 T1Quals.removeObjCLifetime();
3815 T2Quals.removeObjCGCAttr();
3816 T2Quals.removeObjCLifetime();
3817 if (!T1Quals.compatiblyIncludes(T2Quals))
3818 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003819 }
3820
3821 // If at least one of the types is a class type, the types are not
3822 // related, and we aren't allowed any user conversions, the
3823 // reference binding fails. This case is important for breaking
3824 // recursion, since TryImplicitConversion below will attempt to
3825 // create a temporary through the use of a copy constructor.
3826 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3827 (T1->isRecordType() || T2->isRecordType()))
3828 return ICS;
3829
Douglas Gregorcba72b12011-01-21 05:18:22 +00003830 // If T1 is reference-related to T2 and the reference is an rvalue
3831 // reference, the initializer expression shall not be an lvalue.
3832 if (RefRelationship >= Sema::Ref_Related &&
3833 isRValRef && Init->Classify(S.Context).isLValue())
3834 return ICS;
3835
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003836 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003837 // When a parameter of reference type is not bound directly to
3838 // an argument expression, the conversion sequence is the one
3839 // required to convert the argument expression to the
3840 // underlying type of the reference according to
3841 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3842 // to copy-initializing a temporary of the underlying type with
3843 // the argument expression. Any difference in top-level
3844 // cv-qualification is subsumed by the initialization itself
3845 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003846 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3847 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003848 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003849 /*CStyle=*/false,
3850 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003851
3852 // Of course, that's still a reference binding.
3853 if (ICS.isStandard()) {
3854 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003855 ICS.Standard.IsLvalueReference = !isRValRef;
3856 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3857 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003858 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003859 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003860 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003861 // Don't allow rvalue references to bind to lvalues.
3862 if (DeclType->isRValueReferenceType()) {
3863 if (const ReferenceType *RefType
3864 = ICS.UserDefined.ConversionFunction->getResultType()
3865 ->getAs<LValueReferenceType>()) {
3866 if (!RefType->getPointeeType()->isFunctionType()) {
3867 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
3868 DeclType);
3869 return ICS;
3870 }
3871 }
3872 }
3873
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003874 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00003875 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3876 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3877 ICS.UserDefined.After.BindsToRvalue = true;
3878 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3879 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003880 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003881
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003882 return ICS;
3883}
3884
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003885static ImplicitConversionSequence
3886TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
3887 bool SuppressUserConversions,
3888 bool InOverloadResolution,
3889 bool AllowObjCWritebackConversion);
3890
3891/// TryListConversion - Try to copy-initialize a value of type ToType from the
3892/// initializer list From.
3893static ImplicitConversionSequence
3894TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
3895 bool SuppressUserConversions,
3896 bool InOverloadResolution,
3897 bool AllowObjCWritebackConversion) {
3898 // C++11 [over.ics.list]p1:
3899 // When an argument is an initializer list, it is not an expression and
3900 // special rules apply for converting it to a parameter type.
3901
3902 ImplicitConversionSequence Result;
3903 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003904 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003905
3906 // C++11 [over.ics.list]p2:
3907 // If the parameter type is std::initializer_list<X> or "array of X" and
3908 // all the elements can be implicitly converted to X, the implicit
3909 // conversion sequence is the worst conversion necessary to convert an
3910 // element of the list to X.
3911 // FIXME: Recognize std::initializer_list.
3912 // FIXME: Arrays don't make sense until we can deal with references.
3913 if (ToType->isArrayType())
3914 return Result;
3915
3916 // C++11 [over.ics.list]p3:
3917 // Otherwise, if the parameter is a non-aggregate class X and overload
3918 // resolution chooses a single best constructor [...] the implicit
3919 // conversion sequence is a user-defined conversion sequence. If multiple
3920 // constructors are viable but none is better than the others, the
3921 // implicit conversion sequence is a user-defined conversion sequence.
3922 // FIXME: Implement this.
3923 if (ToType->isRecordType() && !ToType->isAggregateType())
3924 return Result;
3925
3926 // C++11 [over.ics.list]p4:
3927 // Otherwise, if the parameter has an aggregate type which can be
3928 // initialized from the initializer list [...] the implicit conversion
3929 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003930 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003931 // Type is an aggregate, argument is an init list. At this point it comes
3932 // down to checking whether the initialization works.
3933 // FIXME: Find out whether this parameter is consumed or not.
3934 InitializedEntity Entity =
3935 InitializedEntity::InitializeParameter(S.Context, ToType,
3936 /*Consumed=*/false);
3937 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
3938 Result.setUserDefined();
3939 Result.UserDefined.Before.setAsIdentityConversion();
3940 // Initializer lists don't have a type.
3941 Result.UserDefined.Before.setFromType(QualType());
3942 Result.UserDefined.Before.setAllToTypes(QualType());
3943
3944 Result.UserDefined.After.setAsIdentityConversion();
3945 Result.UserDefined.After.setFromType(ToType);
3946 Result.UserDefined.After.setAllToTypes(ToType);
3947 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003948 return Result;
3949 }
3950
3951 // C++11 [over.ics.list]p5:
3952 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
3953 // FIXME: Implement this.
3954 if (ToType->isReferenceType())
3955 return Result;
3956
3957 // C++11 [over.ics.list]p6:
3958 // Otherwise, if the parameter type is not a class:
3959 if (!ToType->isRecordType()) {
3960 // - if the initializer list has one element, the implicit conversion
3961 // sequence is the one required to convert the element to the
3962 // parameter type.
3963 // FIXME: Catch narrowing here?
3964 unsigned NumInits = From->getNumInits();
3965 if (NumInits == 1)
3966 Result = TryCopyInitialization(S, From->getInit(0), ToType,
3967 SuppressUserConversions,
3968 InOverloadResolution,
3969 AllowObjCWritebackConversion);
3970 // - if the initializer list has no elements, the implicit conversion
3971 // sequence is the identity conversion.
3972 else if (NumInits == 0) {
3973 Result.setStandard();
3974 Result.Standard.setAsIdentityConversion();
3975 }
3976 return Result;
3977 }
3978
3979 // C++11 [over.ics.list]p7:
3980 // In all cases other than those enumerated above, no conversion is possible
3981 return Result;
3982}
3983
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003984/// TryCopyInitialization - Try to copy-initialize a value of type
3985/// ToType from the expression From. Return the implicit conversion
3986/// sequence required to pass this argument, which may be a bad
3987/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003988/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003989/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003990static ImplicitConversionSequence
3991TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003992 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00003993 bool InOverloadResolution,
3994 bool AllowObjCWritebackConversion) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003995 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
3996 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
3997 InOverloadResolution,AllowObjCWritebackConversion);
3998
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003999 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004000 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004001 /*FIXME:*/From->getLocStart(),
4002 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004003 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004004
John McCall5c32be02010-08-24 20:38:10 +00004005 return TryImplicitConversion(S, From, ToType,
4006 SuppressUserConversions,
4007 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004008 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004009 /*CStyle=*/false,
4010 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004011}
4012
Anna Zaks1b068122011-07-28 19:46:48 +00004013static bool TryCopyInitialization(const CanQualType FromQTy,
4014 const CanQualType ToQTy,
4015 Sema &S,
4016 SourceLocation Loc,
4017 ExprValueKind FromVK) {
4018 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4019 ImplicitConversionSequence ICS =
4020 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4021
4022 return !ICS.isBad();
4023}
4024
Douglas Gregor436424c2008-11-18 23:14:02 +00004025/// TryObjectArgumentInitialization - Try to initialize the object
4026/// parameter of the given member function (@c Method) from the
4027/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004028static ImplicitConversionSequence
4029TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004030 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004031 CXXMethodDecl *Method,
4032 CXXRecordDecl *ActingContext) {
4033 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004034 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4035 // const volatile object.
4036 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4037 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004038 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004039
4040 // Set up the conversion sequence as a "bad" conversion, to allow us
4041 // to exit early.
4042 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004043
4044 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004045 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004046 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004047 FromType = PT->getPointeeType();
4048
Douglas Gregor02824322011-01-26 19:30:28 +00004049 // When we had a pointer, it's implicitly dereferenced, so we
4050 // better have an lvalue.
4051 assert(FromClassification.isLValue());
4052 }
4053
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004054 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004055
Douglas Gregor02824322011-01-26 19:30:28 +00004056 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004057 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004058 // parameter is
4059 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004060 // - "lvalue reference to cv X" for functions declared without a
4061 // ref-qualifier or with the & ref-qualifier
4062 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004063 // ref-qualifier
4064 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004065 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004066 // cv-qualification on the member function declaration.
4067 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004068 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004069 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004070 // (C++ [over.match.funcs]p5). We perform a simplified version of
4071 // reference binding here, that allows class rvalues to bind to
4072 // non-constant references.
4073
Douglas Gregor02824322011-01-26 19:30:28 +00004074 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004075 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004076 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004077 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004078 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004079 ICS.setBad(BadConversionSequence::bad_qualifiers,
4080 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004081 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004082 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004083
4084 // Check that we have either the same type or a derived type. It
4085 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004086 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004087 ImplicitConversionKind SecondKind;
4088 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4089 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004090 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004091 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004092 else {
John McCall65eb8792010-02-25 01:37:24 +00004093 ICS.setBad(BadConversionSequence::unrelated_class,
4094 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004095 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004096 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004097
Douglas Gregor02824322011-01-26 19:30:28 +00004098 // Check the ref-qualifier.
4099 switch (Method->getRefQualifier()) {
4100 case RQ_None:
4101 // Do nothing; we don't care about lvalueness or rvalueness.
4102 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004103
Douglas Gregor02824322011-01-26 19:30:28 +00004104 case RQ_LValue:
4105 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4106 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004107 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004108 ImplicitParamType);
4109 return ICS;
4110 }
4111 break;
4112
4113 case RQ_RValue:
4114 if (!FromClassification.isRValue()) {
4115 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004116 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004117 ImplicitParamType);
4118 return ICS;
4119 }
4120 break;
4121 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004122
Douglas Gregor436424c2008-11-18 23:14:02 +00004123 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004124 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004125 ICS.Standard.setAsIdentityConversion();
4126 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004127 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004128 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004129 ICS.Standard.ReferenceBinding = true;
4130 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004131 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004132 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004133 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4134 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4135 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004136 return ICS;
4137}
4138
4139/// PerformObjectArgumentInitialization - Perform initialization of
4140/// the implicit object parameter for the given Method with the given
4141/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004142ExprResult
4143Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004144 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004145 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004146 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004147 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004148 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004149 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004150
Douglas Gregor02824322011-01-26 19:30:28 +00004151 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004152 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004153 FromRecordType = PT->getPointeeType();
4154 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004155 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004156 } else {
4157 FromRecordType = From->getType();
4158 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004159 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004160 }
4161
John McCall6e9f8f62009-12-03 04:06:58 +00004162 // Note that we always use the true parent context when performing
4163 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004164 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004165 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4166 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004167 if (ICS.isBad()) {
4168 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4169 Qualifiers FromQs = FromRecordType.getQualifiers();
4170 Qualifiers ToQs = DestType.getQualifiers();
4171 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4172 if (CVR) {
4173 Diag(From->getSourceRange().getBegin(),
4174 diag::err_member_function_call_bad_cvr)
4175 << Method->getDeclName() << FromRecordType << (CVR - 1)
4176 << From->getSourceRange();
4177 Diag(Method->getLocation(), diag::note_previous_decl)
4178 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004179 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004180 }
4181 }
4182
Douglas Gregor436424c2008-11-18 23:14:02 +00004183 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004184 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004185 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004186 }
Mike Stump11289f42009-09-09 15:08:12 +00004187
John Wiegley01296292011-04-08 18:41:53 +00004188 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4189 ExprResult FromRes =
4190 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4191 if (FromRes.isInvalid())
4192 return ExprError();
4193 From = FromRes.take();
4194 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004195
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004196 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004197 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004198 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004199 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004200}
4201
Douglas Gregor5fb53972009-01-14 15:45:31 +00004202/// TryContextuallyConvertToBool - Attempt to contextually convert the
4203/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004204static ImplicitConversionSequence
4205TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004206 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004207 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004208 // FIXME: Are these flags correct?
4209 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004210 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004211 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004212 /*CStyle=*/false,
4213 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004214}
4215
4216/// PerformContextuallyConvertToBool - Perform a contextual conversion
4217/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004218ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004219 if (checkPlaceholderForOverload(*this, From))
4220 return ExprError();
4221
John McCall5c32be02010-08-24 20:38:10 +00004222 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004223 if (!ICS.isBad())
4224 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004225
Fariborz Jahanian76197412009-11-18 18:26:29 +00004226 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00004227 return Diag(From->getSourceRange().getBegin(),
4228 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004229 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004230 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004231}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004232
John McCallfec112d2011-09-09 06:11:02 +00004233/// dropPointerConversions - If the given standard conversion sequence
4234/// involves any pointer conversions, remove them. This may change
4235/// the result type of the conversion sequence.
4236static void dropPointerConversion(StandardConversionSequence &SCS) {
4237 if (SCS.Second == ICK_Pointer_Conversion) {
4238 SCS.Second = ICK_Identity;
4239 SCS.Third = ICK_Identity;
4240 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4241 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004242}
John McCall5c32be02010-08-24 20:38:10 +00004243
John McCallfec112d2011-09-09 06:11:02 +00004244/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4245/// convert the expression From to an Objective-C pointer type.
4246static ImplicitConversionSequence
4247TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4248 // Do an implicit conversion to 'id'.
4249 QualType Ty = S.Context.getObjCIdType();
4250 ImplicitConversionSequence ICS
4251 = TryImplicitConversion(S, From, Ty,
4252 // FIXME: Are these flags correct?
4253 /*SuppressUserConversions=*/false,
4254 /*AllowExplicit=*/true,
4255 /*InOverloadResolution=*/false,
4256 /*CStyle=*/false,
4257 /*AllowObjCWritebackConversion=*/false);
4258
4259 // Strip off any final conversions to 'id'.
4260 switch (ICS.getKind()) {
4261 case ImplicitConversionSequence::BadConversion:
4262 case ImplicitConversionSequence::AmbiguousConversion:
4263 case ImplicitConversionSequence::EllipsisConversion:
4264 break;
4265
4266 case ImplicitConversionSequence::UserDefinedConversion:
4267 dropPointerConversion(ICS.UserDefined.After);
4268 break;
4269
4270 case ImplicitConversionSequence::StandardConversion:
4271 dropPointerConversion(ICS.Standard);
4272 break;
4273 }
4274
4275 return ICS;
4276}
4277
4278/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4279/// conversion of the expression From to an Objective-C pointer type.
4280ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004281 if (checkPlaceholderForOverload(*this, From))
4282 return ExprError();
4283
John McCall8b07ec22010-05-15 11:32:37 +00004284 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004285 ImplicitConversionSequence ICS =
4286 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004287 if (!ICS.isBad())
4288 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004289 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004290}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004291
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004292/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004293/// enumeration type.
4294///
4295/// This routine will attempt to convert an expression of class type to an
4296/// integral or enumeration type, if that class type only has a single
4297/// conversion to an integral or enumeration type.
4298///
Douglas Gregor4799d032010-06-30 00:20:43 +00004299/// \param Loc The source location of the construct that requires the
4300/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004301///
Douglas Gregor4799d032010-06-30 00:20:43 +00004302/// \param FromE The expression we're converting from.
4303///
4304/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4305/// have integral or enumeration type.
4306///
4307/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4308/// incomplete class type.
4309///
4310/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4311/// explicit conversion function (because no implicit conversion functions
4312/// were available). This is a recovery mode.
4313///
4314/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4315/// showing which conversion was picked.
4316///
4317/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4318/// conversion function that could convert to integral or enumeration type.
4319///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004320/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004321/// usable conversion function.
4322///
4323/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4324/// function, which may be an extension in this case.
4325///
4326/// \returns The expression, converted to an integral or enumeration type if
4327/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004328ExprResult
John McCallb268a282010-08-23 23:25:46 +00004329Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004330 const PartialDiagnostic &NotIntDiag,
4331 const PartialDiagnostic &IncompleteDiag,
4332 const PartialDiagnostic &ExplicitConvDiag,
4333 const PartialDiagnostic &ExplicitConvNote,
4334 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004335 const PartialDiagnostic &AmbigNote,
4336 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004337 // We can't perform any more checking for type-dependent expressions.
4338 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004339 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004340
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004341 // If the expression already has integral or enumeration type, we're golden.
4342 QualType T = From->getType();
4343 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00004344 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004345
4346 // FIXME: Check for missing '()' if T is a function type?
4347
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004348 // 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 +00004349 // expression of integral or enumeration type.
4350 const RecordType *RecordTy = T->getAs<RecordType>();
4351 if (!RecordTy || !getLangOptions().CPlusPlus) {
4352 Diag(Loc, NotIntDiag)
4353 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004354 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004355 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004356
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004357 // We must have a complete class type.
4358 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004359 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004360
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004361 // Look for a conversion to an integral or enumeration type.
4362 UnresolvedSet<4> ViableConversions;
4363 UnresolvedSet<4> ExplicitConversions;
4364 const UnresolvedSetImpl *Conversions
4365 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004366
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004367 bool HadMultipleCandidates = (Conversions->size() > 1);
4368
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004369 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004370 E = Conversions->end();
4371 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004372 ++I) {
4373 if (CXXConversionDecl *Conversion
4374 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4375 if (Conversion->getConversionType().getNonReferenceType()
4376 ->isIntegralOrEnumerationType()) {
4377 if (Conversion->isExplicit())
4378 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4379 else
4380 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4381 }
4382 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004383
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004384 switch (ViableConversions.size()) {
4385 case 0:
4386 if (ExplicitConversions.size() == 1) {
4387 DeclAccessPair Found = ExplicitConversions[0];
4388 CXXConversionDecl *Conversion
4389 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004390
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004391 // The user probably meant to invoke the given explicit
4392 // conversion; use it.
4393 QualType ConvTy
4394 = Conversion->getConversionType().getNonReferenceType();
4395 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00004396 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004397
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004398 Diag(Loc, ExplicitConvDiag)
4399 << T << ConvTy
4400 << FixItHint::CreateInsertion(From->getLocStart(),
4401 "static_cast<" + TypeStr + ">(")
4402 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4403 ")");
4404 Diag(Conversion->getLocation(), ExplicitConvNote)
4405 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004406
4407 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004408 // explicit conversion function.
4409 if (isSFINAEContext())
4410 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004411
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004412 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004413 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4414 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004415 if (Result.isInvalid())
4416 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004417 // Record usage of conversion in an implicit cast.
4418 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4419 CK_UserDefinedConversion,
4420 Result.get(), 0,
4421 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004422 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004423
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004424 // We'll complain below about a non-integral condition type.
4425 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004426
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004427 case 1: {
4428 // Apply this conversion.
4429 DeclAccessPair Found = ViableConversions[0];
4430 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004431
Douglas Gregor4799d032010-06-30 00:20:43 +00004432 CXXConversionDecl *Conversion
4433 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4434 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004435 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004436 if (ConvDiag.getDiagID()) {
4437 if (isSFINAEContext())
4438 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004439
Douglas Gregor4799d032010-06-30 00:20:43 +00004440 Diag(Loc, ConvDiag)
4441 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4442 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004443
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004444 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4445 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004446 if (Result.isInvalid())
4447 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004448 // Record usage of conversion in an implicit cast.
4449 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4450 CK_UserDefinedConversion,
4451 Result.get(), 0,
4452 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004453 break;
4454 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004455
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004456 default:
4457 Diag(Loc, AmbigDiag)
4458 << T << From->getSourceRange();
4459 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4460 CXXConversionDecl *Conv
4461 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4462 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4463 Diag(Conv->getLocation(), AmbigNote)
4464 << ConvTy->isEnumeralType() << ConvTy;
4465 }
John McCallb268a282010-08-23 23:25:46 +00004466 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004467 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004468
Douglas Gregor5823da32010-06-29 23:25:20 +00004469 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004470 Diag(Loc, NotIntDiag)
4471 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004472
John McCallb268a282010-08-23 23:25:46 +00004473 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004474}
4475
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004476/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004477/// candidate functions, using the given function call arguments. If
4478/// @p SuppressUserConversions, then don't allow user-defined
4479/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004480///
4481/// \para PartialOverloading true if we are performing "partial" overloading
4482/// based on an incomplete set of function arguments. This feature is used by
4483/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004484void
4485Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004486 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004487 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004488 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004489 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004490 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004491 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004492 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004493 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004494 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004495 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004496
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004497 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004498 if (!isa<CXXConstructorDecl>(Method)) {
4499 // If we get here, it's because we're calling a member function
4500 // that is named without a member access expression (e.g.,
4501 // "this->f") that was either written explicitly or created
4502 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004503 // function, e.g., X::f(). We use an empty type for the implied
4504 // object argument (C++ [over.call.func]p3), and the acting context
4505 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004506 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004507 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004508 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004509 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004510 return;
4511 }
4512 // We treat a constructor like a non-member function, since its object
4513 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004514 }
4515
Douglas Gregorff7028a2009-11-13 23:59:09 +00004516 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004517 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004518
Douglas Gregor27381f32009-11-23 12:27:39 +00004519 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004520 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004521
Douglas Gregorffe14e32009-11-14 01:20:54 +00004522 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4523 // C++ [class.copy]p3:
4524 // A member function template is never instantiated to perform the copy
4525 // of a class object to an object of its class type.
4526 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004527 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004528 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004529 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4530 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004531 return;
4532 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004533
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004534 // Add this candidate
4535 CandidateSet.push_back(OverloadCandidate());
4536 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004537 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004538 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004539 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004540 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004541 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004542 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004543
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004544 unsigned NumArgsInProto = Proto->getNumArgs();
4545
4546 // (C++ 13.3.2p2): A candidate function having fewer than m
4547 // parameters is viable only if it has an ellipsis in its parameter
4548 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004549 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004550 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004551 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004552 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004553 return;
4554 }
4555
4556 // (C++ 13.3.2p2): A candidate function having more than m parameters
4557 // is viable only if the (m+1)st parameter has a default argument
4558 // (8.3.6). For the purposes of overload resolution, the
4559 // parameter list is truncated on the right, so that there are
4560 // exactly m parameters.
4561 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004562 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004563 // Not enough arguments.
4564 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004565 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004566 return;
4567 }
4568
Peter Collingbourne7277fe82011-10-02 23:49:40 +00004569 // (CUDA B.1): Check for invalid calls between targets.
4570 if (getLangOptions().CUDA)
4571 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4572 if (CheckCUDATarget(Caller, Function)) {
4573 Candidate.Viable = false;
4574 Candidate.FailureKind = ovl_fail_bad_target;
4575 return;
4576 }
4577
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004578 // Determine the implicit conversion sequences for each of the
4579 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004580 Candidate.Conversions.resize(NumArgs);
4581 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4582 if (ArgIdx < NumArgsInProto) {
4583 // (C++ 13.3.2p3): for F to be a viable function, there shall
4584 // exist for each argument an implicit conversion sequence
4585 // (13.3.3.1) that converts that argument to the corresponding
4586 // parameter of F.
4587 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004588 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004589 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004590 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004591 /*InOverloadResolution=*/true,
4592 /*AllowObjCWritebackConversion=*/
4593 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004594 if (Candidate.Conversions[ArgIdx].isBad()) {
4595 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004596 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004597 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004598 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004599 } else {
4600 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4601 // argument for which there is no corresponding parameter is
4602 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004603 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004604 }
4605 }
4606}
4607
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004608/// \brief Add all of the function declarations in the given function set to
4609/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004610void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004611 Expr **Args, unsigned NumArgs,
4612 OverloadCandidateSet& CandidateSet,
4613 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004614 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004615 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4616 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004617 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004618 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004619 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004620 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004621 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004622 CandidateSet, SuppressUserConversions);
4623 else
John McCalla0296f72010-03-19 07:35:19 +00004624 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004625 SuppressUserConversions);
4626 } else {
John McCalla0296f72010-03-19 07:35:19 +00004627 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004628 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4629 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004630 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004631 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004632 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004633 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004634 Args[0]->Classify(Context),
4635 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004636 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004637 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004638 else
John McCalla0296f72010-03-19 07:35:19 +00004639 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004640 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004641 Args, NumArgs, CandidateSet,
4642 SuppressUserConversions);
4643 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004644 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004645}
4646
John McCallf0f1cf02009-11-17 07:50:12 +00004647/// AddMethodCandidate - Adds a named decl (which is some kind of
4648/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004649void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004650 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004651 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004652 Expr **Args, unsigned NumArgs,
4653 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004654 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004655 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004656 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004657
4658 if (isa<UsingShadowDecl>(Decl))
4659 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004660
John McCallf0f1cf02009-11-17 07:50:12 +00004661 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4662 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4663 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004664 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4665 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004666 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004667 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004668 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004669 } else {
John McCalla0296f72010-03-19 07:35:19 +00004670 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004671 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004672 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004673 }
4674}
4675
Douglas Gregor436424c2008-11-18 23:14:02 +00004676/// AddMethodCandidate - Adds the given C++ member function to the set
4677/// of candidate functions, using the given function call arguments
4678/// and the object argument (@c Object). For example, in a call
4679/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4680/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4681/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004682/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004683void
John McCalla0296f72010-03-19 07:35:19 +00004684Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004685 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004686 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004687 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004688 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004689 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004690 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004691 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004692 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004693 assert(!isa<CXXConstructorDecl>(Method) &&
4694 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004695
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004696 if (!CandidateSet.isNewCandidate(Method))
4697 return;
4698
Douglas Gregor27381f32009-11-23 12:27:39 +00004699 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004700 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004701
Douglas Gregor436424c2008-11-18 23:14:02 +00004702 // Add this candidate
4703 CandidateSet.push_back(OverloadCandidate());
4704 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004705 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004706 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004707 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004708 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004709 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004710
4711 unsigned NumArgsInProto = Proto->getNumArgs();
4712
4713 // (C++ 13.3.2p2): A candidate function having fewer than m
4714 // parameters is viable only if it has an ellipsis in its parameter
4715 // list (8.3.5).
4716 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4717 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004718 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004719 return;
4720 }
4721
4722 // (C++ 13.3.2p2): A candidate function having more than m parameters
4723 // is viable only if the (m+1)st parameter has a default argument
4724 // (8.3.6). For the purposes of overload resolution, the
4725 // parameter list is truncated on the right, so that there are
4726 // exactly m parameters.
4727 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4728 if (NumArgs < MinRequiredArgs) {
4729 // Not enough arguments.
4730 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004731 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004732 return;
4733 }
4734
4735 Candidate.Viable = true;
4736 Candidate.Conversions.resize(NumArgs + 1);
4737
John McCall6e9f8f62009-12-03 04:06:58 +00004738 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004739 // The implicit object argument is ignored.
4740 Candidate.IgnoreObjectArgument = true;
4741 else {
4742 // Determine the implicit conversion sequence for the object
4743 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004744 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004745 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4746 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004747 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004748 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004749 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004750 return;
4751 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004752 }
4753
4754 // Determine the implicit conversion sequences for each of the
4755 // arguments.
4756 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4757 if (ArgIdx < NumArgsInProto) {
4758 // (C++ 13.3.2p3): for F to be a viable function, there shall
4759 // exist for each argument an implicit conversion sequence
4760 // (13.3.3.1) that converts that argument to the corresponding
4761 // parameter of F.
4762 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004763 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004764 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004765 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004766 /*InOverloadResolution=*/true,
4767 /*AllowObjCWritebackConversion=*/
4768 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004769 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004770 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004771 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004772 break;
4773 }
4774 } else {
4775 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4776 // argument for which there is no corresponding parameter is
4777 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004778 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004779 }
4780 }
4781}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004782
Douglas Gregor97628d62009-08-21 00:16:32 +00004783/// \brief Add a C++ member function template as a candidate to the candidate
4784/// set, using template argument deduction to produce an appropriate member
4785/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004786void
Douglas Gregor97628d62009-08-21 00:16:32 +00004787Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004788 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004789 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004790 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004791 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004792 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004793 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004794 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004795 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004796 if (!CandidateSet.isNewCandidate(MethodTmpl))
4797 return;
4798
Douglas Gregor97628d62009-08-21 00:16:32 +00004799 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004800 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004801 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004802 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004803 // candidate functions in the usual way.113) A given name can refer to one
4804 // or more function templates and also to a set of overloaded non-template
4805 // functions. In such a case, the candidate functions generated from each
4806 // function template are combined with the set of non-template candidate
4807 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004808 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004809 FunctionDecl *Specialization = 0;
4810 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004811 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004812 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004813 CandidateSet.push_back(OverloadCandidate());
4814 OverloadCandidate &Candidate = CandidateSet.back();
4815 Candidate.FoundDecl = FoundDecl;
4816 Candidate.Function = MethodTmpl->getTemplatedDecl();
4817 Candidate.Viable = false;
4818 Candidate.FailureKind = ovl_fail_bad_deduction;
4819 Candidate.IsSurrogate = false;
4820 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004821 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004822 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004823 Info);
4824 return;
4825 }
Mike Stump11289f42009-09-09 15:08:12 +00004826
Douglas Gregor97628d62009-08-21 00:16:32 +00004827 // Add the function template specialization produced by template argument
4828 // deduction as a candidate.
4829 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004830 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004831 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004832 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004833 ActingContext, ObjectType, ObjectClassification,
4834 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004835}
4836
Douglas Gregor05155d82009-08-21 23:19:43 +00004837/// \brief Add a C++ function template specialization as a candidate
4838/// in the candidate set, using template argument deduction to produce
4839/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004840void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004841Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004842 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004843 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004844 Expr **Args, unsigned NumArgs,
4845 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004846 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004847 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4848 return;
4849
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004850 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004851 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004852 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004853 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004854 // candidate functions in the usual way.113) A given name can refer to one
4855 // or more function templates and also to a set of overloaded non-template
4856 // functions. In such a case, the candidate functions generated from each
4857 // function template are combined with the set of non-template candidate
4858 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004859 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004860 FunctionDecl *Specialization = 0;
4861 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004862 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004863 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004864 CandidateSet.push_back(OverloadCandidate());
4865 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004866 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004867 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4868 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004869 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004870 Candidate.IsSurrogate = false;
4871 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004872 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004873 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004874 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004875 return;
4876 }
Mike Stump11289f42009-09-09 15:08:12 +00004877
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004878 // Add the function template specialization produced by template argument
4879 // deduction as a candidate.
4880 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004881 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004882 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004883}
Mike Stump11289f42009-09-09 15:08:12 +00004884
Douglas Gregora1f013e2008-11-07 22:36:19 +00004885/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004886/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004887/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004888/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004889/// (which may or may not be the same type as the type that the
4890/// conversion function produces).
4891void
4892Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004893 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004894 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004895 Expr *From, QualType ToType,
4896 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004897 assert(!Conversion->getDescribedFunctionTemplate() &&
4898 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004899 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004900 if (!CandidateSet.isNewCandidate(Conversion))
4901 return;
4902
Douglas Gregor27381f32009-11-23 12:27:39 +00004903 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004904 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004905
Douglas Gregora1f013e2008-11-07 22:36:19 +00004906 // Add this candidate
4907 CandidateSet.push_back(OverloadCandidate());
4908 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004909 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004910 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004911 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004912 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004913 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004914 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004915 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004916 Candidate.Viable = true;
4917 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004918 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004919
Douglas Gregor6affc782010-08-19 15:37:02 +00004920 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004921 // For conversion functions, the function is considered to be a member of
4922 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004923 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004924 //
4925 // Determine the implicit conversion sequence for the implicit
4926 // object parameter.
4927 QualType ImplicitParamType = From->getType();
4928 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4929 ImplicitParamType = FromPtrType->getPointeeType();
4930 CXXRecordDecl *ConversionContext
4931 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004932
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004933 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004934 = TryObjectArgumentInitialization(*this, From->getType(),
4935 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004936 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004937
John McCall0d1da222010-01-12 00:44:57 +00004938 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004939 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004940 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004941 return;
4942 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004943
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004944 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004945 // derived to base as such conversions are given Conversion Rank. They only
4946 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4947 QualType FromCanon
4948 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4949 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4950 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4951 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004952 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004953 return;
4954 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004955
Douglas Gregora1f013e2008-11-07 22:36:19 +00004956 // To determine what the conversion from the result of calling the
4957 // conversion function to the type we're eventually trying to
4958 // convert to (ToType), we need to synthesize a call to the
4959 // conversion function and attempt copy initialization from it. This
4960 // makes sure that we get the right semantics with respect to
4961 // lvalues/rvalues and the type. Fortunately, we can allocate this
4962 // call on the stack and we don't need its arguments to be
4963 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004964 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004965 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004966 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4967 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004968 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004969 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004970
Richard Smith48d24642011-07-13 22:53:21 +00004971 QualType ConversionType = Conversion->getConversionType();
4972 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004973 Candidate.Viable = false;
4974 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4975 return;
4976 }
4977
Richard Smith48d24642011-07-13 22:53:21 +00004978 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00004979
Mike Stump11289f42009-09-09 15:08:12 +00004980 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004981 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4982 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00004983 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004984 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004985 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004986 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004987 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004988 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00004989 /*InOverloadResolution=*/false,
4990 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004991
John McCall0d1da222010-01-12 00:44:57 +00004992 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004993 case ImplicitConversionSequence::StandardConversion:
4994 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004995
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004996 // C++ [over.ics.user]p3:
4997 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004998 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004999 // shall have exact match rank.
5000 if (Conversion->getPrimaryTemplate() &&
5001 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5002 Candidate.Viable = false;
5003 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5004 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005005
Douglas Gregorcba72b12011-01-21 05:18:22 +00005006 // C++0x [dcl.init.ref]p5:
5007 // In the second case, if the reference is an rvalue reference and
5008 // the second standard conversion sequence of the user-defined
5009 // conversion sequence includes an lvalue-to-rvalue conversion, the
5010 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005011 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005012 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5013 Candidate.Viable = false;
5014 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5015 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005016 break;
5017
5018 case ImplicitConversionSequence::BadConversion:
5019 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005020 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005021 break;
5022
5023 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005024 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005025 "Can only end up with a standard conversion sequence or failure");
5026 }
5027}
5028
Douglas Gregor05155d82009-08-21 23:19:43 +00005029/// \brief Adds a conversion function template specialization
5030/// candidate to the overload set, using template argument deduction
5031/// to deduce the template arguments of the conversion function
5032/// template from the type that we are converting to (C++
5033/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005034void
Douglas Gregor05155d82009-08-21 23:19:43 +00005035Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005036 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005037 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005038 Expr *From, QualType ToType,
5039 OverloadCandidateSet &CandidateSet) {
5040 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5041 "Only conversion function templates permitted here");
5042
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005043 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5044 return;
5045
John McCallbc077cf2010-02-08 23:07:23 +00005046 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005047 CXXConversionDecl *Specialization = 0;
5048 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005049 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005050 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005051 CandidateSet.push_back(OverloadCandidate());
5052 OverloadCandidate &Candidate = CandidateSet.back();
5053 Candidate.FoundDecl = FoundDecl;
5054 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5055 Candidate.Viable = false;
5056 Candidate.FailureKind = ovl_fail_bad_deduction;
5057 Candidate.IsSurrogate = false;
5058 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005059 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005060 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005061 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005062 return;
5063 }
Mike Stump11289f42009-09-09 15:08:12 +00005064
Douglas Gregor05155d82009-08-21 23:19:43 +00005065 // Add the conversion function template specialization produced by
5066 // template argument deduction as a candidate.
5067 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005068 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005069 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005070}
5071
Douglas Gregorab7897a2008-11-19 22:57:39 +00005072/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5073/// converts the given @c Object to a function pointer via the
5074/// conversion function @c Conversion, and then attempts to call it
5075/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5076/// the type of function that we'll eventually be calling.
5077void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005078 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005079 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005080 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005081 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00005082 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005083 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005084 if (!CandidateSet.isNewCandidate(Conversion))
5085 return;
5086
Douglas Gregor27381f32009-11-23 12:27:39 +00005087 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005088 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005089
Douglas Gregorab7897a2008-11-19 22:57:39 +00005090 CandidateSet.push_back(OverloadCandidate());
5091 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00005092 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005093 Candidate.Function = 0;
5094 Candidate.Surrogate = Conversion;
5095 Candidate.Viable = true;
5096 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005097 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005098 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00005099 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005100
5101 // Determine the implicit conversion sequence for the implicit
5102 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005103 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005104 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005105 Object->Classify(Context),
5106 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005107 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005108 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005109 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005110 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005111 return;
5112 }
5113
5114 // The first conversion is actually a user-defined conversion whose
5115 // first conversion is ObjectInit's standard conversion (which is
5116 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005117 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005118 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005119 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005120 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005121 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005122 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005123 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005124 = Candidate.Conversions[0].UserDefined.Before;
5125 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5126
Mike Stump11289f42009-09-09 15:08:12 +00005127 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005128 unsigned NumArgsInProto = Proto->getNumArgs();
5129
5130 // (C++ 13.3.2p2): A candidate function having fewer than m
5131 // parameters is viable only if it has an ellipsis in its parameter
5132 // list (8.3.5).
5133 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5134 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005135 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005136 return;
5137 }
5138
5139 // Function types don't have any default arguments, so just check if
5140 // we have enough arguments.
5141 if (NumArgs < NumArgsInProto) {
5142 // Not enough arguments.
5143 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005144 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005145 return;
5146 }
5147
5148 // Determine the implicit conversion sequences for each of the
5149 // arguments.
5150 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5151 if (ArgIdx < NumArgsInProto) {
5152 // (C++ 13.3.2p3): for F to be a viable function, there shall
5153 // exist for each argument an implicit conversion sequence
5154 // (13.3.3.1) that converts that argument to the corresponding
5155 // parameter of F.
5156 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005157 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005158 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005159 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005160 /*InOverloadResolution=*/false,
5161 /*AllowObjCWritebackConversion=*/
5162 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005163 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005164 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005165 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005166 break;
5167 }
5168 } else {
5169 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5170 // argument for which there is no corresponding parameter is
5171 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005172 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005173 }
5174 }
5175}
5176
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005177/// \brief Add overload candidates for overloaded operators that are
5178/// member functions.
5179///
5180/// Add the overloaded operator candidates that are member functions
5181/// for the operator Op that was used in an operator expression such
5182/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5183/// CandidateSet will store the added overload candidates. (C++
5184/// [over.match.oper]).
5185void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5186 SourceLocation OpLoc,
5187 Expr **Args, unsigned NumArgs,
5188 OverloadCandidateSet& CandidateSet,
5189 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005190 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5191
5192 // C++ [over.match.oper]p3:
5193 // For a unary operator @ with an operand of a type whose
5194 // cv-unqualified version is T1, and for a binary operator @ with
5195 // a left operand of a type whose cv-unqualified version is T1 and
5196 // a right operand of a type whose cv-unqualified version is T2,
5197 // three sets of candidate functions, designated member
5198 // candidates, non-member candidates and built-in candidates, are
5199 // constructed as follows:
5200 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005201
5202 // -- If T1 is a class type, the set of member candidates is the
5203 // result of the qualified lookup of T1::operator@
5204 // (13.3.1.1.1); otherwise, the set of member candidates is
5205 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005206 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005207 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005208 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005209 return;
Mike Stump11289f42009-09-09 15:08:12 +00005210
John McCall27b18f82009-11-17 02:14:36 +00005211 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5212 LookupQualifiedName(Operators, T1Rec->getDecl());
5213 Operators.suppressDiagnostics();
5214
Mike Stump11289f42009-09-09 15:08:12 +00005215 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005216 OperEnd = Operators.end();
5217 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005218 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005219 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005220 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005221 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005222 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005223 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005224}
5225
Douglas Gregora11693b2008-11-12 17:17:38 +00005226/// AddBuiltinCandidate - Add a candidate for a built-in
5227/// operator. ResultTy and ParamTys are the result and parameter types
5228/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005229/// arguments being passed to the candidate. IsAssignmentOperator
5230/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005231/// operator. NumContextualBoolArguments is the number of arguments
5232/// (at the beginning of the argument list) that will be contextually
5233/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005234void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005235 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005236 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005237 bool IsAssignmentOperator,
5238 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005239 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005240 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005241
Douglas Gregora11693b2008-11-12 17:17:38 +00005242 // Add this candidate
5243 CandidateSet.push_back(OverloadCandidate());
5244 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00005245 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005246 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005247 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005248 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005249 Candidate.BuiltinTypes.ResultTy = ResultTy;
5250 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5251 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5252
5253 // Determine the implicit conversion sequences for each of the
5254 // arguments.
5255 Candidate.Viable = true;
5256 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00005257 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005258 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005259 // C++ [over.match.oper]p4:
5260 // For the built-in assignment operators, conversions of the
5261 // left operand are restricted as follows:
5262 // -- no temporaries are introduced to hold the left operand, and
5263 // -- no user-defined conversions are applied to the left
5264 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005265 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005266 //
5267 // We block these conversions by turning off user-defined
5268 // conversions, since that is the only way that initialization of
5269 // a reference to a non-class type can occur from something that
5270 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005271 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005272 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005273 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005274 Candidate.Conversions[ArgIdx]
5275 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005276 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005277 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005278 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005279 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005280 /*InOverloadResolution=*/false,
5281 /*AllowObjCWritebackConversion=*/
5282 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005283 }
John McCall0d1da222010-01-12 00:44:57 +00005284 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005285 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005286 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005287 break;
5288 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005289 }
5290}
5291
5292/// BuiltinCandidateTypeSet - A set of types that will be used for the
5293/// candidate operator functions for built-in operators (C++
5294/// [over.built]). The types are separated into pointer types and
5295/// enumeration types.
5296class BuiltinCandidateTypeSet {
5297 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005298 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005299
5300 /// PointerTypes - The set of pointer types that will be used in the
5301 /// built-in candidates.
5302 TypeSet PointerTypes;
5303
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005304 /// MemberPointerTypes - The set of member pointer types that will be
5305 /// used in the built-in candidates.
5306 TypeSet MemberPointerTypes;
5307
Douglas Gregora11693b2008-11-12 17:17:38 +00005308 /// EnumerationTypes - The set of enumeration types that will be
5309 /// used in the built-in candidates.
5310 TypeSet EnumerationTypes;
5311
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005312 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005313 /// candidates.
5314 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005315
5316 /// \brief A flag indicating non-record types are viable candidates
5317 bool HasNonRecordTypes;
5318
5319 /// \brief A flag indicating whether either arithmetic or enumeration types
5320 /// were present in the candidate set.
5321 bool HasArithmeticOrEnumeralTypes;
5322
Douglas Gregor80af3132011-05-21 23:15:46 +00005323 /// \brief A flag indicating whether the nullptr type was present in the
5324 /// candidate set.
5325 bool HasNullPtrType;
5326
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005327 /// Sema - The semantic analysis instance where we are building the
5328 /// candidate type set.
5329 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005330
Douglas Gregora11693b2008-11-12 17:17:38 +00005331 /// Context - The AST context in which we will build the type sets.
5332 ASTContext &Context;
5333
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005334 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5335 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005336 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005337
5338public:
5339 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005340 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005341
Mike Stump11289f42009-09-09 15:08:12 +00005342 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005343 : HasNonRecordTypes(false),
5344 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005345 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005346 SemaRef(SemaRef),
5347 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005348
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005349 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005350 SourceLocation Loc,
5351 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005352 bool AllowExplicitConversions,
5353 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005354
5355 /// pointer_begin - First pointer type found;
5356 iterator pointer_begin() { return PointerTypes.begin(); }
5357
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005358 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005359 iterator pointer_end() { return PointerTypes.end(); }
5360
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005361 /// member_pointer_begin - First member pointer type found;
5362 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5363
5364 /// member_pointer_end - Past the last member pointer type found;
5365 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5366
Douglas Gregora11693b2008-11-12 17:17:38 +00005367 /// enumeration_begin - First enumeration type found;
5368 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5369
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005370 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005371 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005372
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005373 iterator vector_begin() { return VectorTypes.begin(); }
5374 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005375
5376 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5377 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005378 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005379};
5380
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005381/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005382/// the set of pointer types along with any more-qualified variants of
5383/// that type. For example, if @p Ty is "int const *", this routine
5384/// will add "int const *", "int const volatile *", "int const
5385/// restrict *", and "int const volatile restrict *" to the set of
5386/// pointer types. Returns true if the add of @p Ty itself succeeded,
5387/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005388///
5389/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005390bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005391BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5392 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00005393
Douglas Gregora11693b2008-11-12 17:17:38 +00005394 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005395 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00005396 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005397
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005398 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00005399 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005400 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005401 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005402 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005403 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005404 buildObjCPtr = true;
5405 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005406 else
David Blaikie83d382b2011-09-23 05:06:16 +00005407 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005408 }
5409 else
5410 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005411
Sebastian Redl4990a632009-11-18 20:39:26 +00005412 // Don't add qualified variants of arrays. For one, they're not allowed
5413 // (the qualifier would sink to the element type), and for another, the
5414 // only overload situation where it matters is subscript or pointer +- int,
5415 // and those shouldn't have qualifier variants anyway.
5416 if (PointeeTy->isArrayType())
5417 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005418 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005419 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005420 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005421 bool hasVolatile = VisibleQuals.hasVolatile();
5422 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005423
John McCall8ccfcb52009-09-24 19:53:00 +00005424 // Iterate through all strict supersets of BaseCVR.
5425 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5426 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005427 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5428 // in the types.
5429 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5430 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005431 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005432 if (!buildObjCPtr)
5433 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5434 else
5435 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005436 }
5437
5438 return true;
5439}
5440
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005441/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5442/// to the set of pointer types along with any more-qualified variants of
5443/// that type. For example, if @p Ty is "int const *", this routine
5444/// will add "int const *", "int const volatile *", "int const
5445/// restrict *", and "int const volatile restrict *" to the set of
5446/// pointer types. Returns true if the add of @p Ty itself succeeded,
5447/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005448///
5449/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005450bool
5451BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5452 QualType Ty) {
5453 // Insert this type.
5454 if (!MemberPointerTypes.insert(Ty))
5455 return false;
5456
John McCall8ccfcb52009-09-24 19:53:00 +00005457 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5458 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005459
John McCall8ccfcb52009-09-24 19:53:00 +00005460 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005461 // Don't add qualified variants of arrays. For one, they're not allowed
5462 // (the qualifier would sink to the element type), and for another, the
5463 // only overload situation where it matters is subscript or pointer +- int,
5464 // and those shouldn't have qualifier variants anyway.
5465 if (PointeeTy->isArrayType())
5466 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005467 const Type *ClassTy = PointerTy->getClass();
5468
5469 // Iterate through all strict supersets of the pointee type's CVR
5470 // qualifiers.
5471 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5472 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5473 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005474
John McCall8ccfcb52009-09-24 19:53:00 +00005475 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005476 MemberPointerTypes.insert(
5477 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005478 }
5479
5480 return true;
5481}
5482
Douglas Gregora11693b2008-11-12 17:17:38 +00005483/// AddTypesConvertedFrom - Add each of the types to which the type @p
5484/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005485/// primarily interested in pointer types and enumeration types. We also
5486/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005487/// AllowUserConversions is true if we should look at the conversion
5488/// functions of a class type, and AllowExplicitConversions if we
5489/// should also include the explicit conversion functions of a class
5490/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005491void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005492BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005493 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005494 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005495 bool AllowExplicitConversions,
5496 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005497 // Only deal with canonical types.
5498 Ty = Context.getCanonicalType(Ty);
5499
5500 // Look through reference types; they aren't part of the type of an
5501 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005502 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005503 Ty = RefTy->getPointeeType();
5504
John McCall33ddac02011-01-19 10:06:00 +00005505 // If we're dealing with an array type, decay to the pointer.
5506 if (Ty->isArrayType())
5507 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5508
5509 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005510 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005511
Chandler Carruth00a38332010-12-13 01:44:01 +00005512 // Flag if we ever add a non-record type.
5513 const RecordType *TyRec = Ty->getAs<RecordType>();
5514 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5515
Chandler Carruth00a38332010-12-13 01:44:01 +00005516 // Flag if we encounter an arithmetic type.
5517 HasArithmeticOrEnumeralTypes =
5518 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5519
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005520 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5521 PointerTypes.insert(Ty);
5522 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005523 // Insert our type, and its more-qualified variants, into the set
5524 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005525 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005526 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005527 } else if (Ty->isMemberPointerType()) {
5528 // Member pointers are far easier, since the pointee can't be converted.
5529 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5530 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005531 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005532 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005533 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005534 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005535 // We treat vector types as arithmetic types in many contexts as an
5536 // extension.
5537 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005538 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005539 } else if (Ty->isNullPtrType()) {
5540 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005541 } else if (AllowUserConversions && TyRec) {
5542 // No conversion functions in incomplete types.
5543 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5544 return;
Mike Stump11289f42009-09-09 15:08:12 +00005545
Chandler Carruth00a38332010-12-13 01:44:01 +00005546 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5547 const UnresolvedSetImpl *Conversions
5548 = ClassDecl->getVisibleConversionFunctions();
5549 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5550 E = Conversions->end(); I != E; ++I) {
5551 NamedDecl *D = I.getDecl();
5552 if (isa<UsingShadowDecl>(D))
5553 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005554
Chandler Carruth00a38332010-12-13 01:44:01 +00005555 // Skip conversion function templates; they don't tell us anything
5556 // about which builtin types we can convert to.
5557 if (isa<FunctionTemplateDecl>(D))
5558 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005559
Chandler Carruth00a38332010-12-13 01:44:01 +00005560 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5561 if (AllowExplicitConversions || !Conv->isExplicit()) {
5562 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5563 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005564 }
5565 }
5566 }
5567}
5568
Douglas Gregor84605ae2009-08-24 13:43:27 +00005569/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5570/// the volatile- and non-volatile-qualified assignment operators for the
5571/// given type to the candidate set.
5572static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5573 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005574 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005575 unsigned NumArgs,
5576 OverloadCandidateSet &CandidateSet) {
5577 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005578
Douglas Gregor84605ae2009-08-24 13:43:27 +00005579 // T& operator=(T&, T)
5580 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5581 ParamTypes[1] = T;
5582 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5583 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005584
Douglas Gregor84605ae2009-08-24 13:43:27 +00005585 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5586 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005587 ParamTypes[0]
5588 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005589 ParamTypes[1] = T;
5590 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005591 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005592 }
5593}
Mike Stump11289f42009-09-09 15:08:12 +00005594
Sebastian Redl1054fae2009-10-25 17:03:50 +00005595/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5596/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005597static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5598 Qualifiers VRQuals;
5599 const RecordType *TyRec;
5600 if (const MemberPointerType *RHSMPType =
5601 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005602 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005603 else
5604 TyRec = ArgExpr->getType()->getAs<RecordType>();
5605 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005606 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005607 VRQuals.addVolatile();
5608 VRQuals.addRestrict();
5609 return VRQuals;
5610 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005611
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005612 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005613 if (!ClassDecl->hasDefinition())
5614 return VRQuals;
5615
John McCallad371252010-01-20 00:46:10 +00005616 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005617 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005618
John McCallad371252010-01-20 00:46:10 +00005619 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005620 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005621 NamedDecl *D = I.getDecl();
5622 if (isa<UsingShadowDecl>(D))
5623 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5624 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005625 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5626 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5627 CanTy = ResTypeRef->getPointeeType();
5628 // Need to go down the pointer/mempointer chain and add qualifiers
5629 // as see them.
5630 bool done = false;
5631 while (!done) {
5632 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5633 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005634 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005635 CanTy->getAs<MemberPointerType>())
5636 CanTy = ResTypeMPtr->getPointeeType();
5637 else
5638 done = true;
5639 if (CanTy.isVolatileQualified())
5640 VRQuals.addVolatile();
5641 if (CanTy.isRestrictQualified())
5642 VRQuals.addRestrict();
5643 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5644 return VRQuals;
5645 }
5646 }
5647 }
5648 return VRQuals;
5649}
John McCall52872982010-11-13 05:51:15 +00005650
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005651namespace {
John McCall52872982010-11-13 05:51:15 +00005652
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005653/// \brief Helper class to manage the addition of builtin operator overload
5654/// candidates. It provides shared state and utility methods used throughout
5655/// the process, as well as a helper method to add each group of builtin
5656/// operator overloads from the standard to a candidate set.
5657class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005658 // Common instance state available to all overload candidate addition methods.
5659 Sema &S;
5660 Expr **Args;
5661 unsigned NumArgs;
5662 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005663 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005664 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005665 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005666
Chandler Carruthc6586e52010-12-12 10:35:00 +00005667 // Define some constants used to index and iterate over the arithemetic types
5668 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005669 // The "promoted arithmetic types" are the arithmetic
5670 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005671 static const unsigned FirstIntegralType = 3;
5672 static const unsigned LastIntegralType = 18;
5673 static const unsigned FirstPromotedIntegralType = 3,
5674 LastPromotedIntegralType = 9;
5675 static const unsigned FirstPromotedArithmeticType = 0,
5676 LastPromotedArithmeticType = 9;
5677 static const unsigned NumArithmeticTypes = 18;
5678
Chandler Carruthc6586e52010-12-12 10:35:00 +00005679 /// \brief Get the canonical type for a given arithmetic type index.
5680 CanQualType getArithmeticType(unsigned index) {
5681 assert(index < NumArithmeticTypes);
5682 static CanQualType ASTContext::* const
5683 ArithmeticTypes[NumArithmeticTypes] = {
5684 // Start of promoted types.
5685 &ASTContext::FloatTy,
5686 &ASTContext::DoubleTy,
5687 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005688
Chandler Carruthc6586e52010-12-12 10:35:00 +00005689 // Start of integral types.
5690 &ASTContext::IntTy,
5691 &ASTContext::LongTy,
5692 &ASTContext::LongLongTy,
5693 &ASTContext::UnsignedIntTy,
5694 &ASTContext::UnsignedLongTy,
5695 &ASTContext::UnsignedLongLongTy,
5696 // End of promoted types.
5697
5698 &ASTContext::BoolTy,
5699 &ASTContext::CharTy,
5700 &ASTContext::WCharTy,
5701 &ASTContext::Char16Ty,
5702 &ASTContext::Char32Ty,
5703 &ASTContext::SignedCharTy,
5704 &ASTContext::ShortTy,
5705 &ASTContext::UnsignedCharTy,
5706 &ASTContext::UnsignedShortTy,
5707 // End of integral types.
5708 // FIXME: What about complex?
5709 };
5710 return S.Context.*ArithmeticTypes[index];
5711 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005712
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005713 /// \brief Gets the canonical type resulting from the usual arithemetic
5714 /// converions for the given arithmetic types.
5715 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5716 // Accelerator table for performing the usual arithmetic conversions.
5717 // The rules are basically:
5718 // - if either is floating-point, use the wider floating-point
5719 // - if same signedness, use the higher rank
5720 // - if same size, use unsigned of the higher rank
5721 // - use the larger type
5722 // These rules, together with the axiom that higher ranks are
5723 // never smaller, are sufficient to precompute all of these results
5724 // *except* when dealing with signed types of higher rank.
5725 // (we could precompute SLL x UI for all known platforms, but it's
5726 // better not to make any assumptions).
5727 enum PromotedType {
5728 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5729 };
5730 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5731 [LastPromotedArithmeticType] = {
5732 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5733 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5734 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5735 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5736 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5737 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5738 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5739 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5740 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5741 };
5742
5743 assert(L < LastPromotedArithmeticType);
5744 assert(R < LastPromotedArithmeticType);
5745 int Idx = ConversionsTable[L][R];
5746
5747 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005748 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005749
5750 // Slow path: we need to compare widths.
5751 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005752 CanQualType LT = getArithmeticType(L),
5753 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005754 unsigned LW = S.Context.getIntWidth(LT),
5755 RW = S.Context.getIntWidth(RT);
5756
5757 // If they're different widths, use the signed type.
5758 if (LW > RW) return LT;
5759 else if (LW < RW) return RT;
5760
5761 // Otherwise, use the unsigned type of the signed type's rank.
5762 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5763 assert(L == SLL || R == SLL);
5764 return S.Context.UnsignedLongLongTy;
5765 }
5766
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005767 /// \brief Helper method to factor out the common pattern of adding overloads
5768 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005769 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5770 bool HasVolatile) {
5771 QualType ParamTypes[2] = {
5772 S.Context.getLValueReferenceType(CandidateTy),
5773 S.Context.IntTy
5774 };
5775
5776 // Non-volatile version.
5777 if (NumArgs == 1)
5778 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5779 else
5780 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5781
5782 // Use a heuristic to reduce number of builtin candidates in the set:
5783 // add volatile version only if there are conversions to a volatile type.
5784 if (HasVolatile) {
5785 ParamTypes[0] =
5786 S.Context.getLValueReferenceType(
5787 S.Context.getVolatileType(CandidateTy));
5788 if (NumArgs == 1)
5789 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5790 else
5791 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5792 }
5793 }
5794
5795public:
5796 BuiltinOperatorOverloadBuilder(
5797 Sema &S, Expr **Args, unsigned NumArgs,
5798 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005799 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005800 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005801 OverloadCandidateSet &CandidateSet)
5802 : S(S), Args(Args), NumArgs(NumArgs),
5803 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005804 HasArithmeticOrEnumeralCandidateType(
5805 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005806 CandidateTypes(CandidateTypes),
5807 CandidateSet(CandidateSet) {
5808 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005809 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005810 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005811 assert(getArithmeticType(LastPromotedIntegralType - 1)
5812 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005813 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005814 assert(getArithmeticType(FirstPromotedArithmeticType)
5815 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005816 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005817 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5818 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005819 "Invalid last promoted arithmetic type");
5820 }
5821
5822 // C++ [over.built]p3:
5823 //
5824 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5825 // is either volatile or empty, there exist candidate operator
5826 // functions of the form
5827 //
5828 // VQ T& operator++(VQ T&);
5829 // T operator++(VQ T&, int);
5830 //
5831 // C++ [over.built]p4:
5832 //
5833 // For every pair (T, VQ), where T is an arithmetic type other
5834 // than bool, and VQ is either volatile or empty, there exist
5835 // candidate operator functions of the form
5836 //
5837 // VQ T& operator--(VQ T&);
5838 // T operator--(VQ T&, int);
5839 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005840 if (!HasArithmeticOrEnumeralCandidateType)
5841 return;
5842
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005843 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5844 Arith < NumArithmeticTypes; ++Arith) {
5845 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005846 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005847 VisibleTypeConversionsQuals.hasVolatile());
5848 }
5849 }
5850
5851 // C++ [over.built]p5:
5852 //
5853 // For every pair (T, VQ), where T is a cv-qualified or
5854 // cv-unqualified object type, and VQ is either volatile or
5855 // empty, there exist candidate operator functions of the form
5856 //
5857 // T*VQ& operator++(T*VQ&);
5858 // T*VQ& operator--(T*VQ&);
5859 // T* operator++(T*VQ&, int);
5860 // T* operator--(T*VQ&, int);
5861 void addPlusPlusMinusMinusPointerOverloads() {
5862 for (BuiltinCandidateTypeSet::iterator
5863 Ptr = CandidateTypes[0].pointer_begin(),
5864 PtrEnd = CandidateTypes[0].pointer_end();
5865 Ptr != PtrEnd; ++Ptr) {
5866 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005867 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005868 continue;
5869
5870 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5871 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5872 VisibleTypeConversionsQuals.hasVolatile()));
5873 }
5874 }
5875
5876 // C++ [over.built]p6:
5877 // For every cv-qualified or cv-unqualified object type T, there
5878 // exist candidate operator functions of the form
5879 //
5880 // T& operator*(T*);
5881 //
5882 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005883 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005884 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005885 // T& operator*(T*);
5886 void addUnaryStarPointerOverloads() {
5887 for (BuiltinCandidateTypeSet::iterator
5888 Ptr = CandidateTypes[0].pointer_begin(),
5889 PtrEnd = CandidateTypes[0].pointer_end();
5890 Ptr != PtrEnd; ++Ptr) {
5891 QualType ParamTy = *Ptr;
5892 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005893 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5894 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005895
Douglas Gregor02824322011-01-26 19:30:28 +00005896 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5897 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5898 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005899
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005900 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5901 &ParamTy, Args, 1, CandidateSet);
5902 }
5903 }
5904
5905 // C++ [over.built]p9:
5906 // For every promoted arithmetic type T, there exist candidate
5907 // operator functions of the form
5908 //
5909 // T operator+(T);
5910 // T operator-(T);
5911 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005912 if (!HasArithmeticOrEnumeralCandidateType)
5913 return;
5914
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005915 for (unsigned Arith = FirstPromotedArithmeticType;
5916 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005917 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005918 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5919 }
5920
5921 // Extension: We also add these operators for vector types.
5922 for (BuiltinCandidateTypeSet::iterator
5923 Vec = CandidateTypes[0].vector_begin(),
5924 VecEnd = CandidateTypes[0].vector_end();
5925 Vec != VecEnd; ++Vec) {
5926 QualType VecTy = *Vec;
5927 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5928 }
5929 }
5930
5931 // C++ [over.built]p8:
5932 // For every type T, there exist candidate operator functions of
5933 // the form
5934 //
5935 // T* operator+(T*);
5936 void addUnaryPlusPointerOverloads() {
5937 for (BuiltinCandidateTypeSet::iterator
5938 Ptr = CandidateTypes[0].pointer_begin(),
5939 PtrEnd = CandidateTypes[0].pointer_end();
5940 Ptr != PtrEnd; ++Ptr) {
5941 QualType ParamTy = *Ptr;
5942 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5943 }
5944 }
5945
5946 // C++ [over.built]p10:
5947 // For every promoted integral type T, there exist candidate
5948 // operator functions of the form
5949 //
5950 // T operator~(T);
5951 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005952 if (!HasArithmeticOrEnumeralCandidateType)
5953 return;
5954
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005955 for (unsigned Int = FirstPromotedIntegralType;
5956 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005957 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005958 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5959 }
5960
5961 // Extension: We also add this operator for vector types.
5962 for (BuiltinCandidateTypeSet::iterator
5963 Vec = CandidateTypes[0].vector_begin(),
5964 VecEnd = CandidateTypes[0].vector_end();
5965 Vec != VecEnd; ++Vec) {
5966 QualType VecTy = *Vec;
5967 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5968 }
5969 }
5970
5971 // C++ [over.match.oper]p16:
5972 // For every pointer to member type T, there exist candidate operator
5973 // functions of the form
5974 //
5975 // bool operator==(T,T);
5976 // bool operator!=(T,T);
5977 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5978 /// Set of (canonical) types that we've already handled.
5979 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5980
5981 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5982 for (BuiltinCandidateTypeSet::iterator
5983 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5984 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5985 MemPtr != MemPtrEnd;
5986 ++MemPtr) {
5987 // Don't add the same builtin candidate twice.
5988 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5989 continue;
5990
5991 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5992 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5993 CandidateSet);
5994 }
5995 }
5996 }
5997
5998 // C++ [over.built]p15:
5999 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006000 // For every T, where T is an enumeration type, a pointer type, or
6001 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006002 //
6003 // bool operator<(T, T);
6004 // bool operator>(T, T);
6005 // bool operator<=(T, T);
6006 // bool operator>=(T, T);
6007 // bool operator==(T, T);
6008 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006009 void addRelationalPointerOrEnumeralOverloads() {
6010 // C++ [over.built]p1:
6011 // If there is a user-written candidate with the same name and parameter
6012 // types as a built-in candidate operator function, the built-in operator
6013 // function is hidden and is not included in the set of candidate
6014 // functions.
6015 //
6016 // The text is actually in a note, but if we don't implement it then we end
6017 // up with ambiguities when the user provides an overloaded operator for
6018 // an enumeration type. Note that only enumeration types have this problem,
6019 // so we track which enumeration types we've seen operators for. Also, the
6020 // only other overloaded operator with enumeration argumenst, operator=,
6021 // cannot be overloaded for enumeration types, so this is the only place
6022 // where we must suppress candidates like this.
6023 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6024 UserDefinedBinaryOperators;
6025
6026 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6027 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6028 CandidateTypes[ArgIdx].enumeration_end()) {
6029 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6030 CEnd = CandidateSet.end();
6031 C != CEnd; ++C) {
6032 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6033 continue;
6034
6035 QualType FirstParamType =
6036 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6037 QualType SecondParamType =
6038 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6039
6040 // Skip if either parameter isn't of enumeral type.
6041 if (!FirstParamType->isEnumeralType() ||
6042 !SecondParamType->isEnumeralType())
6043 continue;
6044
6045 // Add this operator to the set of known user-defined operators.
6046 UserDefinedBinaryOperators.insert(
6047 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6048 S.Context.getCanonicalType(SecondParamType)));
6049 }
6050 }
6051 }
6052
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006053 /// Set of (canonical) types that we've already handled.
6054 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6055
6056 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6057 for (BuiltinCandidateTypeSet::iterator
6058 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6059 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6060 Ptr != PtrEnd; ++Ptr) {
6061 // Don't add the same builtin candidate twice.
6062 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6063 continue;
6064
6065 QualType ParamTypes[2] = { *Ptr, *Ptr };
6066 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6067 CandidateSet);
6068 }
6069 for (BuiltinCandidateTypeSet::iterator
6070 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6071 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6072 Enum != EnumEnd; ++Enum) {
6073 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6074
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006075 // Don't add the same builtin candidate twice, or if a user defined
6076 // candidate exists.
6077 if (!AddedTypes.insert(CanonType) ||
6078 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6079 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006080 continue;
6081
6082 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006083 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6084 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006085 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006086
6087 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6088 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6089 if (AddedTypes.insert(NullPtrTy) &&
6090 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6091 NullPtrTy))) {
6092 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6093 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6094 CandidateSet);
6095 }
6096 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006097 }
6098 }
6099
6100 // C++ [over.built]p13:
6101 //
6102 // For every cv-qualified or cv-unqualified object type T
6103 // there exist candidate operator functions of the form
6104 //
6105 // T* operator+(T*, ptrdiff_t);
6106 // T& operator[](T*, ptrdiff_t); [BELOW]
6107 // T* operator-(T*, ptrdiff_t);
6108 // T* operator+(ptrdiff_t, T*);
6109 // T& operator[](ptrdiff_t, T*); [BELOW]
6110 //
6111 // C++ [over.built]p14:
6112 //
6113 // For every T, where T is a pointer to object type, there
6114 // exist candidate operator functions of the form
6115 //
6116 // ptrdiff_t operator-(T, T);
6117 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6118 /// Set of (canonical) types that we've already handled.
6119 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6120
6121 for (int Arg = 0; Arg < 2; ++Arg) {
6122 QualType AsymetricParamTypes[2] = {
6123 S.Context.getPointerDiffType(),
6124 S.Context.getPointerDiffType(),
6125 };
6126 for (BuiltinCandidateTypeSet::iterator
6127 Ptr = CandidateTypes[Arg].pointer_begin(),
6128 PtrEnd = CandidateTypes[Arg].pointer_end();
6129 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006130 QualType PointeeTy = (*Ptr)->getPointeeType();
6131 if (!PointeeTy->isObjectType())
6132 continue;
6133
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006134 AsymetricParamTypes[Arg] = *Ptr;
6135 if (Arg == 0 || Op == OO_Plus) {
6136 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6137 // T* operator+(ptrdiff_t, T*);
6138 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6139 CandidateSet);
6140 }
6141 if (Op == OO_Minus) {
6142 // ptrdiff_t operator-(T, T);
6143 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6144 continue;
6145
6146 QualType ParamTypes[2] = { *Ptr, *Ptr };
6147 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6148 Args, 2, CandidateSet);
6149 }
6150 }
6151 }
6152 }
6153
6154 // C++ [over.built]p12:
6155 //
6156 // For every pair of promoted arithmetic types L and R, there
6157 // exist candidate operator functions of the form
6158 //
6159 // LR operator*(L, R);
6160 // LR operator/(L, R);
6161 // LR operator+(L, R);
6162 // LR operator-(L, R);
6163 // bool operator<(L, R);
6164 // bool operator>(L, R);
6165 // bool operator<=(L, R);
6166 // bool operator>=(L, R);
6167 // bool operator==(L, R);
6168 // bool operator!=(L, R);
6169 //
6170 // where LR is the result of the usual arithmetic conversions
6171 // between types L and R.
6172 //
6173 // C++ [over.built]p24:
6174 //
6175 // For every pair of promoted arithmetic types L and R, there exist
6176 // candidate operator functions of the form
6177 //
6178 // LR operator?(bool, L, R);
6179 //
6180 // where LR is the result of the usual arithmetic conversions
6181 // between types L and R.
6182 // Our candidates ignore the first parameter.
6183 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006184 if (!HasArithmeticOrEnumeralCandidateType)
6185 return;
6186
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006187 for (unsigned Left = FirstPromotedArithmeticType;
6188 Left < LastPromotedArithmeticType; ++Left) {
6189 for (unsigned Right = FirstPromotedArithmeticType;
6190 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006191 QualType LandR[2] = { getArithmeticType(Left),
6192 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006193 QualType Result =
6194 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006195 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006196 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6197 }
6198 }
6199
6200 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6201 // conditional operator for vector types.
6202 for (BuiltinCandidateTypeSet::iterator
6203 Vec1 = CandidateTypes[0].vector_begin(),
6204 Vec1End = CandidateTypes[0].vector_end();
6205 Vec1 != Vec1End; ++Vec1) {
6206 for (BuiltinCandidateTypeSet::iterator
6207 Vec2 = CandidateTypes[1].vector_begin(),
6208 Vec2End = CandidateTypes[1].vector_end();
6209 Vec2 != Vec2End; ++Vec2) {
6210 QualType LandR[2] = { *Vec1, *Vec2 };
6211 QualType Result = S.Context.BoolTy;
6212 if (!isComparison) {
6213 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6214 Result = *Vec1;
6215 else
6216 Result = *Vec2;
6217 }
6218
6219 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6220 }
6221 }
6222 }
6223
6224 // C++ [over.built]p17:
6225 //
6226 // For every pair of promoted integral types L and R, there
6227 // exist candidate operator functions of the form
6228 //
6229 // LR operator%(L, R);
6230 // LR operator&(L, R);
6231 // LR operator^(L, R);
6232 // LR operator|(L, R);
6233 // L operator<<(L, R);
6234 // L operator>>(L, R);
6235 //
6236 // where LR is the result of the usual arithmetic conversions
6237 // between types L and R.
6238 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006239 if (!HasArithmeticOrEnumeralCandidateType)
6240 return;
6241
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006242 for (unsigned Left = FirstPromotedIntegralType;
6243 Left < LastPromotedIntegralType; ++Left) {
6244 for (unsigned Right = FirstPromotedIntegralType;
6245 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006246 QualType LandR[2] = { getArithmeticType(Left),
6247 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006248 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6249 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006250 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006251 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6252 }
6253 }
6254 }
6255
6256 // C++ [over.built]p20:
6257 //
6258 // For every pair (T, VQ), where T is an enumeration or
6259 // pointer to member type and VQ is either volatile or
6260 // empty, there exist candidate operator functions of the form
6261 //
6262 // VQ T& operator=(VQ T&, T);
6263 void addAssignmentMemberPointerOrEnumeralOverloads() {
6264 /// Set of (canonical) types that we've already handled.
6265 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6266
6267 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6268 for (BuiltinCandidateTypeSet::iterator
6269 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6270 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6271 Enum != EnumEnd; ++Enum) {
6272 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6273 continue;
6274
6275 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6276 CandidateSet);
6277 }
6278
6279 for (BuiltinCandidateTypeSet::iterator
6280 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6281 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6282 MemPtr != MemPtrEnd; ++MemPtr) {
6283 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6284 continue;
6285
6286 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6287 CandidateSet);
6288 }
6289 }
6290 }
6291
6292 // C++ [over.built]p19:
6293 //
6294 // For every pair (T, VQ), where T is any type and VQ is either
6295 // volatile or empty, there exist candidate operator functions
6296 // of the form
6297 //
6298 // T*VQ& operator=(T*VQ&, T*);
6299 //
6300 // C++ [over.built]p21:
6301 //
6302 // For every pair (T, VQ), where T is a cv-qualified or
6303 // cv-unqualified object type and VQ is either volatile or
6304 // empty, there exist candidate operator functions of the form
6305 //
6306 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6307 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6308 void addAssignmentPointerOverloads(bool isEqualOp) {
6309 /// Set of (canonical) types that we've already handled.
6310 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6311
6312 for (BuiltinCandidateTypeSet::iterator
6313 Ptr = CandidateTypes[0].pointer_begin(),
6314 PtrEnd = CandidateTypes[0].pointer_end();
6315 Ptr != PtrEnd; ++Ptr) {
6316 // If this is operator=, keep track of the builtin candidates we added.
6317 if (isEqualOp)
6318 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006319 else if (!(*Ptr)->getPointeeType()->isObjectType())
6320 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006321
6322 // non-volatile version
6323 QualType ParamTypes[2] = {
6324 S.Context.getLValueReferenceType(*Ptr),
6325 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6326 };
6327 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6328 /*IsAssigmentOperator=*/ isEqualOp);
6329
6330 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6331 VisibleTypeConversionsQuals.hasVolatile()) {
6332 // volatile version
6333 ParamTypes[0] =
6334 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6335 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6336 /*IsAssigmentOperator=*/isEqualOp);
6337 }
6338 }
6339
6340 if (isEqualOp) {
6341 for (BuiltinCandidateTypeSet::iterator
6342 Ptr = CandidateTypes[1].pointer_begin(),
6343 PtrEnd = CandidateTypes[1].pointer_end();
6344 Ptr != PtrEnd; ++Ptr) {
6345 // Make sure we don't add the same candidate twice.
6346 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6347 continue;
6348
Chandler Carruth8e543b32010-12-12 08:17:55 +00006349 QualType ParamTypes[2] = {
6350 S.Context.getLValueReferenceType(*Ptr),
6351 *Ptr,
6352 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006353
6354 // non-volatile version
6355 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6356 /*IsAssigmentOperator=*/true);
6357
6358 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6359 VisibleTypeConversionsQuals.hasVolatile()) {
6360 // volatile version
6361 ParamTypes[0] =
6362 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006363 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6364 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006365 }
6366 }
6367 }
6368 }
6369
6370 // C++ [over.built]p18:
6371 //
6372 // For every triple (L, VQ, R), where L is an arithmetic type,
6373 // VQ is either volatile or empty, and R is a promoted
6374 // arithmetic type, there exist candidate operator functions of
6375 // the form
6376 //
6377 // VQ L& operator=(VQ L&, R);
6378 // VQ L& operator*=(VQ L&, R);
6379 // VQ L& operator/=(VQ L&, R);
6380 // VQ L& operator+=(VQ L&, R);
6381 // VQ L& operator-=(VQ L&, R);
6382 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006383 if (!HasArithmeticOrEnumeralCandidateType)
6384 return;
6385
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006386 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6387 for (unsigned Right = FirstPromotedArithmeticType;
6388 Right < LastPromotedArithmeticType; ++Right) {
6389 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006390 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006391
6392 // Add this built-in operator as a candidate (VQ is empty).
6393 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006394 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006395 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6396 /*IsAssigmentOperator=*/isEqualOp);
6397
6398 // Add this built-in operator as a candidate (VQ is 'volatile').
6399 if (VisibleTypeConversionsQuals.hasVolatile()) {
6400 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006401 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006402 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006403 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6404 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006405 /*IsAssigmentOperator=*/isEqualOp);
6406 }
6407 }
6408 }
6409
6410 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6411 for (BuiltinCandidateTypeSet::iterator
6412 Vec1 = CandidateTypes[0].vector_begin(),
6413 Vec1End = CandidateTypes[0].vector_end();
6414 Vec1 != Vec1End; ++Vec1) {
6415 for (BuiltinCandidateTypeSet::iterator
6416 Vec2 = CandidateTypes[1].vector_begin(),
6417 Vec2End = CandidateTypes[1].vector_end();
6418 Vec2 != Vec2End; ++Vec2) {
6419 QualType ParamTypes[2];
6420 ParamTypes[1] = *Vec2;
6421 // Add this built-in operator as a candidate (VQ is empty).
6422 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6423 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6424 /*IsAssigmentOperator=*/isEqualOp);
6425
6426 // Add this built-in operator as a candidate (VQ is 'volatile').
6427 if (VisibleTypeConversionsQuals.hasVolatile()) {
6428 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6429 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006430 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6431 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006432 /*IsAssigmentOperator=*/isEqualOp);
6433 }
6434 }
6435 }
6436 }
6437
6438 // C++ [over.built]p22:
6439 //
6440 // For every triple (L, VQ, R), where L is an integral type, VQ
6441 // is either volatile or empty, and R is a promoted integral
6442 // type, there exist candidate operator functions of the form
6443 //
6444 // VQ L& operator%=(VQ L&, R);
6445 // VQ L& operator<<=(VQ L&, R);
6446 // VQ L& operator>>=(VQ L&, R);
6447 // VQ L& operator&=(VQ L&, R);
6448 // VQ L& operator^=(VQ L&, R);
6449 // VQ L& operator|=(VQ L&, R);
6450 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006451 if (!HasArithmeticOrEnumeralCandidateType)
6452 return;
6453
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006454 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6455 for (unsigned Right = FirstPromotedIntegralType;
6456 Right < LastPromotedIntegralType; ++Right) {
6457 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006458 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006459
6460 // Add this built-in operator as a candidate (VQ is empty).
6461 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006462 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006463 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6464 if (VisibleTypeConversionsQuals.hasVolatile()) {
6465 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006466 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006467 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6468 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6469 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6470 CandidateSet);
6471 }
6472 }
6473 }
6474 }
6475
6476 // C++ [over.operator]p23:
6477 //
6478 // There also exist candidate operator functions of the form
6479 //
6480 // bool operator!(bool);
6481 // bool operator&&(bool, bool);
6482 // bool operator||(bool, bool);
6483 void addExclaimOverload() {
6484 QualType ParamTy = S.Context.BoolTy;
6485 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6486 /*IsAssignmentOperator=*/false,
6487 /*NumContextualBoolArguments=*/1);
6488 }
6489 void addAmpAmpOrPipePipeOverload() {
6490 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6491 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6492 /*IsAssignmentOperator=*/false,
6493 /*NumContextualBoolArguments=*/2);
6494 }
6495
6496 // C++ [over.built]p13:
6497 //
6498 // For every cv-qualified or cv-unqualified object type T there
6499 // exist candidate operator functions of the form
6500 //
6501 // T* operator+(T*, ptrdiff_t); [ABOVE]
6502 // T& operator[](T*, ptrdiff_t);
6503 // T* operator-(T*, ptrdiff_t); [ABOVE]
6504 // T* operator+(ptrdiff_t, T*); [ABOVE]
6505 // T& operator[](ptrdiff_t, T*);
6506 void addSubscriptOverloads() {
6507 for (BuiltinCandidateTypeSet::iterator
6508 Ptr = CandidateTypes[0].pointer_begin(),
6509 PtrEnd = CandidateTypes[0].pointer_end();
6510 Ptr != PtrEnd; ++Ptr) {
6511 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6512 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006513 if (!PointeeType->isObjectType())
6514 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006515
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006516 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6517
6518 // T& operator[](T*, ptrdiff_t)
6519 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6520 }
6521
6522 for (BuiltinCandidateTypeSet::iterator
6523 Ptr = CandidateTypes[1].pointer_begin(),
6524 PtrEnd = CandidateTypes[1].pointer_end();
6525 Ptr != PtrEnd; ++Ptr) {
6526 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6527 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006528 if (!PointeeType->isObjectType())
6529 continue;
6530
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006531 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6532
6533 // T& operator[](ptrdiff_t, T*)
6534 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6535 }
6536 }
6537
6538 // C++ [over.built]p11:
6539 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6540 // C1 is the same type as C2 or is a derived class of C2, T is an object
6541 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6542 // there exist candidate operator functions of the form
6543 //
6544 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6545 //
6546 // where CV12 is the union of CV1 and CV2.
6547 void addArrowStarOverloads() {
6548 for (BuiltinCandidateTypeSet::iterator
6549 Ptr = CandidateTypes[0].pointer_begin(),
6550 PtrEnd = CandidateTypes[0].pointer_end();
6551 Ptr != PtrEnd; ++Ptr) {
6552 QualType C1Ty = (*Ptr);
6553 QualType C1;
6554 QualifierCollector Q1;
6555 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6556 if (!isa<RecordType>(C1))
6557 continue;
6558 // heuristic to reduce number of builtin candidates in the set.
6559 // Add volatile/restrict version only if there are conversions to a
6560 // volatile/restrict type.
6561 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6562 continue;
6563 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6564 continue;
6565 for (BuiltinCandidateTypeSet::iterator
6566 MemPtr = CandidateTypes[1].member_pointer_begin(),
6567 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6568 MemPtr != MemPtrEnd; ++MemPtr) {
6569 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6570 QualType C2 = QualType(mptr->getClass(), 0);
6571 C2 = C2.getUnqualifiedType();
6572 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6573 break;
6574 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6575 // build CV12 T&
6576 QualType T = mptr->getPointeeType();
6577 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6578 T.isVolatileQualified())
6579 continue;
6580 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6581 T.isRestrictQualified())
6582 continue;
6583 T = Q1.apply(S.Context, T);
6584 QualType ResultTy = S.Context.getLValueReferenceType(T);
6585 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6586 }
6587 }
6588 }
6589
6590 // Note that we don't consider the first argument, since it has been
6591 // contextually converted to bool long ago. The candidates below are
6592 // therefore added as binary.
6593 //
6594 // C++ [over.built]p25:
6595 // For every type T, where T is a pointer, pointer-to-member, or scoped
6596 // enumeration type, there exist candidate operator functions of the form
6597 //
6598 // T operator?(bool, T, T);
6599 //
6600 void addConditionalOperatorOverloads() {
6601 /// Set of (canonical) types that we've already handled.
6602 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6603
6604 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6605 for (BuiltinCandidateTypeSet::iterator
6606 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6607 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6608 Ptr != PtrEnd; ++Ptr) {
6609 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6610 continue;
6611
6612 QualType ParamTypes[2] = { *Ptr, *Ptr };
6613 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6614 }
6615
6616 for (BuiltinCandidateTypeSet::iterator
6617 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6618 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6619 MemPtr != MemPtrEnd; ++MemPtr) {
6620 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6621 continue;
6622
6623 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6624 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6625 }
6626
6627 if (S.getLangOptions().CPlusPlus0x) {
6628 for (BuiltinCandidateTypeSet::iterator
6629 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6630 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6631 Enum != EnumEnd; ++Enum) {
6632 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6633 continue;
6634
6635 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6636 continue;
6637
6638 QualType ParamTypes[2] = { *Enum, *Enum };
6639 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6640 }
6641 }
6642 }
6643 }
6644};
6645
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006646} // end anonymous namespace
6647
6648/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6649/// operator overloads to the candidate set (C++ [over.built]), based
6650/// on the operator @p Op and the arguments given. For example, if the
6651/// operator is a binary '+', this routine might add "int
6652/// operator+(int, int)" to cover integer addition.
6653void
6654Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6655 SourceLocation OpLoc,
6656 Expr **Args, unsigned NumArgs,
6657 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006658 // Find all of the types that the arguments can convert to, but only
6659 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006660 // that make use of these types. Also record whether we encounter non-record
6661 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006662 Qualifiers VisibleTypeConversionsQuals;
6663 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006664 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6665 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006666
6667 bool HasNonRecordCandidateType = false;
6668 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006669 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006670 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6671 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6672 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6673 OpLoc,
6674 true,
6675 (Op == OO_Exclaim ||
6676 Op == OO_AmpAmp ||
6677 Op == OO_PipePipe),
6678 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006679 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6680 CandidateTypes[ArgIdx].hasNonRecordTypes();
6681 HasArithmeticOrEnumeralCandidateType =
6682 HasArithmeticOrEnumeralCandidateType ||
6683 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006684 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006685
Chandler Carruth00a38332010-12-13 01:44:01 +00006686 // Exit early when no non-record types have been added to the candidate set
6687 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00006688 //
6689 // We can't exit early for !, ||, or &&, since there we have always have
6690 // 'bool' overloads.
6691 if (!HasNonRecordCandidateType &&
6692 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00006693 return;
6694
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006695 // Setup an object to manage the common state for building overloads.
6696 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6697 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006698 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006699 CandidateTypes, CandidateSet);
6700
6701 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006702 switch (Op) {
6703 case OO_None:
6704 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00006705 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00006706
Chandler Carruth5184de02010-12-12 08:51:33 +00006707 case OO_New:
6708 case OO_Delete:
6709 case OO_Array_New:
6710 case OO_Array_Delete:
6711 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00006712 llvm_unreachable(
6713 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00006714
6715 case OO_Comma:
6716 case OO_Arrow:
6717 // C++ [over.match.oper]p3:
6718 // -- For the operator ',', the unary operator '&', or the
6719 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006720 break;
6721
6722 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006723 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006724 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006725 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006726
6727 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006728 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006729 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006730 } else {
6731 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6732 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6733 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006734 break;
6735
Chandler Carruth5184de02010-12-12 08:51:33 +00006736 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006737 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006738 OpBuilder.addUnaryStarPointerOverloads();
6739 else
6740 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6741 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006742
Chandler Carruth5184de02010-12-12 08:51:33 +00006743 case OO_Slash:
6744 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006745 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006746
6747 case OO_PlusPlus:
6748 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006749 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6750 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006751 break;
6752
Douglas Gregor84605ae2009-08-24 13:43:27 +00006753 case OO_EqualEqual:
6754 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006755 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006756 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006757
Douglas Gregora11693b2008-11-12 17:17:38 +00006758 case OO_Less:
6759 case OO_Greater:
6760 case OO_LessEqual:
6761 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006762 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006763 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6764 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006765
Douglas Gregora11693b2008-11-12 17:17:38 +00006766 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006767 case OO_Caret:
6768 case OO_Pipe:
6769 case OO_LessLess:
6770 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006771 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006772 break;
6773
Chandler Carruth5184de02010-12-12 08:51:33 +00006774 case OO_Amp: // '&' is either unary or binary
6775 if (NumArgs == 1)
6776 // C++ [over.match.oper]p3:
6777 // -- For the operator ',', the unary operator '&', or the
6778 // operator '->', the built-in candidates set is empty.
6779 break;
6780
6781 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6782 break;
6783
6784 case OO_Tilde:
6785 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6786 break;
6787
Douglas Gregora11693b2008-11-12 17:17:38 +00006788 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006789 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006790 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006791
6792 case OO_PlusEqual:
6793 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006794 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006795 // Fall through.
6796
6797 case OO_StarEqual:
6798 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006799 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006800 break;
6801
6802 case OO_PercentEqual:
6803 case OO_LessLessEqual:
6804 case OO_GreaterGreaterEqual:
6805 case OO_AmpEqual:
6806 case OO_CaretEqual:
6807 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006808 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006809 break;
6810
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006811 case OO_Exclaim:
6812 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006813 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006814
Douglas Gregora11693b2008-11-12 17:17:38 +00006815 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006816 case OO_PipePipe:
6817 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006818 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006819
6820 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006821 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006822 break;
6823
6824 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006825 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006826 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006827
6828 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006829 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006830 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6831 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006832 }
6833}
6834
Douglas Gregore254f902009-02-04 00:32:51 +00006835/// \brief Add function candidates found via argument-dependent lookup
6836/// to the set of overloading candidates.
6837///
6838/// This routine performs argument-dependent name lookup based on the
6839/// given function name (which may also be an operator name) and adds
6840/// all of the overload candidates found by ADL to the overload
6841/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006842void
Douglas Gregore254f902009-02-04 00:32:51 +00006843Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006844 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006845 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006846 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006847 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006848 bool PartialOverloading,
6849 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006850 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006851
John McCall91f61fc2010-01-26 06:04:06 +00006852 // FIXME: This approach for uniquing ADL results (and removing
6853 // redundant candidates from the set) relies on pointer-equality,
6854 // which means we need to key off the canonical decl. However,
6855 // always going back to the canonical decl might not get us the
6856 // right set of default arguments. What default arguments are
6857 // we supposed to consider on ADL candidates, anyway?
6858
Douglas Gregorcabea402009-09-22 15:41:20 +00006859 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006860 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6861 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006862
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006863 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006864 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6865 CandEnd = CandidateSet.end();
6866 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006867 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006868 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006869 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006870 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006871 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006872
6873 // For each of the ADL candidates we found, add it to the overload
6874 // set.
John McCall8fe68082010-01-26 07:16:45 +00006875 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006876 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006877 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006878 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006879 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006880
John McCalla0296f72010-03-19 07:35:19 +00006881 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006882 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006883 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006884 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006885 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006886 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006887 }
Douglas Gregore254f902009-02-04 00:32:51 +00006888}
6889
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006890/// isBetterOverloadCandidate - Determines whether the first overload
6891/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006892bool
John McCall5c32be02010-08-24 20:38:10 +00006893isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006894 const OverloadCandidate &Cand1,
6895 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006896 SourceLocation Loc,
6897 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006898 // Define viable functions to be better candidates than non-viable
6899 // functions.
6900 if (!Cand2.Viable)
6901 return Cand1.Viable;
6902 else if (!Cand1.Viable)
6903 return false;
6904
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006905 // C++ [over.match.best]p1:
6906 //
6907 // -- if F is a static member function, ICS1(F) is defined such
6908 // that ICS1(F) is neither better nor worse than ICS1(G) for
6909 // any function G, and, symmetrically, ICS1(G) is neither
6910 // better nor worse than ICS1(F).
6911 unsigned StartArg = 0;
6912 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6913 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006914
Douglas Gregord3cb3562009-07-07 23:38:56 +00006915 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006916 // A viable function F1 is defined to be a better function than another
6917 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006918 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006919 unsigned NumArgs = Cand1.Conversions.size();
6920 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6921 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006922 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006923 switch (CompareImplicitConversionSequences(S,
6924 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006925 Cand2.Conversions[ArgIdx])) {
6926 case ImplicitConversionSequence::Better:
6927 // Cand1 has a better conversion sequence.
6928 HasBetterConversion = true;
6929 break;
6930
6931 case ImplicitConversionSequence::Worse:
6932 // Cand1 can't be better than Cand2.
6933 return false;
6934
6935 case ImplicitConversionSequence::Indistinguishable:
6936 // Do nothing.
6937 break;
6938 }
6939 }
6940
Mike Stump11289f42009-09-09 15:08:12 +00006941 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006942 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006943 if (HasBetterConversion)
6944 return true;
6945
Mike Stump11289f42009-09-09 15:08:12 +00006946 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006947 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006948 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006949 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6950 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006951
6952 // -- F1 and F2 are function template specializations, and the function
6953 // template for F1 is more specialized than the template for F2
6954 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006955 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006956 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006957 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006958 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006959 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6960 Cand2.Function->getPrimaryTemplate(),
6961 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006962 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006963 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006964 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006965 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006966 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006967
Douglas Gregora1f013e2008-11-07 22:36:19 +00006968 // -- the context is an initialization by user-defined conversion
6969 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6970 // from the return type of F1 to the destination type (i.e.,
6971 // the type of the entity being initialized) is a better
6972 // conversion sequence than the standard conversion sequence
6973 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006974 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006975 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006976 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006977 switch (CompareStandardConversionSequences(S,
6978 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006979 Cand2.FinalConversion)) {
6980 case ImplicitConversionSequence::Better:
6981 // Cand1 has a better conversion sequence.
6982 return true;
6983
6984 case ImplicitConversionSequence::Worse:
6985 // Cand1 can't be better than Cand2.
6986 return false;
6987
6988 case ImplicitConversionSequence::Indistinguishable:
6989 // Do nothing
6990 break;
6991 }
6992 }
6993
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006994 return false;
6995}
6996
Mike Stump11289f42009-09-09 15:08:12 +00006997/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006998/// within an overload candidate set.
6999///
7000/// \param CandidateSet the set of candidate functions.
7001///
7002/// \param Loc the location of the function name (or operator symbol) for
7003/// which overload resolution occurs.
7004///
Mike Stump11289f42009-09-09 15:08:12 +00007005/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007006/// function, Best points to the candidate function found.
7007///
7008/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007009OverloadingResult
7010OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007011 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007012 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007013 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007014 Best = end();
7015 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7016 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007017 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007018 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007019 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007020 }
7021
7022 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007023 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007024 return OR_No_Viable_Function;
7025
7026 // Make sure that this function is better than every other viable
7027 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007028 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007029 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007030 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007031 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007032 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007033 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007034 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007035 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007036 }
Mike Stump11289f42009-09-09 15:08:12 +00007037
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007038 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007039 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007040 (Best->Function->isDeleted() ||
7041 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007042 return OR_Deleted;
7043
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007044 return OR_Success;
7045}
7046
John McCall53262c92010-01-12 02:15:36 +00007047namespace {
7048
7049enum OverloadCandidateKind {
7050 oc_function,
7051 oc_method,
7052 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007053 oc_function_template,
7054 oc_method_template,
7055 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007056 oc_implicit_default_constructor,
7057 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007058 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007059 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007060 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007061 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007062};
7063
John McCalle1ac8d12010-01-13 00:25:19 +00007064OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7065 FunctionDecl *Fn,
7066 std::string &Description) {
7067 bool isTemplate = false;
7068
7069 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7070 isTemplate = true;
7071 Description = S.getTemplateArgumentBindingsText(
7072 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7073 }
John McCallfd0b2f82010-01-06 09:43:14 +00007074
7075 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007076 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007077 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007078
Sebastian Redl08905022011-02-05 19:23:19 +00007079 if (Ctor->getInheritedConstructor())
7080 return oc_implicit_inherited_constructor;
7081
Alexis Hunt119c10e2011-05-25 23:16:36 +00007082 if (Ctor->isDefaultConstructor())
7083 return oc_implicit_default_constructor;
7084
7085 if (Ctor->isMoveConstructor())
7086 return oc_implicit_move_constructor;
7087
7088 assert(Ctor->isCopyConstructor() &&
7089 "unexpected sort of implicit constructor");
7090 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007091 }
7092
7093 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7094 // This actually gets spelled 'candidate function' for now, but
7095 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007096 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007097 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007098
Alexis Hunt119c10e2011-05-25 23:16:36 +00007099 if (Meth->isMoveAssignmentOperator())
7100 return oc_implicit_move_assignment;
7101
Douglas Gregorec3bec02010-09-27 22:37:28 +00007102 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00007103 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00007104 return oc_implicit_copy_assignment;
7105 }
7106
John McCalle1ac8d12010-01-13 00:25:19 +00007107 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007108}
7109
Sebastian Redl08905022011-02-05 19:23:19 +00007110void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7111 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7112 if (!Ctor) return;
7113
7114 Ctor = Ctor->getInheritedConstructor();
7115 if (!Ctor) return;
7116
7117 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7118}
7119
John McCall53262c92010-01-12 02:15:36 +00007120} // end anonymous namespace
7121
7122// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007123void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007124 std::string FnDesc;
7125 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007126 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7127 << (unsigned) K << FnDesc;
7128 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7129 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007130 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007131}
7132
Douglas Gregorb491ed32011-02-19 21:32:49 +00007133//Notes the location of all overload candidates designated through
7134// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007135void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007136 assert(OverloadedExpr->getType() == Context.OverloadTy);
7137
7138 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7139 OverloadExpr *OvlExpr = Ovl.Expression;
7140
7141 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7142 IEnd = OvlExpr->decls_end();
7143 I != IEnd; ++I) {
7144 if (FunctionTemplateDecl *FunTmpl =
7145 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007146 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007147 } else if (FunctionDecl *Fun
7148 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007149 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007150 }
7151 }
7152}
7153
John McCall0d1da222010-01-12 00:44:57 +00007154/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7155/// "lead" diagnostic; it will be given two arguments, the source and
7156/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007157void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7158 Sema &S,
7159 SourceLocation CaretLoc,
7160 const PartialDiagnostic &PDiag) const {
7161 S.Diag(CaretLoc, PDiag)
7162 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007163 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007164 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7165 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007166 }
John McCall12f97bc2010-01-08 04:41:39 +00007167}
7168
John McCall0d1da222010-01-12 00:44:57 +00007169namespace {
7170
John McCall6a61b522010-01-13 09:16:55 +00007171void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7172 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7173 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007174 assert(Cand->Function && "for now, candidate must be a function");
7175 FunctionDecl *Fn = Cand->Function;
7176
7177 // There's a conversion slot for the object argument if this is a
7178 // non-constructor method. Note that 'I' corresponds the
7179 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007180 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007181 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007182 if (I == 0)
7183 isObjectArgument = true;
7184 else
7185 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007186 }
7187
John McCalle1ac8d12010-01-13 00:25:19 +00007188 std::string FnDesc;
7189 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7190
John McCall6a61b522010-01-13 09:16:55 +00007191 Expr *FromExpr = Conv.Bad.FromExpr;
7192 QualType FromTy = Conv.Bad.getFromType();
7193 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007194
John McCallfb7ad0f2010-02-02 02:42:52 +00007195 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007196 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007197 Expr *E = FromExpr->IgnoreParens();
7198 if (isa<UnaryOperator>(E))
7199 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007200 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007201
7202 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7203 << (unsigned) FnKind << FnDesc
7204 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7205 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007206 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007207 return;
7208 }
7209
John McCall6d174642010-01-23 08:10:49 +00007210 // Do some hand-waving analysis to see if the non-viability is due
7211 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007212 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7213 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7214 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7215 CToTy = RT->getPointeeType();
7216 else {
7217 // TODO: detect and diagnose the full richness of const mismatches.
7218 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7219 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7220 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7221 }
7222
7223 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7224 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7225 // It is dumb that we have to do this here.
7226 while (isa<ArrayType>(CFromTy))
7227 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7228 while (isa<ArrayType>(CToTy))
7229 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7230
7231 Qualifiers FromQs = CFromTy.getQualifiers();
7232 Qualifiers ToQs = CToTy.getQualifiers();
7233
7234 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7235 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7236 << (unsigned) FnKind << FnDesc
7237 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7238 << FromTy
7239 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7240 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007241 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007242 return;
7243 }
7244
John McCall31168b02011-06-15 23:02:42 +00007245 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007246 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007247 << (unsigned) FnKind << FnDesc
7248 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7249 << FromTy
7250 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7251 << (unsigned) isObjectArgument << I+1;
7252 MaybeEmitInheritedConstructorNote(S, Fn);
7253 return;
7254 }
7255
Douglas Gregoraec25842011-04-26 23:16:46 +00007256 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7257 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7258 << (unsigned) FnKind << FnDesc
7259 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7260 << FromTy
7261 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7262 << (unsigned) isObjectArgument << I+1;
7263 MaybeEmitInheritedConstructorNote(S, Fn);
7264 return;
7265 }
7266
John McCall47000992010-01-14 03:28:57 +00007267 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7268 assert(CVR && "unexpected qualifiers mismatch");
7269
7270 if (isObjectArgument) {
7271 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7272 << (unsigned) FnKind << FnDesc
7273 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7274 << FromTy << (CVR - 1);
7275 } else {
7276 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7277 << (unsigned) FnKind << FnDesc
7278 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7279 << FromTy << (CVR - 1) << I+1;
7280 }
Sebastian Redl08905022011-02-05 19:23:19 +00007281 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007282 return;
7283 }
7284
Sebastian Redla72462c2011-09-24 17:48:32 +00007285 // Special diagnostic for failure to convert an initializer list, since
7286 // telling the user that it has type void is not useful.
7287 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7288 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7289 << (unsigned) FnKind << FnDesc
7290 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7291 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7292 MaybeEmitInheritedConstructorNote(S, Fn);
7293 return;
7294 }
7295
John McCall6d174642010-01-23 08:10:49 +00007296 // Diagnose references or pointers to incomplete types differently,
7297 // since it's far from impossible that the incompleteness triggered
7298 // the failure.
7299 QualType TempFromTy = FromTy.getNonReferenceType();
7300 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7301 TempFromTy = PTy->getPointeeType();
7302 if (TempFromTy->isIncompleteType()) {
7303 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7304 << (unsigned) FnKind << FnDesc
7305 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7306 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007307 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007308 return;
7309 }
7310
Douglas Gregor56f2e342010-06-30 23:01:39 +00007311 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007312 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007313 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7314 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7315 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7316 FromPtrTy->getPointeeType()) &&
7317 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7318 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007319 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007320 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007321 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007322 }
7323 } else if (const ObjCObjectPointerType *FromPtrTy
7324 = FromTy->getAs<ObjCObjectPointerType>()) {
7325 if (const ObjCObjectPointerType *ToPtrTy
7326 = ToTy->getAs<ObjCObjectPointerType>())
7327 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7328 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7329 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7330 FromPtrTy->getPointeeType()) &&
7331 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007332 BaseToDerivedConversion = 2;
7333 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7334 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7335 !FromTy->isIncompleteType() &&
7336 !ToRefTy->getPointeeType()->isIncompleteType() &&
7337 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7338 BaseToDerivedConversion = 3;
7339 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007340
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007341 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007342 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007343 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007344 << (unsigned) FnKind << FnDesc
7345 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007346 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007347 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007348 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007349 return;
7350 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007351
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007352 if (isa<ObjCObjectPointerType>(CFromTy) &&
7353 isa<PointerType>(CToTy)) {
7354 Qualifiers FromQs = CFromTy.getQualifiers();
7355 Qualifiers ToQs = CToTy.getQualifiers();
7356 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7357 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7358 << (unsigned) FnKind << FnDesc
7359 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7360 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7361 MaybeEmitInheritedConstructorNote(S, Fn);
7362 return;
7363 }
7364 }
7365
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007366 // Emit the generic diagnostic and, optionally, add the hints to it.
7367 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7368 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007369 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007370 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7371 << (unsigned) (Cand->Fix.Kind);
7372
7373 // If we can fix the conversion, suggest the FixIts.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007374 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007375 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7376 HI != HE; ++HI)
7377 FDiag << *HI;
7378 S.Diag(Fn->getLocation(), FDiag);
7379
Sebastian Redl08905022011-02-05 19:23:19 +00007380 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007381}
7382
7383void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7384 unsigned NumFormalArgs) {
7385 // TODO: treat calls to a missing default constructor as a special case
7386
7387 FunctionDecl *Fn = Cand->Function;
7388 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7389
7390 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007391
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00007392 // With invalid overloaded operators, it's possible that we think we
7393 // have an arity mismatch when it fact it looks like we have the
7394 // right number of arguments, because only overloaded operators have
7395 // the weird behavior of overloading member and non-member functions.
7396 // Just don't report anything.
7397 if (Fn->isInvalidDecl() &&
7398 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7399 return;
7400
John McCall6a61b522010-01-13 09:16:55 +00007401 // at least / at most / exactly
7402 unsigned mode, modeCount;
7403 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007404 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7405 (Cand->FailureKind == ovl_fail_bad_deduction &&
7406 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007407 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00007408 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00007409 mode = 0; // "at least"
7410 else
7411 mode = 2; // "exactly"
7412 modeCount = MinParams;
7413 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007414 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7415 (Cand->FailureKind == ovl_fail_bad_deduction &&
7416 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00007417 if (MinParams != FnTy->getNumArgs())
7418 mode = 1; // "at most"
7419 else
7420 mode = 2; // "exactly"
7421 modeCount = FnTy->getNumArgs();
7422 }
7423
7424 std::string Description;
7425 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7426
7427 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007428 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00007429 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00007430 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007431}
7432
John McCall8b9ed552010-02-01 18:53:26 +00007433/// Diagnose a failed template-argument deduction.
7434void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7435 Expr **Args, unsigned NumArgs) {
7436 FunctionDecl *Fn = Cand->Function; // pattern
7437
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007438 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007439 NamedDecl *ParamD;
7440 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7441 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7442 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007443 switch (Cand->DeductionFailure.Result) {
7444 case Sema::TDK_Success:
7445 llvm_unreachable("TDK_success while diagnosing bad deduction");
7446
7447 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007448 assert(ParamD && "no parameter found for incomplete deduction result");
7449 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7450 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007451 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007452 return;
7453 }
7454
John McCall42d7d192010-08-05 09:05:08 +00007455 case Sema::TDK_Underqualified: {
7456 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7457 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7458
7459 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7460
7461 // Param will have been canonicalized, but it should just be a
7462 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007463 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007464 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007465 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007466 assert(S.Context.hasSameType(Param, NonCanonParam));
7467
7468 // Arg has also been canonicalized, but there's nothing we can do
7469 // about that. It also doesn't matter as much, because it won't
7470 // have any template parameters in it (because deduction isn't
7471 // done on dependent types).
7472 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7473
7474 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7475 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007476 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007477 return;
7478 }
7479
7480 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007481 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007482 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007483 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007484 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007485 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007486 which = 1;
7487 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007488 which = 2;
7489 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007490
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007491 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007492 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007493 << *Cand->DeductionFailure.getFirstArg()
7494 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007495 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007496 return;
7497 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007498
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007499 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007500 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007501 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007502 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007503 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7504 << ParamD->getDeclName();
7505 else {
7506 int index = 0;
7507 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7508 index = TTP->getIndex();
7509 else if (NonTypeTemplateParmDecl *NTTP
7510 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7511 index = NTTP->getIndex();
7512 else
7513 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007514 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007515 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7516 << (index + 1);
7517 }
Sebastian Redl08905022011-02-05 19:23:19 +00007518 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007519 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007520
Douglas Gregor02eb4832010-05-08 18:13:28 +00007521 case Sema::TDK_TooManyArguments:
7522 case Sema::TDK_TooFewArguments:
7523 DiagnoseArityMismatch(S, Cand, NumArgs);
7524 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007525
7526 case Sema::TDK_InstantiationDepth:
7527 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007528 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007529 return;
7530
7531 case Sema::TDK_SubstitutionFailure: {
7532 std::string ArgString;
7533 if (TemplateArgumentList *Args
7534 = Cand->DeductionFailure.getTemplateArgumentList())
7535 ArgString = S.getTemplateArgumentBindingsText(
7536 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7537 *Args);
7538 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7539 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007540 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007541 return;
7542 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007543
John McCall8b9ed552010-02-01 18:53:26 +00007544 // TODO: diagnose these individually, then kill off
7545 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007546 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007547 case Sema::TDK_FailedOverloadResolution:
7548 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007549 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007550 return;
7551 }
7552}
7553
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007554/// CUDA: diagnose an invalid call across targets.
7555void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7556 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7557 FunctionDecl *Callee = Cand->Function;
7558
7559 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7560 CalleeTarget = S.IdentifyCUDATarget(Callee);
7561
7562 std::string FnDesc;
7563 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7564
7565 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7566 << (unsigned) FnKind << CalleeTarget << CallerTarget;
7567}
7568
John McCall8b9ed552010-02-01 18:53:26 +00007569/// Generates a 'note' diagnostic for an overload candidate. We've
7570/// already generated a primary error at the call site.
7571///
7572/// It really does need to be a single diagnostic with its caret
7573/// pointed at the candidate declaration. Yes, this creates some
7574/// major challenges of technical writing. Yes, this makes pointing
7575/// out problems with specific arguments quite awkward. It's still
7576/// better than generating twenty screens of text for every failed
7577/// overload.
7578///
7579/// It would be great to be able to express per-candidate problems
7580/// more richly for those diagnostic clients that cared, but we'd
7581/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007582void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7583 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007584 FunctionDecl *Fn = Cand->Function;
7585
John McCall12f97bc2010-01-08 04:41:39 +00007586 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007587 if (Cand->Viable && (Fn->isDeleted() ||
7588 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007589 std::string FnDesc;
7590 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007591
7592 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007593 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007594 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007595 return;
John McCall12f97bc2010-01-08 04:41:39 +00007596 }
7597
John McCalle1ac8d12010-01-13 00:25:19 +00007598 // We don't really have anything else to say about viable candidates.
7599 if (Cand->Viable) {
7600 S.NoteOverloadCandidate(Fn);
7601 return;
7602 }
John McCall0d1da222010-01-12 00:44:57 +00007603
John McCall6a61b522010-01-13 09:16:55 +00007604 switch (Cand->FailureKind) {
7605 case ovl_fail_too_many_arguments:
7606 case ovl_fail_too_few_arguments:
7607 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007608
John McCall6a61b522010-01-13 09:16:55 +00007609 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007610 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7611
John McCallfe796dd2010-01-23 05:17:32 +00007612 case ovl_fail_trivial_conversion:
7613 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007614 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007615 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007616
John McCall65eb8792010-02-25 01:37:24 +00007617 case ovl_fail_bad_conversion: {
7618 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7619 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007620 if (Cand->Conversions[I].isBad())
7621 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007622
John McCall6a61b522010-01-13 09:16:55 +00007623 // FIXME: this currently happens when we're called from SemaInit
7624 // when user-conversion overload fails. Figure out how to handle
7625 // those conditions and diagnose them well.
7626 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007627 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007628
7629 case ovl_fail_bad_target:
7630 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00007631 }
John McCalld3224162010-01-08 00:58:21 +00007632}
7633
7634void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7635 // Desugar the type of the surrogate down to a function type,
7636 // retaining as many typedefs as possible while still showing
7637 // the function type (and, therefore, its parameter types).
7638 QualType FnType = Cand->Surrogate->getConversionType();
7639 bool isLValueReference = false;
7640 bool isRValueReference = false;
7641 bool isPointer = false;
7642 if (const LValueReferenceType *FnTypeRef =
7643 FnType->getAs<LValueReferenceType>()) {
7644 FnType = FnTypeRef->getPointeeType();
7645 isLValueReference = true;
7646 } else if (const RValueReferenceType *FnTypeRef =
7647 FnType->getAs<RValueReferenceType>()) {
7648 FnType = FnTypeRef->getPointeeType();
7649 isRValueReference = true;
7650 }
7651 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7652 FnType = FnTypePtr->getPointeeType();
7653 isPointer = true;
7654 }
7655 // Desugar down to a function type.
7656 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7657 // Reconstruct the pointer/reference as appropriate.
7658 if (isPointer) FnType = S.Context.getPointerType(FnType);
7659 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7660 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7661
7662 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7663 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007664 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007665}
7666
7667void NoteBuiltinOperatorCandidate(Sema &S,
7668 const char *Opc,
7669 SourceLocation OpLoc,
7670 OverloadCandidate *Cand) {
7671 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7672 std::string TypeStr("operator");
7673 TypeStr += Opc;
7674 TypeStr += "(";
7675 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7676 if (Cand->Conversions.size() == 1) {
7677 TypeStr += ")";
7678 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7679 } else {
7680 TypeStr += ", ";
7681 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7682 TypeStr += ")";
7683 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7684 }
7685}
7686
7687void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7688 OverloadCandidate *Cand) {
7689 unsigned NoOperands = Cand->Conversions.size();
7690 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7691 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007692 if (ICS.isBad()) break; // all meaningless after first invalid
7693 if (!ICS.isAmbiguous()) continue;
7694
John McCall5c32be02010-08-24 20:38:10 +00007695 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007696 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007697 }
7698}
7699
John McCall3712d9e2010-01-15 23:32:50 +00007700SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7701 if (Cand->Function)
7702 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007703 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007704 return Cand->Surrogate->getLocation();
7705 return SourceLocation();
7706}
7707
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007708static unsigned
7709RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00007710 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007711 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00007712 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007713
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007714 case Sema::TDK_Incomplete:
7715 return 1;
7716
7717 case Sema::TDK_Underqualified:
7718 case Sema::TDK_Inconsistent:
7719 return 2;
7720
7721 case Sema::TDK_SubstitutionFailure:
7722 case Sema::TDK_NonDeducedMismatch:
7723 return 3;
7724
7725 case Sema::TDK_InstantiationDepth:
7726 case Sema::TDK_FailedOverloadResolution:
7727 return 4;
7728
7729 case Sema::TDK_InvalidExplicitArguments:
7730 return 5;
7731
7732 case Sema::TDK_TooManyArguments:
7733 case Sema::TDK_TooFewArguments:
7734 return 6;
7735 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007736 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007737}
7738
John McCallad2587a2010-01-12 00:48:53 +00007739struct CompareOverloadCandidatesForDisplay {
7740 Sema &S;
7741 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007742
7743 bool operator()(const OverloadCandidate *L,
7744 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007745 // Fast-path this check.
7746 if (L == R) return false;
7747
John McCall12f97bc2010-01-08 04:41:39 +00007748 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007749 if (L->Viable) {
7750 if (!R->Viable) return true;
7751
7752 // TODO: introduce a tri-valued comparison for overload
7753 // candidates. Would be more worthwhile if we had a sort
7754 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007755 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7756 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007757 } else if (R->Viable)
7758 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007759
John McCall3712d9e2010-01-15 23:32:50 +00007760 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007761
John McCall3712d9e2010-01-15 23:32:50 +00007762 // Criteria by which we can sort non-viable candidates:
7763 if (!L->Viable) {
7764 // 1. Arity mismatches come after other candidates.
7765 if (L->FailureKind == ovl_fail_too_many_arguments ||
7766 L->FailureKind == ovl_fail_too_few_arguments)
7767 return false;
7768 if (R->FailureKind == ovl_fail_too_many_arguments ||
7769 R->FailureKind == ovl_fail_too_few_arguments)
7770 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007771
John McCallfe796dd2010-01-23 05:17:32 +00007772 // 2. Bad conversions come first and are ordered by the number
7773 // of bad conversions and quality of good conversions.
7774 if (L->FailureKind == ovl_fail_bad_conversion) {
7775 if (R->FailureKind != ovl_fail_bad_conversion)
7776 return true;
7777
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007778 // The conversion that can be fixed with a smaller number of changes,
7779 // comes first.
7780 unsigned numLFixes = L->Fix.NumConversionsFixed;
7781 unsigned numRFixes = R->Fix.NumConversionsFixed;
7782 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7783 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007784 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007785 if (numLFixes < numRFixes)
7786 return true;
7787 else
7788 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007789 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007790
John McCallfe796dd2010-01-23 05:17:32 +00007791 // If there's any ordering between the defined conversions...
7792 // FIXME: this might not be transitive.
7793 assert(L->Conversions.size() == R->Conversions.size());
7794
7795 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007796 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7797 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007798 switch (CompareImplicitConversionSequences(S,
7799 L->Conversions[I],
7800 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007801 case ImplicitConversionSequence::Better:
7802 leftBetter++;
7803 break;
7804
7805 case ImplicitConversionSequence::Worse:
7806 leftBetter--;
7807 break;
7808
7809 case ImplicitConversionSequence::Indistinguishable:
7810 break;
7811 }
7812 }
7813 if (leftBetter > 0) return true;
7814 if (leftBetter < 0) return false;
7815
7816 } else if (R->FailureKind == ovl_fail_bad_conversion)
7817 return false;
7818
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007819 if (L->FailureKind == ovl_fail_bad_deduction) {
7820 if (R->FailureKind != ovl_fail_bad_deduction)
7821 return true;
7822
7823 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7824 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00007825 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00007826 } else if (R->FailureKind == ovl_fail_bad_deduction)
7827 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007828
John McCall3712d9e2010-01-15 23:32:50 +00007829 // TODO: others?
7830 }
7831
7832 // Sort everything else by location.
7833 SourceLocation LLoc = GetLocationForCandidate(L);
7834 SourceLocation RLoc = GetLocationForCandidate(R);
7835
7836 // Put candidates without locations (e.g. builtins) at the end.
7837 if (LLoc.isInvalid()) return false;
7838 if (RLoc.isInvalid()) return true;
7839
7840 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007841 }
7842};
7843
John McCallfe796dd2010-01-23 05:17:32 +00007844/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007845/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00007846void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7847 Expr **Args, unsigned NumArgs) {
7848 assert(!Cand->Viable);
7849
7850 // Don't do anything on failures other than bad conversion.
7851 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7852
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007853 // We only want the FixIts if all the arguments can be corrected.
7854 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00007855 // Use a implicit copy initialization to check conversion fixes.
7856 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007857
John McCallfe796dd2010-01-23 05:17:32 +00007858 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007859 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007860 unsigned ConvCount = Cand->Conversions.size();
7861 while (true) {
7862 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7863 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007864 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00007865 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00007866 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007867 }
John McCallfe796dd2010-01-23 05:17:32 +00007868 }
7869
7870 if (ConvIdx == ConvCount)
7871 return;
7872
John McCall65eb8792010-02-25 01:37:24 +00007873 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7874 "remaining conversion is initialized?");
7875
Douglas Gregoradc7a702010-04-16 17:45:54 +00007876 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007877 // operation somehow.
7878 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007879
7880 const FunctionProtoType* Proto;
7881 unsigned ArgIdx = ConvIdx;
7882
7883 if (Cand->IsSurrogate) {
7884 QualType ConvType
7885 = Cand->Surrogate->getConversionType().getNonReferenceType();
7886 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7887 ConvType = ConvPtrType->getPointeeType();
7888 Proto = ConvType->getAs<FunctionProtoType>();
7889 ArgIdx--;
7890 } else if (Cand->Function) {
7891 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7892 if (isa<CXXMethodDecl>(Cand->Function) &&
7893 !isa<CXXConstructorDecl>(Cand->Function))
7894 ArgIdx--;
7895 } else {
7896 // Builtin binary operator with a bad first conversion.
7897 assert(ConvCount <= 3);
7898 for (; ConvIdx != ConvCount; ++ConvIdx)
7899 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007900 = TryCopyInitialization(S, Args[ConvIdx],
7901 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007902 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007903 /*InOverloadResolution*/ true,
7904 /*AllowObjCWritebackConversion=*/
7905 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00007906 return;
7907 }
7908
7909 // Fill in the rest of the conversions.
7910 unsigned NumArgsInProto = Proto->getNumArgs();
7911 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007912 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00007913 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007914 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007915 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007916 /*InOverloadResolution=*/true,
7917 /*AllowObjCWritebackConversion=*/
7918 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007919 // Store the FixIt in the candidate if it exists.
7920 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00007921 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007922 }
John McCallfe796dd2010-01-23 05:17:32 +00007923 else
7924 Cand->Conversions[ConvIdx].setEllipsis();
7925 }
7926}
7927
John McCalld3224162010-01-08 00:58:21 +00007928} // end anonymous namespace
7929
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007930/// PrintOverloadCandidates - When overload resolution fails, prints
7931/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007932/// set.
John McCall5c32be02010-08-24 20:38:10 +00007933void OverloadCandidateSet::NoteCandidates(Sema &S,
7934 OverloadCandidateDisplayKind OCD,
7935 Expr **Args, unsigned NumArgs,
7936 const char *Opc,
7937 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007938 // Sort the candidates by viability and position. Sorting directly would
7939 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007940 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007941 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7942 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007943 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007944 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007945 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007946 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007947 if (Cand->Function || Cand->IsSurrogate)
7948 Cands.push_back(Cand);
7949 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7950 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007951 }
7952 }
7953
John McCallad2587a2010-01-12 00:48:53 +00007954 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007955 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007956
John McCall0d1da222010-01-12 00:44:57 +00007957 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007958
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007959 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00007960 const DiagnosticsEngine::OverloadsShown ShowOverloads =
7961 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007962 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007963 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7964 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007965
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007966 // Set an arbitrary limit on the number of candidate functions we'll spam
7967 // the user with. FIXME: This limit should depend on details of the
7968 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00007969 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007970 break;
7971 }
7972 ++CandsShown;
7973
John McCalld3224162010-01-08 00:58:21 +00007974 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007975 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007976 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007977 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007978 else {
7979 assert(Cand->Viable &&
7980 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007981 // Generally we only see ambiguities including viable builtin
7982 // operators if overload resolution got screwed up by an
7983 // ambiguous user-defined conversion.
7984 //
7985 // FIXME: It's quite possible for different conversions to see
7986 // different ambiguities, though.
7987 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007988 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007989 ReportedAmbiguousConversions = true;
7990 }
John McCalld3224162010-01-08 00:58:21 +00007991
John McCall0d1da222010-01-12 00:44:57 +00007992 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007993 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007994 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007995 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007996
7997 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007998 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007999}
8000
Douglas Gregorb491ed32011-02-19 21:32:49 +00008001// [PossiblyAFunctionType] --> [Return]
8002// NonFunctionType --> NonFunctionType
8003// R (A) --> R(A)
8004// R (*)(A) --> R (A)
8005// R (&)(A) --> R (A)
8006// R (S::*)(A) --> R (A)
8007QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8008 QualType Ret = PossiblyAFunctionType;
8009 if (const PointerType *ToTypePtr =
8010 PossiblyAFunctionType->getAs<PointerType>())
8011 Ret = ToTypePtr->getPointeeType();
8012 else if (const ReferenceType *ToTypeRef =
8013 PossiblyAFunctionType->getAs<ReferenceType>())
8014 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008015 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008016 PossiblyAFunctionType->getAs<MemberPointerType>())
8017 Ret = MemTypePtr->getPointeeType();
8018 Ret =
8019 Context.getCanonicalType(Ret).getUnqualifiedType();
8020 return Ret;
8021}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008022
Douglas Gregorb491ed32011-02-19 21:32:49 +00008023// A helper class to help with address of function resolution
8024// - allows us to avoid passing around all those ugly parameters
8025class AddressOfFunctionResolver
8026{
8027 Sema& S;
8028 Expr* SourceExpr;
8029 const QualType& TargetType;
8030 QualType TargetFunctionType; // Extracted function type from target type
8031
8032 bool Complain;
8033 //DeclAccessPair& ResultFunctionAccessPair;
8034 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008035
Douglas Gregorb491ed32011-02-19 21:32:49 +00008036 bool TargetTypeIsNonStaticMemberFunction;
8037 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008038
Douglas Gregorb491ed32011-02-19 21:32:49 +00008039 OverloadExpr::FindResult OvlExprInfo;
8040 OverloadExpr *OvlExpr;
8041 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008042 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008043
Douglas Gregorb491ed32011-02-19 21:32:49 +00008044public:
8045 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8046 const QualType& TargetType, bool Complain)
8047 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8048 Complain(Complain), Context(S.getASTContext()),
8049 TargetTypeIsNonStaticMemberFunction(
8050 !!TargetType->getAs<MemberPointerType>()),
8051 FoundNonTemplateFunction(false),
8052 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8053 OvlExpr(OvlExprInfo.Expression)
8054 {
8055 ExtractUnqualifiedFunctionTypeFromTargetType();
8056
8057 if (!TargetFunctionType->isFunctionType()) {
8058 if (OvlExpr->hasExplicitTemplateArgs()) {
8059 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008060 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008061 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008062
8063 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8064 if (!Method->isStatic()) {
8065 // If the target type is a non-function type and the function
8066 // found is a non-static member function, pretend as if that was
8067 // the target, it's the only possible type to end up with.
8068 TargetTypeIsNonStaticMemberFunction = true;
8069
8070 // And skip adding the function if its not in the proper form.
8071 // We'll diagnose this due to an empty set of functions.
8072 if (!OvlExprInfo.HasFormOfMemberPointer)
8073 return;
8074 }
8075 }
8076
Douglas Gregorb491ed32011-02-19 21:32:49 +00008077 Matches.push_back(std::make_pair(dap,Fn));
8078 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008079 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008080 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008081 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008082
8083 if (OvlExpr->hasExplicitTemplateArgs())
8084 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008085
Douglas Gregorb491ed32011-02-19 21:32:49 +00008086 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8087 // C++ [over.over]p4:
8088 // If more than one function is selected, [...]
8089 if (Matches.size() > 1) {
8090 if (FoundNonTemplateFunction)
8091 EliminateAllTemplateMatches();
8092 else
8093 EliminateAllExceptMostSpecializedTemplate();
8094 }
8095 }
8096 }
8097
8098private:
8099 bool isTargetTypeAFunction() const {
8100 return TargetFunctionType->isFunctionType();
8101 }
8102
8103 // [ToType] [Return]
8104
8105 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8106 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8107 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8108 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8109 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8110 }
8111
8112 // return true if any matching specializations were found
8113 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8114 const DeclAccessPair& CurAccessFunPair) {
8115 if (CXXMethodDecl *Method
8116 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8117 // Skip non-static function templates when converting to pointer, and
8118 // static when converting to member pointer.
8119 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8120 return false;
8121 }
8122 else if (TargetTypeIsNonStaticMemberFunction)
8123 return false;
8124
8125 // C++ [over.over]p2:
8126 // If the name is a function template, template argument deduction is
8127 // done (14.8.2.2), and if the argument deduction succeeds, the
8128 // resulting template argument list is used to generate a single
8129 // function template specialization, which is added to the set of
8130 // overloaded functions considered.
8131 FunctionDecl *Specialization = 0;
8132 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8133 if (Sema::TemplateDeductionResult Result
8134 = S.DeduceTemplateArguments(FunctionTemplate,
8135 &OvlExplicitTemplateArgs,
8136 TargetFunctionType, Specialization,
8137 Info)) {
8138 // FIXME: make a note of the failed deduction for diagnostics.
8139 (void)Result;
8140 return false;
8141 }
8142
8143 // Template argument deduction ensures that we have an exact match.
8144 // This function template specicalization works.
8145 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8146 assert(TargetFunctionType
8147 == Context.getCanonicalType(Specialization->getType()));
8148 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8149 return true;
8150 }
8151
8152 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8153 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008154 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008155 // Skip non-static functions when converting to pointer, and static
8156 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008157 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8158 return false;
8159 }
8160 else if (TargetTypeIsNonStaticMemberFunction)
8161 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008162
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008163 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008164 if (S.getLangOptions().CUDA)
8165 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8166 if (S.CheckCUDATarget(Caller, FunDecl))
8167 return false;
8168
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008169 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008170 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8171 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008172 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8173 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008174 Matches.push_back(std::make_pair(CurAccessFunPair,
8175 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008176 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008177 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008178 }
Mike Stump11289f42009-09-09 15:08:12 +00008179 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008180
8181 return false;
8182 }
8183
8184 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8185 bool Ret = false;
8186
8187 // If the overload expression doesn't have the form of a pointer to
8188 // member, don't try to convert it to a pointer-to-member type.
8189 if (IsInvalidFormOfPointerToMemberFunction())
8190 return false;
8191
8192 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8193 E = OvlExpr->decls_end();
8194 I != E; ++I) {
8195 // Look through any using declarations to find the underlying function.
8196 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8197
8198 // C++ [over.over]p3:
8199 // Non-member functions and static member functions match
8200 // targets of type "pointer-to-function" or "reference-to-function."
8201 // Nonstatic member functions match targets of
8202 // type "pointer-to-member-function."
8203 // Note that according to DR 247, the containing class does not matter.
8204 if (FunctionTemplateDecl *FunctionTemplate
8205 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8206 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8207 Ret = true;
8208 }
8209 // If we have explicit template arguments supplied, skip non-templates.
8210 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8211 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8212 Ret = true;
8213 }
8214 assert(Ret || Matches.empty());
8215 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008216 }
8217
Douglas Gregorb491ed32011-02-19 21:32:49 +00008218 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008219 // [...] and any given function template specialization F1 is
8220 // eliminated if the set contains a second function template
8221 // specialization whose function template is more specialized
8222 // than the function template of F1 according to the partial
8223 // ordering rules of 14.5.5.2.
8224
8225 // The algorithm specified above is quadratic. We instead use a
8226 // two-pass algorithm (similar to the one used to identify the
8227 // best viable function in an overload set) that identifies the
8228 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008229
8230 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8231 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8232 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008233
John McCall58cc69d2010-01-27 01:50:18 +00008234 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008235 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8236 TPOC_Other, 0, SourceExpr->getLocStart(),
8237 S.PDiag(),
8238 S.PDiag(diag::err_addr_ovl_ambiguous)
8239 << Matches[0].second->getDeclName(),
8240 S.PDiag(diag::note_ovl_candidate)
8241 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00008242 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008243
Douglas Gregorb491ed32011-02-19 21:32:49 +00008244 if (Result != MatchesCopy.end()) {
8245 // Make it the first and only element
8246 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8247 Matches[0].second = cast<FunctionDecl>(*Result);
8248 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008249 }
8250 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008251
Douglas Gregorb491ed32011-02-19 21:32:49 +00008252 void EliminateAllTemplateMatches() {
8253 // [...] any function template specializations in the set are
8254 // eliminated if the set also contains a non-template function, [...]
8255 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8256 if (Matches[I].second->getPrimaryTemplate() == 0)
8257 ++I;
8258 else {
8259 Matches[I] = Matches[--N];
8260 Matches.set_size(N);
8261 }
8262 }
8263 }
8264
8265public:
8266 void ComplainNoMatchesFound() const {
8267 assert(Matches.empty());
8268 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8269 << OvlExpr->getName() << TargetFunctionType
8270 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008271 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008272 }
8273
8274 bool IsInvalidFormOfPointerToMemberFunction() const {
8275 return TargetTypeIsNonStaticMemberFunction &&
8276 !OvlExprInfo.HasFormOfMemberPointer;
8277 }
8278
8279 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8280 // TODO: Should we condition this on whether any functions might
8281 // have matched, or is it more appropriate to do that in callers?
8282 // TODO: a fixit wouldn't hurt.
8283 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8284 << TargetType << OvlExpr->getSourceRange();
8285 }
8286
8287 void ComplainOfInvalidConversion() const {
8288 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8289 << OvlExpr->getName() << TargetType;
8290 }
8291
8292 void ComplainMultipleMatchesFound() const {
8293 assert(Matches.size() > 1);
8294 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8295 << OvlExpr->getName()
8296 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008297 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008298 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008299
8300 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8301
Douglas Gregorb491ed32011-02-19 21:32:49 +00008302 int getNumMatches() const { return Matches.size(); }
8303
8304 FunctionDecl* getMatchingFunctionDecl() const {
8305 if (Matches.size() != 1) return 0;
8306 return Matches[0].second;
8307 }
8308
8309 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8310 if (Matches.size() != 1) return 0;
8311 return &Matches[0].first;
8312 }
8313};
8314
8315/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8316/// an overloaded function (C++ [over.over]), where @p From is an
8317/// expression with overloaded function type and @p ToType is the type
8318/// we're trying to resolve to. For example:
8319///
8320/// @code
8321/// int f(double);
8322/// int f(int);
8323///
8324/// int (*pfd)(double) = f; // selects f(double)
8325/// @endcode
8326///
8327/// This routine returns the resulting FunctionDecl if it could be
8328/// resolved, and NULL otherwise. When @p Complain is true, this
8329/// routine will emit diagnostics if there is an error.
8330FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008331Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8332 QualType TargetType,
8333 bool Complain,
8334 DeclAccessPair &FoundResult,
8335 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008336 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008337
8338 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8339 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008340 int NumMatches = Resolver.getNumMatches();
8341 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008342 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008343 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8344 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8345 else
8346 Resolver.ComplainNoMatchesFound();
8347 }
8348 else if (NumMatches > 1 && Complain)
8349 Resolver.ComplainMultipleMatchesFound();
8350 else if (NumMatches == 1) {
8351 Fn = Resolver.getMatchingFunctionDecl();
8352 assert(Fn);
8353 FoundResult = *Resolver.getMatchingFunctionAccessPair();
8354 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00008355 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00008356 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00008357 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008358
8359 if (pHadMultipleCandidates)
8360 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00008361 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008362}
8363
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008364/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008365/// resolve that overloaded function expression down to a single function.
8366///
8367/// This routine can only resolve template-ids that refer to a single function
8368/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008369/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008370/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00008371FunctionDecl *
8372Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8373 bool Complain,
8374 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008375 // C++ [over.over]p1:
8376 // [...] [Note: any redundant set of parentheses surrounding the
8377 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008378 // C++ [over.over]p1:
8379 // [...] The overloaded function name can be preceded by the &
8380 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008381
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008382 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00008383 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008384 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00008385
8386 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00008387 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008388
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008389 // Look through all of the overloaded functions, searching for one
8390 // whose type matches exactly.
8391 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008392 for (UnresolvedSetIterator I = ovl->decls_begin(),
8393 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008394 // C++0x [temp.arg.explicit]p3:
8395 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008396 // where deduction is not done, if a template argument list is
8397 // specified and it, along with any default template arguments,
8398 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008399 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00008400 FunctionTemplateDecl *FunctionTemplate
8401 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008402
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008403 // C++ [over.over]p2:
8404 // If the name is a function template, template argument deduction is
8405 // done (14.8.2.2), and if the argument deduction succeeds, the
8406 // resulting template argument list is used to generate a single
8407 // function template specialization, which is added to the set of
8408 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008409 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008410 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008411 if (TemplateDeductionResult Result
8412 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8413 Specialization, Info)) {
8414 // FIXME: make a note of the failed deduction for diagnostics.
8415 (void)Result;
8416 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008417 }
8418
John McCall0009fcc2011-04-26 20:42:42 +00008419 assert(Specialization && "no specialization and no error?");
8420
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008421 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008422 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008423 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00008424 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8425 << ovl->getName();
8426 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008427 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008428 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00008429 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008430
John McCall0009fcc2011-04-26 20:42:42 +00008431 Matched = Specialization;
8432 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008433 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008434
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008435 return Matched;
8436}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008437
Douglas Gregor1beec452011-03-12 01:48:56 +00008438
8439
8440
John McCall50a2c2c2011-10-11 23:14:30 +00008441// Resolve and fix an overloaded expression that can be resolved
8442// because it identifies a single function template specialization.
8443//
Douglas Gregor1beec452011-03-12 01:48:56 +00008444// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00008445//
8446// Return true if it was logically possible to so resolve the
8447// expression, regardless of whether or not it succeeded. Always
8448// returns true if 'complain' is set.
8449bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8450 ExprResult &SrcExpr, bool doFunctionPointerConverion,
8451 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00008452 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00008453 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00008454 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00008455
John McCall50a2c2c2011-10-11 23:14:30 +00008456 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00008457
John McCall0009fcc2011-04-26 20:42:42 +00008458 DeclAccessPair found;
8459 ExprResult SingleFunctionExpression;
8460 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8461 ovl.Expression, /*complain*/ false, &found)) {
John McCall50a2c2c2011-10-11 23:14:30 +00008462 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8463 SrcExpr = ExprError();
8464 return true;
8465 }
John McCall0009fcc2011-04-26 20:42:42 +00008466
8467 // It is only correct to resolve to an instance method if we're
8468 // resolving a form that's permitted to be a pointer to member.
8469 // Otherwise we'll end up making a bound member expression, which
8470 // is illegal in all the contexts we resolve like this.
8471 if (!ovl.HasFormOfMemberPointer &&
8472 isa<CXXMethodDecl>(fn) &&
8473 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00008474 if (!complain) return false;
8475
8476 Diag(ovl.Expression->getExprLoc(),
8477 diag::err_bound_member_function)
8478 << 0 << ovl.Expression->getSourceRange();
8479
8480 // TODO: I believe we only end up here if there's a mix of
8481 // static and non-static candidates (otherwise the expression
8482 // would have 'bound member' type, not 'overload' type).
8483 // Ideally we would note which candidate was chosen and why
8484 // the static candidates were rejected.
8485 SrcExpr = ExprError();
8486 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008487 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008488
John McCall0009fcc2011-04-26 20:42:42 +00008489 // Fix the expresion to refer to 'fn'.
8490 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00008491 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00008492
8493 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00008494 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00008495 SingleFunctionExpression =
8496 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00008497 if (SingleFunctionExpression.isInvalid()) {
8498 SrcExpr = ExprError();
8499 return true;
8500 }
8501 }
John McCall0009fcc2011-04-26 20:42:42 +00008502 }
8503
8504 if (!SingleFunctionExpression.isUsable()) {
8505 if (complain) {
8506 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8507 << ovl.Expression->getName()
8508 << DestTypeForComplaining
8509 << OpRangeForComplaining
8510 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00008511 NoteAllOverloadCandidates(SrcExpr.get());
8512
8513 SrcExpr = ExprError();
8514 return true;
8515 }
8516
8517 return false;
John McCall0009fcc2011-04-26 20:42:42 +00008518 }
8519
John McCall50a2c2c2011-10-11 23:14:30 +00008520 SrcExpr = SingleFunctionExpression;
8521 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008522}
8523
Douglas Gregorcabea402009-09-22 15:41:20 +00008524/// \brief Add a single candidate to the overload set.
8525static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00008526 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008527 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008528 Expr **Args, unsigned NumArgs,
8529 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008530 bool PartialOverloading,
8531 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00008532 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00008533 if (isa<UsingShadowDecl>(Callee))
8534 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8535
Douglas Gregorcabea402009-09-22 15:41:20 +00008536 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00008537 if (ExplicitTemplateArgs) {
8538 assert(!KnownValid && "Explicit template arguments?");
8539 return;
8540 }
John McCalla0296f72010-03-19 07:35:19 +00008541 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00008542 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008543 return;
John McCalld14a8642009-11-21 08:51:07 +00008544 }
8545
8546 if (FunctionTemplateDecl *FuncTemplate
8547 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00008548 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8549 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00008550 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00008551 return;
8552 }
8553
Richard Smith95ce4f62011-06-26 22:19:54 +00008554 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00008555}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008556
Douglas Gregorcabea402009-09-22 15:41:20 +00008557/// \brief Add the overload candidates named by callee and/or found by argument
8558/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00008559void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00008560 Expr **Args, unsigned NumArgs,
8561 OverloadCandidateSet &CandidateSet,
8562 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00008563
8564#ifndef NDEBUG
8565 // Verify that ArgumentDependentLookup is consistent with the rules
8566 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00008567 //
Douglas Gregorcabea402009-09-22 15:41:20 +00008568 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8569 // and let Y be the lookup set produced by argument dependent
8570 // lookup (defined as follows). If X contains
8571 //
8572 // -- a declaration of a class member, or
8573 //
8574 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00008575 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00008576 //
8577 // -- a declaration that is neither a function or a function
8578 // template
8579 //
8580 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00008581
John McCall57500772009-12-16 12:17:52 +00008582 if (ULE->requiresADL()) {
8583 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8584 E = ULE->decls_end(); I != E; ++I) {
8585 assert(!(*I)->getDeclContext()->isRecord());
8586 assert(isa<UsingShadowDecl>(*I) ||
8587 !(*I)->getDeclContext()->isFunctionOrMethod());
8588 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008589 }
8590 }
8591#endif
8592
John McCall57500772009-12-16 12:17:52 +00008593 // It would be nice to avoid this copy.
8594 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008595 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008596 if (ULE->hasExplicitTemplateArgs()) {
8597 ULE->copyTemplateArgumentsInto(TABuffer);
8598 ExplicitTemplateArgs = &TABuffer;
8599 }
8600
8601 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8602 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008603 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008604 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008605 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008606
John McCall57500772009-12-16 12:17:52 +00008607 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008608 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8609 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008610 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008611 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008612 PartialOverloading,
8613 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008614}
John McCalld681c392009-12-16 08:11:27 +00008615
Richard Smith998a5912011-06-05 22:42:48 +00008616/// Attempt to recover from an ill-formed use of a non-dependent name in a
8617/// template, where the non-dependent name was declared after the template
8618/// was defined. This is common in code written for a compilers which do not
8619/// correctly implement two-stage name lookup.
8620///
8621/// Returns true if a viable candidate was found and a diagnostic was issued.
8622static bool
8623DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8624 const CXXScopeSpec &SS, LookupResult &R,
8625 TemplateArgumentListInfo *ExplicitTemplateArgs,
8626 Expr **Args, unsigned NumArgs) {
8627 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8628 return false;
8629
8630 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8631 SemaRef.LookupQualifiedName(R, DC);
8632
8633 if (!R.empty()) {
8634 R.suppressDiagnostics();
8635
8636 if (isa<CXXRecordDecl>(DC)) {
8637 // Don't diagnose names we find in classes; we get much better
8638 // diagnostics for these from DiagnoseEmptyLookup.
8639 R.clear();
8640 return false;
8641 }
8642
8643 OverloadCandidateSet Candidates(FnLoc);
8644 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8645 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8646 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008647 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008648
8649 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008650 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008651 // No viable functions. Don't bother the user with notes for functions
8652 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008653 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008654 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008655 }
Richard Smith998a5912011-06-05 22:42:48 +00008656
8657 // Find the namespaces where ADL would have looked, and suggest
8658 // declaring the function there instead.
8659 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8660 Sema::AssociatedClassSet AssociatedClasses;
8661 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8662 AssociatedNamespaces,
8663 AssociatedClasses);
8664 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008665 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008666 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008667 for (Sema::AssociatedNamespaceSet::iterator
8668 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008669 end = AssociatedNamespaces.end(); it != end; ++it) {
8670 if (!Std->Encloses(*it))
8671 SuggestedNamespaces.insert(*it);
8672 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008673 } else {
8674 // Lacking the 'std::' namespace, use all of the associated namespaces.
8675 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008676 }
8677
8678 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8679 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008680 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008681 SemaRef.Diag(Best->Function->getLocation(),
8682 diag::note_not_found_by_two_phase_lookup)
8683 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008684 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008685 SemaRef.Diag(Best->Function->getLocation(),
8686 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008687 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008688 } else {
8689 // FIXME: It would be useful to list the associated namespaces here,
8690 // but the diagnostics infrastructure doesn't provide a way to produce
8691 // a localized representation of a list of items.
8692 SemaRef.Diag(Best->Function->getLocation(),
8693 diag::note_not_found_by_two_phase_lookup)
8694 << R.getLookupName() << 2;
8695 }
8696
8697 // Try to recover by calling this function.
8698 return true;
8699 }
8700
8701 R.clear();
8702 }
8703
8704 return false;
8705}
8706
8707/// Attempt to recover from ill-formed use of a non-dependent operator in a
8708/// template, where the non-dependent operator was declared after the template
8709/// was defined.
8710///
8711/// Returns true if a viable candidate was found and a diagnostic was issued.
8712static bool
8713DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8714 SourceLocation OpLoc,
8715 Expr **Args, unsigned NumArgs) {
8716 DeclarationName OpName =
8717 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8718 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8719 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8720 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8721}
8722
John McCalld681c392009-12-16 08:11:27 +00008723/// Attempts to recover from a call where no functions were found.
8724///
8725/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008726static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008727BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008728 UnresolvedLookupExpr *ULE,
8729 SourceLocation LParenLoc,
8730 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008731 SourceLocation RParenLoc,
8732 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008733
8734 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008735 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008736
John McCall57500772009-12-16 12:17:52 +00008737 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008738 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008739 if (ULE->hasExplicitTemplateArgs()) {
8740 ULE->copyTemplateArgumentsInto(TABuffer);
8741 ExplicitTemplateArgs = &TABuffer;
8742 }
8743
John McCalld681c392009-12-16 08:11:27 +00008744 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8745 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008746 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8747 ExplicitTemplateArgs, Args, NumArgs) &&
8748 (!EmptyLookup ||
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00008749 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00008750 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00008751 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008752
John McCall57500772009-12-16 12:17:52 +00008753 assert(!R.empty() && "lookup results empty despite recovery");
8754
8755 // Build an implicit member call if appropriate. Just drop the
8756 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008757 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008758 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008759 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8760 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008761 else if (ExplicitTemplateArgs)
8762 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8763 else
8764 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8765
8766 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008767 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008768
8769 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008770 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008771 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008772 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008773 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008774}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008775
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008776/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008777/// (which eventually refers to the declaration Func) and the call
8778/// arguments Args/NumArgs, attempt to resolve the function call down
8779/// to a specific function. If overload resolution succeeds, returns
8780/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008781/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008782/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008783ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008784Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008785 SourceLocation LParenLoc,
8786 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008787 SourceLocation RParenLoc,
8788 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008789#ifndef NDEBUG
8790 if (ULE->requiresADL()) {
8791 // To do ADL, we must have found an unqualified name.
8792 assert(!ULE->getQualifier() && "qualified name with ADL");
8793
8794 // We don't perform ADL for implicit declarations of builtins.
8795 // Verify that this was correctly set up.
8796 FunctionDecl *F;
8797 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8798 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8799 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00008800 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008801
John McCall57500772009-12-16 12:17:52 +00008802 // We don't perform ADL in C.
8803 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008804 } else
8805 assert(!ULE->isStdAssociatedNamespace() &&
8806 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008807#endif
8808
John McCall4124c492011-10-17 18:40:02 +00008809 UnbridgedCastsSet UnbridgedCasts;
8810 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
8811 return ExprError();
8812
John McCallbc077cf2010-02-08 23:07:23 +00008813 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008814
John McCall57500772009-12-16 12:17:52 +00008815 // Add the functions denoted by the callee to the set of candidate
8816 // functions, including those from argument-dependent lookup.
8817 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008818
8819 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008820 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8821 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00008822 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008823 // In Microsoft mode, if we are inside a template class member function then
8824 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00008825 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008826 // classes.
Francois Pichetf707ae62011-11-11 00:12:11 +00008827 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00008828 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008829 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8830 Context.DependentTy, VK_RValue,
8831 RParenLoc);
8832 CE->setTypeDependent(true);
8833 return Owned(CE);
8834 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008835 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008836 RParenLoc, /*EmptyLookup=*/true);
Francois Pichetbcf64712011-09-07 00:14:57 +00008837 }
John McCalld681c392009-12-16 08:11:27 +00008838
John McCall4124c492011-10-17 18:40:02 +00008839 UnbridgedCasts.restore();
8840
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008841 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008842 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008843 case OR_Success: {
8844 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008845 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008846 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00008847 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008848 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008849 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8850 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008851 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008852
Richard Smith998a5912011-06-05 22:42:48 +00008853 case OR_No_Viable_Function: {
8854 // Try to recover by looking for viable functions which the user might
8855 // have meant to call.
8856 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8857 Args, NumArgs, RParenLoc,
8858 /*EmptyLookup=*/false);
8859 if (!Recovery.isInvalid())
8860 return Recovery;
8861
Chris Lattner45d9d602009-02-17 07:29:20 +00008862 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008863 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008864 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008865 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008866 break;
Richard Smith998a5912011-06-05 22:42:48 +00008867 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008868
8869 case OR_Ambiguous:
8870 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008871 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008872 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008873 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008874
8875 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008876 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008877 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8878 << Best->Function->isDeleted()
8879 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008880 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008881 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008882 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00008883
8884 // We emitted an error for the unvailable/deleted function call but keep
8885 // the call in the AST.
8886 FunctionDecl *FDecl = Best->Function;
8887 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
8888 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
8889 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008890 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008891 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008892 }
8893
Douglas Gregorb412e172010-07-25 18:17:45 +00008894 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00008895 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008896}
8897
John McCall4c4c1df2010-01-26 03:27:55 +00008898static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00008899 return Functions.size() > 1 ||
8900 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8901}
8902
Douglas Gregor084d8552009-03-13 23:49:33 +00008903/// \brief Create a unary operation that may resolve to an overloaded
8904/// operator.
8905///
8906/// \param OpLoc The location of the operator itself (e.g., '*').
8907///
8908/// \param OpcIn The UnaryOperator::Opcode that describes this
8909/// operator.
8910///
8911/// \param Functions The set of non-member functions that will be
8912/// considered by overload resolution. The caller needs to build this
8913/// set based on the context using, e.g.,
8914/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8915/// set should not contain any member functions; those will be added
8916/// by CreateOverloadedUnaryOp().
8917///
8918/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00008919ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00008920Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8921 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00008922 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008923 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00008924
8925 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8926 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8927 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008928 // TODO: provide better source location info.
8929 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008930
John McCall4124c492011-10-17 18:40:02 +00008931 if (checkPlaceholderForOverload(*this, Input))
8932 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00008933
Douglas Gregor084d8552009-03-13 23:49:33 +00008934 Expr *Args[2] = { Input, 0 };
8935 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00008936
Douglas Gregor084d8552009-03-13 23:49:33 +00008937 // For post-increment and post-decrement, add the implicit '0' as
8938 // the second argument, so that we know this is a post-increment or
8939 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00008940 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008941 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008942 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8943 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00008944 NumArgs = 2;
8945 }
8946
8947 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00008948 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00008949 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008950 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00008951 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008952 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00008953 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008954
John McCall58cc69d2010-01-27 01:50:18 +00008955 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00008956 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008957 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008958 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008959 /*ADL*/ true, IsOverloaded(Fns),
8960 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00008961 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008962 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00008963 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008964 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00008965 OpLoc));
8966 }
8967
8968 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008969 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008970
8971 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008972 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00008973
8974 // Add operator candidates that are member functions.
8975 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8976
John McCall4c4c1df2010-01-26 03:27:55 +00008977 // Add candidates from ADL.
8978 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00008979 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00008980 /*ExplicitTemplateArgs*/ 0,
8981 CandidateSet);
8982
Douglas Gregor084d8552009-03-13 23:49:33 +00008983 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008984 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00008985
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008986 bool HadMultipleCandidates = (CandidateSet.size() > 1);
8987
Douglas Gregor084d8552009-03-13 23:49:33 +00008988 // Perform overload resolution.
8989 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008990 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008991 case OR_Success: {
8992 // We found a built-in operator or an overloaded operator.
8993 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00008994
Douglas Gregor084d8552009-03-13 23:49:33 +00008995 if (FnDecl) {
8996 // We matched an overloaded operator. Build a call to that
8997 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00008998
Chandler Carruth30141632011-02-25 19:41:05 +00008999 MarkDeclarationReferenced(OpLoc, FnDecl);
9000
Douglas Gregor084d8552009-03-13 23:49:33 +00009001 // Convert the arguments.
9002 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009003 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009004
John Wiegley01296292011-04-08 18:41:53 +00009005 ExprResult InputRes =
9006 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9007 Best->FoundDecl, Method);
9008 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009009 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009010 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009011 } else {
9012 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009013 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009014 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009015 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009016 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009017 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009018 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009019 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009020 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009021 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009022 }
9023
John McCall4fa0d5f2010-05-06 18:15:07 +00009024 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9025
John McCall7decc9e2010-11-18 06:31:45 +00009026 // Determine the result type.
9027 QualType ResultTy = FnDecl->getResultType();
9028 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9029 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009030
Douglas Gregor084d8552009-03-13 23:49:33 +00009031 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009032 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9033 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00009034 if (FnExpr.isInvalid())
9035 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009036
Eli Friedman030eee42009-11-18 03:58:17 +00009037 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009038 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009039 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009040 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009041
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009042 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009043 FnDecl))
9044 return ExprError();
9045
John McCallb268a282010-08-23 23:25:46 +00009046 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009047 } else {
9048 // We matched a built-in operator. Convert the arguments, then
9049 // break out so that we will build the appropriate built-in
9050 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009051 ExprResult InputRes =
9052 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9053 Best->Conversions[0], AA_Passing);
9054 if (InputRes.isInvalid())
9055 return ExprError();
9056 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009057 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009058 }
John Wiegley01296292011-04-08 18:41:53 +00009059 }
9060
9061 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009062 // This is an erroneous use of an operator which can be overloaded by
9063 // a non-member function. Check for non-member operators which were
9064 // defined too late to be candidates.
9065 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
9066 // FIXME: Recover by calling the found function.
9067 return ExprError();
9068
John Wiegley01296292011-04-08 18:41:53 +00009069 // No viable function; fall through to handling this as a
9070 // built-in operator, which will produce an error message for us.
9071 break;
9072
9073 case OR_Ambiguous:
9074 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9075 << UnaryOperator::getOpcodeStr(Opc)
9076 << Input->getType()
9077 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009078 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00009079 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9080 return ExprError();
9081
9082 case OR_Deleted:
9083 Diag(OpLoc, diag::err_ovl_deleted_oper)
9084 << Best->Function->isDeleted()
9085 << UnaryOperator::getOpcodeStr(Opc)
9086 << getDeletedOrUnavailableSuffix(Best->Function)
9087 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009088 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
9089 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009090 return ExprError();
9091 }
Douglas Gregor084d8552009-03-13 23:49:33 +00009092
9093 // Either we found no viable overloaded operator or we matched a
9094 // built-in operator. In either case, fall through to trying to
9095 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00009096 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009097}
9098
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009099/// \brief Create a binary operation that may resolve to an overloaded
9100/// operator.
9101///
9102/// \param OpLoc The location of the operator itself (e.g., '+').
9103///
9104/// \param OpcIn The BinaryOperator::Opcode that describes this
9105/// operator.
9106///
9107/// \param Functions The set of non-member functions that will be
9108/// considered by overload resolution. The caller needs to build this
9109/// set based on the context using, e.g.,
9110/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9111/// set should not contain any member functions; those will be added
9112/// by CreateOverloadedBinOp().
9113///
9114/// \param LHS Left-hand argument.
9115/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009116ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009117Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009118 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009119 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009120 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009121 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009122 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009123
9124 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9125 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9126 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9127
9128 // If either side is type-dependent, create an appropriate dependent
9129 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009130 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009131 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009132 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009133 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009134 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009135 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009136 Context.DependentTy,
9137 VK_RValue, OK_Ordinary,
9138 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009139
Douglas Gregor5287f092009-11-05 00:51:44 +00009140 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9141 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009142 VK_LValue,
9143 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009144 Context.DependentTy,
9145 Context.DependentTy,
9146 OpLoc));
9147 }
John McCall4c4c1df2010-01-26 03:27:55 +00009148
9149 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009150 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009151 // TODO: provide better source location info in DNLoc component.
9152 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009153 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009154 = UnresolvedLookupExpr::Create(Context, NamingClass,
9155 NestedNameSpecifierLoc(), OpNameInfo,
9156 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009157 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009158 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009159 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009160 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009161 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009162 OpLoc));
9163 }
9164
John McCall4124c492011-10-17 18:40:02 +00009165 // Always do placeholder-like conversions on the RHS.
9166 if (checkPlaceholderForOverload(*this, Args[1]))
9167 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009168
John McCall526ab472011-10-25 17:37:35 +00009169 // Do placeholder-like conversion on the LHS; note that we should
9170 // not get here with a PseudoObject LHS.
9171 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +00009172 if (checkPlaceholderForOverload(*this, Args[0]))
9173 return ExprError();
9174
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009175 // If this is the assignment operator, we only perform overload resolution
9176 // if the left-hand side is a class or enumeration type. This is actually
9177 // a hack. The standard requires that we do overload resolution between the
9178 // various built-in candidates, but as DR507 points out, this can lead to
9179 // problems. So we do it this way, which pretty much follows what GCC does.
9180 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009181 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009182 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009183
John McCalle26a8722010-12-04 08:14:53 +00009184 // If this is the .* operator, which is not overloadable, just
9185 // create a built-in binary operator.
9186 if (Opc == BO_PtrMemD)
9187 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9188
Douglas Gregor084d8552009-03-13 23:49:33 +00009189 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009190 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009191
9192 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009193 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009194
9195 // Add operator candidates that are member functions.
9196 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9197
John McCall4c4c1df2010-01-26 03:27:55 +00009198 // Add candidates from ADL.
9199 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9200 Args, 2,
9201 /*ExplicitTemplateArgs*/ 0,
9202 CandidateSet);
9203
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009204 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009205 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009206
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009207 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9208
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009209 // Perform overload resolution.
9210 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009211 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009212 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009213 // We found a built-in operator or an overloaded operator.
9214 FunctionDecl *FnDecl = Best->Function;
9215
9216 if (FnDecl) {
9217 // We matched an overloaded operator. Build a call to that
9218 // operator.
9219
Chandler Carruth30141632011-02-25 19:41:05 +00009220 MarkDeclarationReferenced(OpLoc, FnDecl);
9221
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009222 // Convert the arguments.
9223 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009224 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009225 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009226
Chandler Carruth8e543b32010-12-12 08:17:55 +00009227 ExprResult Arg1 =
9228 PerformCopyInitialization(
9229 InitializedEntity::InitializeParameter(Context,
9230 FnDecl->getParamDecl(0)),
9231 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009232 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009233 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009234
John Wiegley01296292011-04-08 18:41:53 +00009235 ExprResult Arg0 =
9236 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9237 Best->FoundDecl, Method);
9238 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009239 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009240 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009241 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009242 } else {
9243 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009244 ExprResult Arg0 = PerformCopyInitialization(
9245 InitializedEntity::InitializeParameter(Context,
9246 FnDecl->getParamDecl(0)),
9247 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009248 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009249 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009250
Chandler Carruth8e543b32010-12-12 08:17:55 +00009251 ExprResult Arg1 =
9252 PerformCopyInitialization(
9253 InitializedEntity::InitializeParameter(Context,
9254 FnDecl->getParamDecl(1)),
9255 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009256 if (Arg1.isInvalid())
9257 return ExprError();
9258 Args[0] = LHS = Arg0.takeAs<Expr>();
9259 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009260 }
9261
John McCall4fa0d5f2010-05-06 18:15:07 +00009262 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9263
John McCall7decc9e2010-11-18 06:31:45 +00009264 // Determine the result type.
9265 QualType ResultTy = FnDecl->getResultType();
9266 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9267 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009268
9269 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009270 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9271 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009272 if (FnExpr.isInvalid())
9273 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009274
John McCallb268a282010-08-23 23:25:46 +00009275 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009276 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009277 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009278
9279 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009280 FnDecl))
9281 return ExprError();
9282
John McCallb268a282010-08-23 23:25:46 +00009283 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009284 } else {
9285 // We matched a built-in operator. Convert the arguments, then
9286 // break out so that we will build the appropriate built-in
9287 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009288 ExprResult ArgsRes0 =
9289 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9290 Best->Conversions[0], AA_Passing);
9291 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009292 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009293 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009294
John Wiegley01296292011-04-08 18:41:53 +00009295 ExprResult ArgsRes1 =
9296 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9297 Best->Conversions[1], AA_Passing);
9298 if (ArgsRes1.isInvalid())
9299 return ExprError();
9300 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009301 break;
9302 }
9303 }
9304
Douglas Gregor66950a32009-09-30 21:46:01 +00009305 case OR_No_Viable_Function: {
9306 // C++ [over.match.oper]p9:
9307 // If the operator is the operator , [...] and there are no
9308 // viable functions, then the operator is assumed to be the
9309 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00009310 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00009311 break;
9312
Chandler Carruth8e543b32010-12-12 08:17:55 +00009313 // For class as left operand for assignment or compound assigment
9314 // operator do not fall through to handling in built-in, but report that
9315 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00009316 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009317 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00009318 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00009319 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9320 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00009321 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00009322 } else {
Richard Smith998a5912011-06-05 22:42:48 +00009323 // This is an erroneous use of an operator which can be overloaded by
9324 // a non-member function. Check for non-member operators which were
9325 // defined too late to be candidates.
9326 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9327 // FIXME: Recover by calling the found function.
9328 return ExprError();
9329
Douglas Gregor66950a32009-09-30 21:46:01 +00009330 // No viable function; try to create a built-in operation, which will
9331 // produce an error. Then, show the non-viable candidates.
9332 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00009333 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009334 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00009335 "C++ binary operator overloading is missing candidates!");
9336 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00009337 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9338 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00009339 return move(Result);
9340 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009341
9342 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009343 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009344 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00009345 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00009346 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009347 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9348 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009349 return ExprError();
9350
9351 case OR_Deleted:
9352 Diag(OpLoc, diag::err_ovl_deleted_oper)
9353 << Best->Function->isDeleted()
9354 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009355 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00009356 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009357 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9358 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009359 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00009360 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009361
Douglas Gregor66950a32009-09-30 21:46:01 +00009362 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00009363 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009364}
9365
John McCalldadc5752010-08-24 06:29:42 +00009366ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00009367Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9368 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00009369 Expr *Base, Expr *Idx) {
9370 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00009371 DeclarationName OpName =
9372 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9373
9374 // If either side is type-dependent, create an appropriate dependent
9375 // expression.
9376 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9377
John McCall58cc69d2010-01-27 01:50:18 +00009378 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009379 // CHECKME: no 'operator' keyword?
9380 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9381 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00009382 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009383 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009384 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009385 /*ADL*/ true, /*Overloaded*/ false,
9386 UnresolvedSetIterator(),
9387 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00009388 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00009389
Sebastian Redladba46e2009-10-29 20:17:01 +00009390 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9391 Args, 2,
9392 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009393 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00009394 RLoc));
9395 }
9396
John McCall4124c492011-10-17 18:40:02 +00009397 // Handle placeholders on both operands.
9398 if (checkPlaceholderForOverload(*this, Args[0]))
9399 return ExprError();
9400 if (checkPlaceholderForOverload(*this, Args[1]))
9401 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009402
Sebastian Redladba46e2009-10-29 20:17:01 +00009403 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009404 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009405
9406 // Subscript can only be overloaded as a member function.
9407
9408 // Add operator candidates that are member functions.
9409 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9410
9411 // Add builtin operator candidates.
9412 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9413
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009414 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9415
Sebastian Redladba46e2009-10-29 20:17:01 +00009416 // Perform overload resolution.
9417 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009418 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00009419 case OR_Success: {
9420 // We found a built-in operator or an overloaded operator.
9421 FunctionDecl *FnDecl = Best->Function;
9422
9423 if (FnDecl) {
9424 // We matched an overloaded operator. Build a call to that
9425 // operator.
9426
Chandler Carruth30141632011-02-25 19:41:05 +00009427 MarkDeclarationReferenced(LLoc, FnDecl);
9428
John McCalla0296f72010-03-19 07:35:19 +00009429 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009430 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00009431
Sebastian Redladba46e2009-10-29 20:17:01 +00009432 // Convert the arguments.
9433 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00009434 ExprResult Arg0 =
9435 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9436 Best->FoundDecl, Method);
9437 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009438 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009439 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009440
Anders Carlssona68e51e2010-01-29 18:37:50 +00009441 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009442 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00009443 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009444 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00009445 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009446 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00009447 Owned(Args[1]));
9448 if (InputInit.isInvalid())
9449 return ExprError();
9450
9451 Args[1] = InputInit.takeAs<Expr>();
9452
Sebastian Redladba46e2009-10-29 20:17:01 +00009453 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00009454 QualType ResultTy = FnDecl->getResultType();
9455 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9456 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00009457
9458 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00009459 DeclarationNameLoc LocInfo;
9460 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9461 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009462 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9463 HadMultipleCandidates,
9464 LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00009465 if (FnExpr.isInvalid())
9466 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009467
John McCallb268a282010-08-23 23:25:46 +00009468 CXXOperatorCallExpr *TheCall =
9469 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00009470 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00009471 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009472
John McCallb268a282010-08-23 23:25:46 +00009473 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00009474 FnDecl))
9475 return ExprError();
9476
John McCallb268a282010-08-23 23:25:46 +00009477 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00009478 } else {
9479 // We matched a built-in operator. Convert the arguments, then
9480 // break out so that we will build the appropriate built-in
9481 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009482 ExprResult ArgsRes0 =
9483 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9484 Best->Conversions[0], AA_Passing);
9485 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009486 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009487 Args[0] = ArgsRes0.take();
9488
9489 ExprResult ArgsRes1 =
9490 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9491 Best->Conversions[1], AA_Passing);
9492 if (ArgsRes1.isInvalid())
9493 return ExprError();
9494 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009495
9496 break;
9497 }
9498 }
9499
9500 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00009501 if (CandidateSet.empty())
9502 Diag(LLoc, diag::err_ovl_no_oper)
9503 << Args[0]->getType() << /*subscript*/ 0
9504 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9505 else
9506 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9507 << Args[0]->getType()
9508 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009509 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9510 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00009511 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009512 }
9513
9514 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009515 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009516 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00009517 << Args[0]->getType() << Args[1]->getType()
9518 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009519 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9520 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009521 return ExprError();
9522
9523 case OR_Deleted:
9524 Diag(LLoc, diag::err_ovl_deleted_oper)
9525 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009526 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00009527 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009528 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9529 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009530 return ExprError();
9531 }
9532
9533 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00009534 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009535}
9536
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009537/// BuildCallToMemberFunction - Build a call to a member
9538/// function. MemExpr is the expression that refers to the member
9539/// function (and includes the object parameter), Args/NumArgs are the
9540/// arguments to the function call (not including the object
9541/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00009542/// expression refers to a non-static member function or an overloaded
9543/// member function.
John McCalldadc5752010-08-24 06:29:42 +00009544ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00009545Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9546 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009547 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00009548 assert(MemExprE->getType() == Context.BoundMemberTy ||
9549 MemExprE->getType() == Context.OverloadTy);
9550
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009551 // Dig out the member expression. This holds both the object
9552 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00009553 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009554
John McCall0009fcc2011-04-26 20:42:42 +00009555 // Determine whether this is a call to a pointer-to-member function.
9556 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9557 assert(op->getType() == Context.BoundMemberTy);
9558 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9559
9560 QualType fnType =
9561 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9562
9563 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9564 QualType resultType = proto->getCallResultType(Context);
9565 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9566
9567 // Check that the object type isn't more qualified than the
9568 // member function we're calling.
9569 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9570
9571 QualType objectType = op->getLHS()->getType();
9572 if (op->getOpcode() == BO_PtrMemI)
9573 objectType = objectType->castAs<PointerType>()->getPointeeType();
9574 Qualifiers objectQuals = objectType.getQualifiers();
9575
9576 Qualifiers difference = objectQuals - funcQuals;
9577 difference.removeObjCGCAttr();
9578 difference.removeAddressSpace();
9579 if (difference) {
9580 std::string qualsString = difference.getAsString();
9581 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9582 << fnType.getUnqualifiedType()
9583 << qualsString
9584 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9585 }
9586
9587 CXXMemberCallExpr *call
9588 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9589 resultType, valueKind, RParenLoc);
9590
9591 if (CheckCallReturnType(proto->getResultType(),
9592 op->getRHS()->getSourceRange().getBegin(),
9593 call, 0))
9594 return ExprError();
9595
9596 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9597 return ExprError();
9598
9599 return MaybeBindToTemporary(call);
9600 }
9601
John McCall4124c492011-10-17 18:40:02 +00009602 UnbridgedCastsSet UnbridgedCasts;
9603 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9604 return ExprError();
9605
John McCall10eae182009-11-30 22:42:35 +00009606 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009607 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009608 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009609 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009610 if (isa<MemberExpr>(NakedMemExpr)) {
9611 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009612 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009613 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009614 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +00009615 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +00009616 } else {
9617 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009618 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009619
John McCall6e9f8f62009-12-03 04:06:58 +00009620 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009621 Expr::Classification ObjectClassification
9622 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9623 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009624
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009625 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009626 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009627
John McCall2d74de92009-12-01 22:10:20 +00009628 // FIXME: avoid copy.
9629 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9630 if (UnresExpr->hasExplicitTemplateArgs()) {
9631 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9632 TemplateArgs = &TemplateArgsBuffer;
9633 }
9634
John McCall10eae182009-11-30 22:42:35 +00009635 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9636 E = UnresExpr->decls_end(); I != E; ++I) {
9637
John McCall6e9f8f62009-12-03 04:06:58 +00009638 NamedDecl *Func = *I;
9639 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9640 if (isa<UsingShadowDecl>(Func))
9641 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9642
Douglas Gregor02824322011-01-26 19:30:28 +00009643
Francois Pichet64225792011-01-18 05:04:39 +00009644 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +00009645 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +00009646 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9647 CandidateSet);
9648 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009649 // If explicit template arguments were provided, we can't call a
9650 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009651 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009652 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009653
John McCalla0296f72010-03-19 07:35:19 +00009654 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009655 ObjectClassification,
9656 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009657 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009658 } else {
John McCall10eae182009-11-30 22:42:35 +00009659 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009660 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009661 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009662 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009663 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009664 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009665 }
Mike Stump11289f42009-09-09 15:08:12 +00009666
John McCall10eae182009-11-30 22:42:35 +00009667 DeclarationName DeclName = UnresExpr->getMemberName();
9668
John McCall4124c492011-10-17 18:40:02 +00009669 UnbridgedCasts.restore();
9670
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009671 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009672 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009673 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009674 case OR_Success:
9675 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009676 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009677 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009678 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009679 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009680 break;
9681
9682 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009683 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009684 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009685 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009686 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009687 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009688 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009689
9690 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009691 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009692 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009693 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009694 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009695 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009696
9697 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009698 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009699 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009700 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009701 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009702 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009703 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009704 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009705 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009706 }
9707
John McCall16df1e52010-03-30 21:47:33 +00009708 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009709
John McCall2d74de92009-12-01 22:10:20 +00009710 // If overload resolution picked a static member, build a
9711 // non-member call based on that function.
9712 if (Method->isStatic()) {
9713 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9714 Args, NumArgs, RParenLoc);
9715 }
9716
John McCall10eae182009-11-30 22:42:35 +00009717 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009718 }
9719
John McCall7decc9e2010-11-18 06:31:45 +00009720 QualType ResultType = Method->getResultType();
9721 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9722 ResultType = ResultType.getNonLValueExprType(Context);
9723
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009724 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009725 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009726 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009727 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009728
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009729 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009730 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009731 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009732 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009733
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009734 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009735 // We only need to do this if there was actually an overload; otherwise
9736 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009737 if (!Method->isStatic()) {
9738 ExprResult ObjectArg =
9739 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9740 FoundDecl, Method);
9741 if (ObjectArg.isInvalid())
9742 return ExprError();
9743 MemExpr->setBase(ObjectArg.take());
9744 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009745
9746 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009747 const FunctionProtoType *Proto =
9748 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009749 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009750 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009751 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009752
John McCallb268a282010-08-23 23:25:46 +00009753 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009754 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009755
Anders Carlsson47061ee2011-05-06 14:25:31 +00009756 if ((isa<CXXConstructorDecl>(CurContext) ||
9757 isa<CXXDestructorDecl>(CurContext)) &&
9758 TheCall->getMethodDecl()->isPure()) {
9759 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9760
Chandler Carruth59259262011-06-27 08:31:58 +00009761 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009762 Diag(MemExpr->getLocStart(),
9763 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9764 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9765 << MD->getParent()->getDeclName();
9766
9767 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009768 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009769 }
John McCallb268a282010-08-23 23:25:46 +00009770 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009771}
9772
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009773/// BuildCallToObjectOfClassType - Build a call to an object of class
9774/// type (C++ [over.call.object]), which can end up invoking an
9775/// overloaded function call operator (@c operator()) or performing a
9776/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009777ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009778Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009779 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009780 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009781 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +00009782 if (checkPlaceholderForOverload(*this, Obj))
9783 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009784 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +00009785
9786 UnbridgedCastsSet UnbridgedCasts;
9787 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9788 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009789
John Wiegley01296292011-04-08 18:41:53 +00009790 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9791 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009792
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009793 // C++ [over.call.object]p1:
9794 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009795 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009796 // candidate functions includes at least the function call
9797 // operators of T. The function call operators of T are obtained by
9798 // ordinary lookup of the name operator() in the context of
9799 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009800 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009801 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009802
John Wiegley01296292011-04-08 18:41:53 +00009803 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009804 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009805 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009806 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009807
John McCall27b18f82009-11-17 02:14:36 +00009808 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9809 LookupQualifiedName(R, Record->getDecl());
9810 R.suppressDiagnostics();
9811
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009812 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009813 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009814 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9815 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009816 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009818
Douglas Gregorab7897a2008-11-19 22:57:39 +00009819 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009820 // In addition, for each (non-explicit in C++0x) conversion function
9821 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +00009822 //
9823 // operator conversion-type-id () cv-qualifier;
9824 //
9825 // where cv-qualifier is the same cv-qualification as, or a
9826 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009827 // denotes the type "pointer to function of (P1,...,Pn) returning
9828 // R", or the type "reference to pointer to function of
9829 // (P1,...,Pn) returning R", or the type "reference to function
9830 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009831 // is also considered as a candidate function. Similarly,
9832 // surrogate call functions are added to the set of candidate
9833 // functions for each conversion function declared in an
9834 // accessible base class provided the function is not hidden
9835 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009836 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009837 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009838 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009839 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009840 NamedDecl *D = *I;
9841 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9842 if (isa<UsingShadowDecl>(D))
9843 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009844
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009845 // Skip over templated conversion functions; they aren't
9846 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009847 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009848 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009849
John McCall6e9f8f62009-12-03 04:06:58 +00009850 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009851 if (!Conv->isExplicit()) {
9852 // Strip the reference type (if any) and then the pointer type (if
9853 // any) to get down to what might be a function type.
9854 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9855 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9856 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +00009857
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009858 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9859 {
9860 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9861 Object.get(), Args, NumArgs, CandidateSet);
9862 }
9863 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00009864 }
Mike Stump11289f42009-09-09 15:08:12 +00009865
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009866 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9867
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009868 // Perform overload resolution.
9869 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009870 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009871 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009872 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009873 // Overload resolution succeeded; we'll build the appropriate call
9874 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009875 break;
9876
9877 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009878 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009879 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9880 << Object.get()->getType() << /*call*/ 1
9881 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009882 else
John Wiegley01296292011-04-08 18:41:53 +00009883 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009884 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009885 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009886 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009887 break;
9888
9889 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009890 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009891 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009892 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009893 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009894 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009895
9896 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00009897 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00009898 diag::err_ovl_deleted_object_call)
9899 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +00009900 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009901 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +00009902 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009903 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009904 break;
Mike Stump11289f42009-09-09 15:08:12 +00009905 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009906
Douglas Gregorb412e172010-07-25 18:17:45 +00009907 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009908 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009909
John McCall4124c492011-10-17 18:40:02 +00009910 UnbridgedCasts.restore();
9911
Douglas Gregorab7897a2008-11-19 22:57:39 +00009912 if (Best->Function == 0) {
9913 // Since there is no function declaration, this is one of the
9914 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00009915 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00009916 = cast<CXXConversionDecl>(
9917 Best->Conversions[0].UserDefined.ConversionFunction);
9918
John Wiegley01296292011-04-08 18:41:53 +00009919 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009920 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009921
Douglas Gregorab7897a2008-11-19 22:57:39 +00009922 // We selected one of the surrogate functions that converts the
9923 // object parameter to a function pointer. Perform the conversion
9924 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009925
Fariborz Jahanian774cf792009-09-28 18:35:46 +00009926 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00009927 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009928 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
9929 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00009930 if (Call.isInvalid())
9931 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00009932 // Record usage of conversion in an implicit cast.
9933 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
9934 CK_UserDefinedConversion,
9935 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009936
Douglas Gregor668443e2011-01-20 00:18:04 +00009937 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00009938 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00009939 }
9940
Chandler Carruth30141632011-02-25 19:41:05 +00009941 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009942 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009943 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009944
Douglas Gregorab7897a2008-11-19 22:57:39 +00009945 // We found an overloaded operator(). Build a CXXOperatorCallExpr
9946 // that calls this method, using Object for the implicit object
9947 // parameter and passing along the remaining arguments.
9948 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00009949 const FunctionProtoType *Proto =
9950 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009951
9952 unsigned NumArgsInProto = Proto->getNumArgs();
9953 unsigned NumArgsToCheck = NumArgs;
9954
9955 // Build the full argument list for the method call (the
9956 // implicit object parameter is placed at the beginning of the
9957 // list).
9958 Expr **MethodArgs;
9959 if (NumArgs < NumArgsInProto) {
9960 NumArgsToCheck = NumArgsInProto;
9961 MethodArgs = new Expr*[NumArgsInProto + 1];
9962 } else {
9963 MethodArgs = new Expr*[NumArgs + 1];
9964 }
John Wiegley01296292011-04-08 18:41:53 +00009965 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009966 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9967 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00009968
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009969 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
9970 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00009971 if (NewFn.isInvalid())
9972 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009973
9974 // Once we've built TheCall, all of the expressions are properly
9975 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00009976 QualType ResultTy = Method->getResultType();
9977 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9978 ResultTy = ResultTy.getNonLValueExprType(Context);
9979
John McCallb268a282010-08-23 23:25:46 +00009980 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009981 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +00009982 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00009983 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009984 delete [] MethodArgs;
9985
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009986 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00009987 Method))
9988 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009989
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009990 // We may have default arguments. If so, we need to allocate more
9991 // slots in the call for them.
9992 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00009993 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009994 else if (NumArgs > NumArgsInProto)
9995 NumArgsToCheck = NumArgsInProto;
9996
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009997 bool IsError = false;
9998
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009999 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010000 ExprResult ObjRes =
10001 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10002 Best->FoundDecl, Method);
10003 if (ObjRes.isInvalid())
10004 IsError = true;
10005 else
10006 Object = move(ObjRes);
10007 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010008
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010009 // Check the argument types.
10010 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010011 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010012 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010013 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010014
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010015 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010016
John McCalldadc5752010-08-24 06:29:42 +000010017 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010018 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010019 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010020 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010021 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010022
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010023 IsError |= InputInit.isInvalid();
10024 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010025 } else {
John McCalldadc5752010-08-24 06:29:42 +000010026 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010027 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10028 if (DefArg.isInvalid()) {
10029 IsError = true;
10030 break;
10031 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010032
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010033 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010034 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010035
10036 TheCall->setArg(i + 1, Arg);
10037 }
10038
10039 // If this is a variadic call, handle args passed through "...".
10040 if (Proto->isVariadic()) {
10041 // Promote the arguments (C99 6.5.2.2p7).
10042 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010043 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10044 IsError |= Arg.isInvalid();
10045 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010046 }
10047 }
10048
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010049 if (IsError) return true;
10050
John McCallb268a282010-08-23 23:25:46 +000010051 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000010052 return true;
10053
John McCalle172be52010-08-24 06:09:16 +000010054 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010055}
10056
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010057/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000010058/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010059/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000010060ExprResult
John McCallb268a282010-08-23 23:25:46 +000010061Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010062 assert(Base->getType()->isRecordType() &&
10063 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000010064
John McCall4124c492011-10-17 18:40:02 +000010065 if (checkPlaceholderForOverload(*this, Base))
10066 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010067
John McCallbc077cf2010-02-08 23:07:23 +000010068 SourceLocation Loc = Base->getExprLoc();
10069
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010070 // C++ [over.ref]p1:
10071 //
10072 // [...] An expression x->m is interpreted as (x.operator->())->m
10073 // for a class object x of type T if T::operator->() exists and if
10074 // the operator is selected as the best match function by the
10075 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000010076 DeclarationName OpName =
10077 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000010078 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010079 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000010080
John McCallbc077cf2010-02-08 23:07:23 +000010081 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +000010082 PDiag(diag::err_typecheck_incomplete_tag)
10083 << Base->getSourceRange()))
10084 return ExprError();
10085
John McCall27b18f82009-11-17 02:14:36 +000010086 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10087 LookupQualifiedName(R, BaseRecord->getDecl());
10088 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000010089
10090 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000010091 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000010092 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10093 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000010094 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010095
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010096 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10097
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010098 // Perform overload resolution.
10099 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010100 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010101 case OR_Success:
10102 // Overload resolution succeeded; we'll build the call below.
10103 break;
10104
10105 case OR_No_Viable_Function:
10106 if (CandidateSet.empty())
10107 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000010108 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010109 else
10110 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000010111 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010112 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010113 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010114
10115 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010116 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10117 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010118 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010119 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010120
10121 case OR_Deleted:
10122 Diag(OpLoc, diag::err_ovl_deleted_oper)
10123 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010124 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010125 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010126 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010127 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010128 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010129 }
10130
Chandler Carruth30141632011-02-25 19:41:05 +000010131 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010132 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010133 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010134
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010135 // Convert the object parameter.
10136 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010137 ExprResult BaseResult =
10138 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10139 Best->FoundDecl, Method);
10140 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010141 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010142 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010143
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010144 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010145 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
10146 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010147 if (FnExpr.isInvalid())
10148 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010149
John McCall7decc9e2010-11-18 06:31:45 +000010150 QualType ResultTy = Method->getResultType();
10151 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10152 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010153 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010154 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010155 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010156
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010157 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010158 Method))
10159 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010160
10161 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010162}
10163
Douglas Gregorcd695e52008-11-10 20:40:00 +000010164/// FixOverloadedFunctionReference - E is an expression that refers to
10165/// a C++ overloaded function (possibly with some parentheses and
10166/// perhaps a '&' around it). We have resolved the overloaded function
10167/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000010168/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000010169Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000010170 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000010171 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010172 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10173 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010174 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010175 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010176
Douglas Gregor51c538b2009-11-20 19:42:02 +000010177 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010178 }
10179
Douglas Gregor51c538b2009-11-20 19:42:02 +000010180 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010181 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10182 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010183 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000010184 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000010185 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000010186 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000010187 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010188 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010189
10190 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000010191 ICE->getCastKind(),
10192 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000010193 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010194 }
10195
Douglas Gregor51c538b2009-11-20 19:42:02 +000010196 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000010197 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000010198 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010199 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10200 if (Method->isStatic()) {
10201 // Do nothing: static member functions aren't any different
10202 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000010203 } else {
John McCalle66edc12009-11-24 19:00:30 +000010204 // Fix the sub expression, which really has to be an
10205 // UnresolvedLookupExpr holding an overloaded member function
10206 // or template.
John McCall16df1e52010-03-30 21:47:33 +000010207 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10208 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000010209 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010210 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010211
John McCalld14a8642009-11-21 08:51:07 +000010212 assert(isa<DeclRefExpr>(SubExpr)
10213 && "fixed to something other than a decl ref");
10214 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10215 && "fixed to a member ref with no nested name qualifier");
10216
10217 // We have taken the address of a pointer to member
10218 // function. Perform the computation here so that we get the
10219 // appropriate pointer to member type.
10220 QualType ClassType
10221 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10222 QualType MemPtrType
10223 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10224
John McCall7decc9e2010-11-18 06:31:45 +000010225 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10226 VK_RValue, OK_Ordinary,
10227 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010228 }
10229 }
John McCall16df1e52010-03-30 21:47:33 +000010230 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10231 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010232 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010233 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010234
John McCalle3027922010-08-25 11:45:40 +000010235 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010236 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000010237 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010238 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010239 }
John McCalld14a8642009-11-21 08:51:07 +000010240
10241 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000010242 // FIXME: avoid copy.
10243 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000010244 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000010245 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10246 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000010247 }
10248
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010249 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10250 ULE->getQualifierLoc(),
10251 Fn,
10252 ULE->getNameLoc(),
10253 Fn->getType(),
10254 VK_LValue,
10255 Found.getDecl(),
10256 TemplateArgs);
10257 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10258 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000010259 }
10260
John McCall10eae182009-11-30 22:42:35 +000010261 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000010262 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000010263 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10264 if (MemExpr->hasExplicitTemplateArgs()) {
10265 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10266 TemplateArgs = &TemplateArgsBuffer;
10267 }
John McCall6b51f282009-11-23 01:53:49 +000010268
John McCall2d74de92009-12-01 22:10:20 +000010269 Expr *Base;
10270
John McCall7decc9e2010-11-18 06:31:45 +000010271 // If we're filling in a static method where we used to have an
10272 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000010273 if (MemExpr->isImplicitAccess()) {
10274 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010275 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10276 MemExpr->getQualifierLoc(),
10277 Fn,
10278 MemExpr->getMemberLoc(),
10279 Fn->getType(),
10280 VK_LValue,
10281 Found.getDecl(),
10282 TemplateArgs);
10283 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10284 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000010285 } else {
10286 SourceLocation Loc = MemExpr->getMemberLoc();
10287 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000010288 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +000010289 Base = new (Context) CXXThisExpr(Loc,
10290 MemExpr->getBaseType(),
10291 /*isImplicit=*/true);
10292 }
John McCall2d74de92009-12-01 22:10:20 +000010293 } else
John McCallc3007a22010-10-26 07:05:15 +000010294 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000010295
John McCall4adb38c2011-04-27 00:36:17 +000010296 ExprValueKind valueKind;
10297 QualType type;
10298 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10299 valueKind = VK_LValue;
10300 type = Fn->getType();
10301 } else {
10302 valueKind = VK_RValue;
10303 type = Context.BoundMemberTy;
10304 }
10305
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010306 MemberExpr *ME = MemberExpr::Create(Context, Base,
10307 MemExpr->isArrow(),
10308 MemExpr->getQualifierLoc(),
10309 Fn,
10310 Found,
10311 MemExpr->getMemberNameInfo(),
10312 TemplateArgs,
10313 type, valueKind, OK_Ordinary);
10314 ME->setHadMultipleCandidates(true);
10315 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010316 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010317
John McCallc3007a22010-10-26 07:05:15 +000010318 llvm_unreachable("Invalid reference to overloaded function");
10319 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010320}
10321
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010322ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000010323 DeclAccessPair Found,
10324 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000010325 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000010326}
10327
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010328} // end namespace clang