blob: 86181040cecd047f9a21ed8eec004b8fe3a4662f [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
Sebastian Redldf888642011-12-03 14:54:30 +00003622TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003623 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.
Sebastian Redldf888642011-12-03 14:54:30 +00003953 if (ToType->isReferenceType()) {
3954 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
3955 // mention initializer lists in any way. So we go by what list-
3956 // initialization would do and try to extrapolate from that.
3957
3958 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
3959
3960 // If the initializer list has a single element that is reference-related
3961 // to the parameter type, we initialize the reference from that.
3962 if (From->getNumInits() == 1) {
3963 Expr *Init = From->getInit(0);
3964
3965 QualType T2 = Init->getType();
3966
3967 // If the initializer is the address of an overloaded function, try
3968 // to resolve the overloaded function. If all goes well, T2 is the
3969 // type of the resulting function.
3970 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3971 DeclAccessPair Found;
3972 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
3973 Init, ToType, false, Found))
3974 T2 = Fn->getType();
3975 }
3976
3977 // Compute some basic properties of the types and the initializer.
3978 bool dummy1 = false;
3979 bool dummy2 = false;
3980 bool dummy3 = false;
3981 Sema::ReferenceCompareResult RefRelationship
3982 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
3983 dummy2, dummy3);
3984
3985 if (RefRelationship >= Sema::Ref_Related)
3986 return TryReferenceInit(S, Init, ToType,
3987 /*FIXME:*/From->getLocStart(),
3988 SuppressUserConversions,
3989 /*AllowExplicit=*/false);
3990 }
3991
3992 // Otherwise, we bind the reference to a temporary created from the
3993 // initializer list.
3994 Result = TryListConversion(S, From, T1, SuppressUserConversions,
3995 InOverloadResolution,
3996 AllowObjCWritebackConversion);
3997 if (Result.isFailure())
3998 return Result;
3999 assert(!Result.isEllipsis() &&
4000 "Sub-initialization cannot result in ellipsis conversion.");
4001
4002 // Can we even bind to a temporary?
4003 if (ToType->isRValueReferenceType() ||
4004 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4005 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4006 Result.UserDefined.After;
4007 SCS.ReferenceBinding = true;
4008 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4009 SCS.BindsToRvalue = true;
4010 SCS.BindsToFunctionLvalue = false;
4011 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4012 SCS.ObjCLifetimeConversionBinding = false;
4013 } else
4014 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4015 From, ToType);
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004016 return Result;
Sebastian Redldf888642011-12-03 14:54:30 +00004017 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004018
4019 // C++11 [over.ics.list]p6:
4020 // Otherwise, if the parameter type is not a class:
4021 if (!ToType->isRecordType()) {
4022 // - if the initializer list has one element, the implicit conversion
4023 // sequence is the one required to convert the element to the
4024 // parameter type.
4025 // FIXME: Catch narrowing here?
4026 unsigned NumInits = From->getNumInits();
4027 if (NumInits == 1)
4028 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4029 SuppressUserConversions,
4030 InOverloadResolution,
4031 AllowObjCWritebackConversion);
4032 // - if the initializer list has no elements, the implicit conversion
4033 // sequence is the identity conversion.
4034 else if (NumInits == 0) {
4035 Result.setStandard();
4036 Result.Standard.setAsIdentityConversion();
4037 }
4038 return Result;
4039 }
4040
4041 // C++11 [over.ics.list]p7:
4042 // In all cases other than those enumerated above, no conversion is possible
4043 return Result;
4044}
4045
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004046/// TryCopyInitialization - Try to copy-initialize a value of type
4047/// ToType from the expression From. Return the implicit conversion
4048/// sequence required to pass this argument, which may be a bad
4049/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00004050/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00004051/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004052static ImplicitConversionSequence
4053TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004054 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004055 bool InOverloadResolution,
4056 bool AllowObjCWritebackConversion) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00004057 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4058 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4059 InOverloadResolution,AllowObjCWritebackConversion);
4060
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004061 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004062 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004063 /*FIXME:*/From->getLocStart(),
4064 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00004065 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00004066
John McCall5c32be02010-08-24 20:38:10 +00004067 return TryImplicitConversion(S, From, ToType,
4068 SuppressUserConversions,
4069 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00004070 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00004071 /*CStyle=*/false,
4072 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00004073}
4074
Anna Zaks1b068122011-07-28 19:46:48 +00004075static bool TryCopyInitialization(const CanQualType FromQTy,
4076 const CanQualType ToQTy,
4077 Sema &S,
4078 SourceLocation Loc,
4079 ExprValueKind FromVK) {
4080 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4081 ImplicitConversionSequence ICS =
4082 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4083
4084 return !ICS.isBad();
4085}
4086
Douglas Gregor436424c2008-11-18 23:14:02 +00004087/// TryObjectArgumentInitialization - Try to initialize the object
4088/// parameter of the given member function (@c Method) from the
4089/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00004090static ImplicitConversionSequence
4091TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004092 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00004093 CXXMethodDecl *Method,
4094 CXXRecordDecl *ActingContext) {
4095 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00004096 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4097 // const volatile object.
4098 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4099 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00004100 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00004101
4102 // Set up the conversion sequence as a "bad" conversion, to allow us
4103 // to exit early.
4104 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00004105
4106 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00004107 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00004108 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004109 FromType = PT->getPointeeType();
4110
Douglas Gregor02824322011-01-26 19:30:28 +00004111 // When we had a pointer, it's implicitly dereferenced, so we
4112 // better have an lvalue.
4113 assert(FromClassification.isLValue());
4114 }
4115
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004116 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00004117
Douglas Gregor02824322011-01-26 19:30:28 +00004118 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004119 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00004120 // parameter is
4121 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004122 // - "lvalue reference to cv X" for functions declared without a
4123 // ref-qualifier or with the & ref-qualifier
4124 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00004125 // ref-qualifier
4126 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004127 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00004128 // cv-qualification on the member function declaration.
4129 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004130 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00004131 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00004132 // (C++ [over.match.funcs]p5). We perform a simplified version of
4133 // reference binding here, that allows class rvalues to bind to
4134 // non-constant references.
4135
Douglas Gregor02824322011-01-26 19:30:28 +00004136 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00004137 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004138 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004139 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00004140 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00004141 ICS.setBad(BadConversionSequence::bad_qualifiers,
4142 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004143 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004144 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004145
4146 // Check that we have either the same type or a derived type. It
4147 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00004148 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00004149 ImplicitConversionKind SecondKind;
4150 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4151 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00004152 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00004153 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00004154 else {
John McCall65eb8792010-02-25 01:37:24 +00004155 ICS.setBad(BadConversionSequence::unrelated_class,
4156 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004157 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00004158 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004159
Douglas Gregor02824322011-01-26 19:30:28 +00004160 // Check the ref-qualifier.
4161 switch (Method->getRefQualifier()) {
4162 case RQ_None:
4163 // Do nothing; we don't care about lvalueness or rvalueness.
4164 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004165
Douglas Gregor02824322011-01-26 19:30:28 +00004166 case RQ_LValue:
4167 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4168 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004169 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004170 ImplicitParamType);
4171 return ICS;
4172 }
4173 break;
4174
4175 case RQ_RValue:
4176 if (!FromClassification.isRValue()) {
4177 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004178 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004179 ImplicitParamType);
4180 return ICS;
4181 }
4182 break;
4183 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004184
Douglas Gregor436424c2008-11-18 23:14:02 +00004185 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004186 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004187 ICS.Standard.setAsIdentityConversion();
4188 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004189 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004190 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004191 ICS.Standard.ReferenceBinding = true;
4192 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004193 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004194 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004195 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4196 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4197 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004198 return ICS;
4199}
4200
4201/// PerformObjectArgumentInitialization - Perform initialization of
4202/// the implicit object parameter for the given Method with the given
4203/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004204ExprResult
4205Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004206 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004207 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004208 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004209 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004210 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004211 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004212
Douglas Gregor02824322011-01-26 19:30:28 +00004213 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004214 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004215 FromRecordType = PT->getPointeeType();
4216 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004217 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004218 } else {
4219 FromRecordType = From->getType();
4220 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004221 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004222 }
4223
John McCall6e9f8f62009-12-03 04:06:58 +00004224 // Note that we always use the true parent context when performing
4225 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004226 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004227 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4228 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004229 if (ICS.isBad()) {
4230 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4231 Qualifiers FromQs = FromRecordType.getQualifiers();
4232 Qualifiers ToQs = DestType.getQualifiers();
4233 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4234 if (CVR) {
4235 Diag(From->getSourceRange().getBegin(),
4236 diag::err_member_function_call_bad_cvr)
4237 << Method->getDeclName() << FromRecordType << (CVR - 1)
4238 << From->getSourceRange();
4239 Diag(Method->getLocation(), diag::note_previous_decl)
4240 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004241 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004242 }
4243 }
4244
Douglas Gregor436424c2008-11-18 23:14:02 +00004245 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004246 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004247 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004248 }
Mike Stump11289f42009-09-09 15:08:12 +00004249
John Wiegley01296292011-04-08 18:41:53 +00004250 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4251 ExprResult FromRes =
4252 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4253 if (FromRes.isInvalid())
4254 return ExprError();
4255 From = FromRes.take();
4256 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004257
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004258 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004259 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004260 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004261 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004262}
4263
Douglas Gregor5fb53972009-01-14 15:45:31 +00004264/// TryContextuallyConvertToBool - Attempt to contextually convert the
4265/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004266static ImplicitConversionSequence
4267TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004268 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004269 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004270 // FIXME: Are these flags correct?
4271 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004272 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004273 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004274 /*CStyle=*/false,
4275 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004276}
4277
4278/// PerformContextuallyConvertToBool - Perform a contextual conversion
4279/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004280ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004281 if (checkPlaceholderForOverload(*this, From))
4282 return ExprError();
4283
John McCall5c32be02010-08-24 20:38:10 +00004284 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004285 if (!ICS.isBad())
4286 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004287
Fariborz Jahanian76197412009-11-18 18:26:29 +00004288 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00004289 return Diag(From->getSourceRange().getBegin(),
4290 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004291 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004292 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004293}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004294
John McCallfec112d2011-09-09 06:11:02 +00004295/// dropPointerConversions - If the given standard conversion sequence
4296/// involves any pointer conversions, remove them. This may change
4297/// the result type of the conversion sequence.
4298static void dropPointerConversion(StandardConversionSequence &SCS) {
4299 if (SCS.Second == ICK_Pointer_Conversion) {
4300 SCS.Second = ICK_Identity;
4301 SCS.Third = ICK_Identity;
4302 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4303 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004304}
John McCall5c32be02010-08-24 20:38:10 +00004305
John McCallfec112d2011-09-09 06:11:02 +00004306/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4307/// convert the expression From to an Objective-C pointer type.
4308static ImplicitConversionSequence
4309TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4310 // Do an implicit conversion to 'id'.
4311 QualType Ty = S.Context.getObjCIdType();
4312 ImplicitConversionSequence ICS
4313 = TryImplicitConversion(S, From, Ty,
4314 // FIXME: Are these flags correct?
4315 /*SuppressUserConversions=*/false,
4316 /*AllowExplicit=*/true,
4317 /*InOverloadResolution=*/false,
4318 /*CStyle=*/false,
4319 /*AllowObjCWritebackConversion=*/false);
4320
4321 // Strip off any final conversions to 'id'.
4322 switch (ICS.getKind()) {
4323 case ImplicitConversionSequence::BadConversion:
4324 case ImplicitConversionSequence::AmbiguousConversion:
4325 case ImplicitConversionSequence::EllipsisConversion:
4326 break;
4327
4328 case ImplicitConversionSequence::UserDefinedConversion:
4329 dropPointerConversion(ICS.UserDefined.After);
4330 break;
4331
4332 case ImplicitConversionSequence::StandardConversion:
4333 dropPointerConversion(ICS.Standard);
4334 break;
4335 }
4336
4337 return ICS;
4338}
4339
4340/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4341/// conversion of the expression From to an Objective-C pointer type.
4342ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004343 if (checkPlaceholderForOverload(*this, From))
4344 return ExprError();
4345
John McCall8b07ec22010-05-15 11:32:37 +00004346 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004347 ImplicitConversionSequence ICS =
4348 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004349 if (!ICS.isBad())
4350 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004351 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004352}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004353
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004354/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004355/// enumeration type.
4356///
4357/// This routine will attempt to convert an expression of class type to an
4358/// integral or enumeration type, if that class type only has a single
4359/// conversion to an integral or enumeration type.
4360///
Douglas Gregor4799d032010-06-30 00:20:43 +00004361/// \param Loc The source location of the construct that requires the
4362/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004363///
Douglas Gregor4799d032010-06-30 00:20:43 +00004364/// \param FromE The expression we're converting from.
4365///
4366/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4367/// have integral or enumeration type.
4368///
4369/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4370/// incomplete class type.
4371///
4372/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4373/// explicit conversion function (because no implicit conversion functions
4374/// were available). This is a recovery mode.
4375///
4376/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4377/// showing which conversion was picked.
4378///
4379/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4380/// conversion function that could convert to integral or enumeration type.
4381///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004382/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004383/// usable conversion function.
4384///
4385/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4386/// function, which may be an extension in this case.
4387///
4388/// \returns The expression, converted to an integral or enumeration type if
4389/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004390ExprResult
John McCallb268a282010-08-23 23:25:46 +00004391Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004392 const PartialDiagnostic &NotIntDiag,
4393 const PartialDiagnostic &IncompleteDiag,
4394 const PartialDiagnostic &ExplicitConvDiag,
4395 const PartialDiagnostic &ExplicitConvNote,
4396 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004397 const PartialDiagnostic &AmbigNote,
4398 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004399 // We can't perform any more checking for type-dependent expressions.
4400 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004401 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004402
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004403 // If the expression already has integral or enumeration type, we're golden.
4404 QualType T = From->getType();
4405 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00004406 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004407
4408 // FIXME: Check for missing '()' if T is a function type?
4409
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004410 // 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 +00004411 // expression of integral or enumeration type.
4412 const RecordType *RecordTy = T->getAs<RecordType>();
4413 if (!RecordTy || !getLangOptions().CPlusPlus) {
4414 Diag(Loc, NotIntDiag)
4415 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004416 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004417 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004418
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004419 // We must have a complete class type.
4420 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004421 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004422
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004423 // Look for a conversion to an integral or enumeration type.
4424 UnresolvedSet<4> ViableConversions;
4425 UnresolvedSet<4> ExplicitConversions;
4426 const UnresolvedSetImpl *Conversions
4427 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004428
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004429 bool HadMultipleCandidates = (Conversions->size() > 1);
4430
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004431 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004432 E = Conversions->end();
4433 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004434 ++I) {
4435 if (CXXConversionDecl *Conversion
4436 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4437 if (Conversion->getConversionType().getNonReferenceType()
4438 ->isIntegralOrEnumerationType()) {
4439 if (Conversion->isExplicit())
4440 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4441 else
4442 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4443 }
4444 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004445
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004446 switch (ViableConversions.size()) {
4447 case 0:
4448 if (ExplicitConversions.size() == 1) {
4449 DeclAccessPair Found = ExplicitConversions[0];
4450 CXXConversionDecl *Conversion
4451 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004452
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004453 // The user probably meant to invoke the given explicit
4454 // conversion; use it.
4455 QualType ConvTy
4456 = Conversion->getConversionType().getNonReferenceType();
4457 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00004458 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004459
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004460 Diag(Loc, ExplicitConvDiag)
4461 << T << ConvTy
4462 << FixItHint::CreateInsertion(From->getLocStart(),
4463 "static_cast<" + TypeStr + ">(")
4464 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4465 ")");
4466 Diag(Conversion->getLocation(), ExplicitConvNote)
4467 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004468
4469 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004470 // explicit conversion function.
4471 if (isSFINAEContext())
4472 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004473
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004474 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004475 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4476 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004477 if (Result.isInvalid())
4478 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004479 // Record usage of conversion in an implicit cast.
4480 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4481 CK_UserDefinedConversion,
4482 Result.get(), 0,
4483 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004484 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004485
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004486 // We'll complain below about a non-integral condition type.
4487 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004488
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004489 case 1: {
4490 // Apply this conversion.
4491 DeclAccessPair Found = ViableConversions[0];
4492 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004493
Douglas Gregor4799d032010-06-30 00:20:43 +00004494 CXXConversionDecl *Conversion
4495 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4496 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004497 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004498 if (ConvDiag.getDiagID()) {
4499 if (isSFINAEContext())
4500 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004501
Douglas Gregor4799d032010-06-30 00:20:43 +00004502 Diag(Loc, ConvDiag)
4503 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4504 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004505
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004506 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4507 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004508 if (Result.isInvalid())
4509 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004510 // Record usage of conversion in an implicit cast.
4511 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4512 CK_UserDefinedConversion,
4513 Result.get(), 0,
4514 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004515 break;
4516 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004517
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004518 default:
4519 Diag(Loc, AmbigDiag)
4520 << T << From->getSourceRange();
4521 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4522 CXXConversionDecl *Conv
4523 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4524 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4525 Diag(Conv->getLocation(), AmbigNote)
4526 << ConvTy->isEnumeralType() << ConvTy;
4527 }
John McCallb268a282010-08-23 23:25:46 +00004528 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004529 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004530
Douglas Gregor5823da32010-06-29 23:25:20 +00004531 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004532 Diag(Loc, NotIntDiag)
4533 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004534
John McCallb268a282010-08-23 23:25:46 +00004535 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004536}
4537
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004538/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004539/// candidate functions, using the given function call arguments. If
4540/// @p SuppressUserConversions, then don't allow user-defined
4541/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004542///
4543/// \para PartialOverloading true if we are performing "partial" overloading
4544/// based on an incomplete set of function arguments. This feature is used by
4545/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004546void
4547Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004548 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004549 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004550 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004551 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004552 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004553 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004554 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004555 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004556 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004557 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004558
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004559 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004560 if (!isa<CXXConstructorDecl>(Method)) {
4561 // If we get here, it's because we're calling a member function
4562 // that is named without a member access expression (e.g.,
4563 // "this->f") that was either written explicitly or created
4564 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004565 // function, e.g., X::f(). We use an empty type for the implied
4566 // object argument (C++ [over.call.func]p3), and the acting context
4567 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004568 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004569 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004570 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004571 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004572 return;
4573 }
4574 // We treat a constructor like a non-member function, since its object
4575 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004576 }
4577
Douglas Gregorff7028a2009-11-13 23:59:09 +00004578 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004579 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004580
Douglas Gregor27381f32009-11-23 12:27:39 +00004581 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004582 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004583
Douglas Gregorffe14e32009-11-14 01:20:54 +00004584 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4585 // C++ [class.copy]p3:
4586 // A member function template is never instantiated to perform the copy
4587 // of a class object to an object of its class type.
4588 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004589 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004590 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004591 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4592 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004593 return;
4594 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004595
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004596 // Add this candidate
4597 CandidateSet.push_back(OverloadCandidate());
4598 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004599 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004600 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004601 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004602 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004603 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004604 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004605
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004606 unsigned NumArgsInProto = Proto->getNumArgs();
4607
4608 // (C++ 13.3.2p2): A candidate function having fewer than m
4609 // parameters is viable only if it has an ellipsis in its parameter
4610 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004611 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004612 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004613 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004614 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004615 return;
4616 }
4617
4618 // (C++ 13.3.2p2): A candidate function having more than m parameters
4619 // is viable only if the (m+1)st parameter has a default argument
4620 // (8.3.6). For the purposes of overload resolution, the
4621 // parameter list is truncated on the right, so that there are
4622 // exactly m parameters.
4623 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004624 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004625 // Not enough arguments.
4626 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004627 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004628 return;
4629 }
4630
Peter Collingbourne7277fe82011-10-02 23:49:40 +00004631 // (CUDA B.1): Check for invalid calls between targets.
4632 if (getLangOptions().CUDA)
4633 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4634 if (CheckCUDATarget(Caller, Function)) {
4635 Candidate.Viable = false;
4636 Candidate.FailureKind = ovl_fail_bad_target;
4637 return;
4638 }
4639
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004640 // Determine the implicit conversion sequences for each of the
4641 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004642 Candidate.Conversions.resize(NumArgs);
4643 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4644 if (ArgIdx < NumArgsInProto) {
4645 // (C++ 13.3.2p3): for F to be a viable function, there shall
4646 // exist for each argument an implicit conversion sequence
4647 // (13.3.3.1) that converts that argument to the corresponding
4648 // parameter of F.
4649 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004650 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004651 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004652 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004653 /*InOverloadResolution=*/true,
4654 /*AllowObjCWritebackConversion=*/
4655 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004656 if (Candidate.Conversions[ArgIdx].isBad()) {
4657 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004658 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004659 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004660 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004661 } else {
4662 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4663 // argument for which there is no corresponding parameter is
4664 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004665 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004666 }
4667 }
4668}
4669
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004670/// \brief Add all of the function declarations in the given function set to
4671/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004672void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004673 Expr **Args, unsigned NumArgs,
4674 OverloadCandidateSet& CandidateSet,
4675 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004676 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004677 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4678 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004679 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004680 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004681 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004682 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004683 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004684 CandidateSet, SuppressUserConversions);
4685 else
John McCalla0296f72010-03-19 07:35:19 +00004686 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004687 SuppressUserConversions);
4688 } else {
John McCalla0296f72010-03-19 07:35:19 +00004689 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004690 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4691 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004692 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004693 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004694 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004695 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004696 Args[0]->Classify(Context),
4697 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004698 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004699 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004700 else
John McCalla0296f72010-03-19 07:35:19 +00004701 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004702 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004703 Args, NumArgs, CandidateSet,
4704 SuppressUserConversions);
4705 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004706 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004707}
4708
John McCallf0f1cf02009-11-17 07:50:12 +00004709/// AddMethodCandidate - Adds a named decl (which is some kind of
4710/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004711void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004712 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004713 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004714 Expr **Args, unsigned NumArgs,
4715 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004716 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004717 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004718 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004719
4720 if (isa<UsingShadowDecl>(Decl))
4721 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004722
John McCallf0f1cf02009-11-17 07:50:12 +00004723 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4724 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4725 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004726 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4727 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004728 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004729 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004730 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004731 } else {
John McCalla0296f72010-03-19 07:35:19 +00004732 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004733 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004734 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004735 }
4736}
4737
Douglas Gregor436424c2008-11-18 23:14:02 +00004738/// AddMethodCandidate - Adds the given C++ member function to the set
4739/// of candidate functions, using the given function call arguments
4740/// and the object argument (@c Object). For example, in a call
4741/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4742/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4743/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004744/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004745void
John McCalla0296f72010-03-19 07:35:19 +00004746Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004747 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004748 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004749 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004750 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004751 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004752 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004753 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004754 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004755 assert(!isa<CXXConstructorDecl>(Method) &&
4756 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004757
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004758 if (!CandidateSet.isNewCandidate(Method))
4759 return;
4760
Douglas Gregor27381f32009-11-23 12:27:39 +00004761 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004762 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004763
Douglas Gregor436424c2008-11-18 23:14:02 +00004764 // Add this candidate
4765 CandidateSet.push_back(OverloadCandidate());
4766 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004767 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004768 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004769 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004770 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004771 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004772
4773 unsigned NumArgsInProto = Proto->getNumArgs();
4774
4775 // (C++ 13.3.2p2): A candidate function having fewer than m
4776 // parameters is viable only if it has an ellipsis in its parameter
4777 // list (8.3.5).
4778 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4779 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004780 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004781 return;
4782 }
4783
4784 // (C++ 13.3.2p2): A candidate function having more than m parameters
4785 // is viable only if the (m+1)st parameter has a default argument
4786 // (8.3.6). For the purposes of overload resolution, the
4787 // parameter list is truncated on the right, so that there are
4788 // exactly m parameters.
4789 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4790 if (NumArgs < MinRequiredArgs) {
4791 // Not enough arguments.
4792 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004793 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004794 return;
4795 }
4796
4797 Candidate.Viable = true;
4798 Candidate.Conversions.resize(NumArgs + 1);
4799
John McCall6e9f8f62009-12-03 04:06:58 +00004800 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004801 // The implicit object argument is ignored.
4802 Candidate.IgnoreObjectArgument = true;
4803 else {
4804 // Determine the implicit conversion sequence for the object
4805 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004806 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004807 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4808 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004809 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004810 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004811 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004812 return;
4813 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004814 }
4815
4816 // Determine the implicit conversion sequences for each of the
4817 // arguments.
4818 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4819 if (ArgIdx < NumArgsInProto) {
4820 // (C++ 13.3.2p3): for F to be a viable function, there shall
4821 // exist for each argument an implicit conversion sequence
4822 // (13.3.3.1) that converts that argument to the corresponding
4823 // parameter of F.
4824 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004825 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004826 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004827 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004828 /*InOverloadResolution=*/true,
4829 /*AllowObjCWritebackConversion=*/
4830 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004831 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004832 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004833 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004834 break;
4835 }
4836 } else {
4837 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4838 // argument for which there is no corresponding parameter is
4839 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004840 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004841 }
4842 }
4843}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004844
Douglas Gregor97628d62009-08-21 00:16:32 +00004845/// \brief Add a C++ member function template as a candidate to the candidate
4846/// set, using template argument deduction to produce an appropriate member
4847/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004848void
Douglas Gregor97628d62009-08-21 00:16:32 +00004849Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004850 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004851 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004852 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004853 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004854 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004855 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004856 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004857 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004858 if (!CandidateSet.isNewCandidate(MethodTmpl))
4859 return;
4860
Douglas Gregor97628d62009-08-21 00:16:32 +00004861 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004862 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004863 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004864 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004865 // candidate functions in the usual way.113) A given name can refer to one
4866 // or more function templates and also to a set of overloaded non-template
4867 // functions. In such a case, the candidate functions generated from each
4868 // function template are combined with the set of non-template candidate
4869 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004870 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004871 FunctionDecl *Specialization = 0;
4872 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004873 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004874 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004875 CandidateSet.push_back(OverloadCandidate());
4876 OverloadCandidate &Candidate = CandidateSet.back();
4877 Candidate.FoundDecl = FoundDecl;
4878 Candidate.Function = MethodTmpl->getTemplatedDecl();
4879 Candidate.Viable = false;
4880 Candidate.FailureKind = ovl_fail_bad_deduction;
4881 Candidate.IsSurrogate = false;
4882 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004883 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004884 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004885 Info);
4886 return;
4887 }
Mike Stump11289f42009-09-09 15:08:12 +00004888
Douglas Gregor97628d62009-08-21 00:16:32 +00004889 // Add the function template specialization produced by template argument
4890 // deduction as a candidate.
4891 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004892 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004893 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004894 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004895 ActingContext, ObjectType, ObjectClassification,
4896 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004897}
4898
Douglas Gregor05155d82009-08-21 23:19:43 +00004899/// \brief Add a C++ function template specialization as a candidate
4900/// in the candidate set, using template argument deduction to produce
4901/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004902void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004903Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004904 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004905 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004906 Expr **Args, unsigned NumArgs,
4907 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004908 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004909 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4910 return;
4911
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004912 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004913 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004914 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004915 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004916 // candidate functions in the usual way.113) A given name can refer to one
4917 // or more function templates and also to a set of overloaded non-template
4918 // functions. In such a case, the candidate functions generated from each
4919 // function template are combined with the set of non-template candidate
4920 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004921 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004922 FunctionDecl *Specialization = 0;
4923 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004924 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004925 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004926 CandidateSet.push_back(OverloadCandidate());
4927 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004928 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004929 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4930 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004931 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004932 Candidate.IsSurrogate = false;
4933 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004934 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004935 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004936 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004937 return;
4938 }
Mike Stump11289f42009-09-09 15:08:12 +00004939
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004940 // Add the function template specialization produced by template argument
4941 // deduction as a candidate.
4942 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004943 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004944 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004945}
Mike Stump11289f42009-09-09 15:08:12 +00004946
Douglas Gregora1f013e2008-11-07 22:36:19 +00004947/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004948/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004949/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004950/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004951/// (which may or may not be the same type as the type that the
4952/// conversion function produces).
4953void
4954Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004955 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004956 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004957 Expr *From, QualType ToType,
4958 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004959 assert(!Conversion->getDescribedFunctionTemplate() &&
4960 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004961 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004962 if (!CandidateSet.isNewCandidate(Conversion))
4963 return;
4964
Douglas Gregor27381f32009-11-23 12:27:39 +00004965 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004966 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004967
Douglas Gregora1f013e2008-11-07 22:36:19 +00004968 // Add this candidate
4969 CandidateSet.push_back(OverloadCandidate());
4970 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004971 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004972 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004973 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004974 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004975 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004976 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004977 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004978 Candidate.Viable = true;
4979 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004980 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004981
Douglas Gregor6affc782010-08-19 15:37:02 +00004982 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004983 // For conversion functions, the function is considered to be a member of
4984 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004985 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004986 //
4987 // Determine the implicit conversion sequence for the implicit
4988 // object parameter.
4989 QualType ImplicitParamType = From->getType();
4990 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4991 ImplicitParamType = FromPtrType->getPointeeType();
4992 CXXRecordDecl *ConversionContext
4993 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004994
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004995 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004996 = TryObjectArgumentInitialization(*this, From->getType(),
4997 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004998 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004999
John McCall0d1da222010-01-12 00:44:57 +00005000 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005001 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005002 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005003 return;
5004 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00005005
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005006 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005007 // derived to base as such conversions are given Conversion Rank. They only
5008 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5009 QualType FromCanon
5010 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5011 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5012 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5013 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005014 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00005015 return;
5016 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005017
Douglas Gregora1f013e2008-11-07 22:36:19 +00005018 // To determine what the conversion from the result of calling the
5019 // conversion function to the type we're eventually trying to
5020 // convert to (ToType), we need to synthesize a call to the
5021 // conversion function and attempt copy initialization from it. This
5022 // makes sure that we get the right semantics with respect to
5023 // lvalues/rvalues and the type. Fortunately, we can allocate this
5024 // call on the stack and we don't need its arguments to be
5025 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00005026 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00005027 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00005028 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5029 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00005030 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00005031 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00005032
Richard Smith48d24642011-07-13 22:53:21 +00005033 QualType ConversionType = Conversion->getConversionType();
5034 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00005035 Candidate.Viable = false;
5036 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5037 return;
5038 }
5039
Richard Smith48d24642011-07-13 22:53:21 +00005040 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00005041
Mike Stump11289f42009-09-09 15:08:12 +00005042 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00005043 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5044 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00005045 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00005046 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00005047 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00005048 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005049 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005050 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00005051 /*InOverloadResolution=*/false,
5052 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00005053
John McCall0d1da222010-01-12 00:44:57 +00005054 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00005055 case ImplicitConversionSequence::StandardConversion:
5056 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005057
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005058 // C++ [over.ics.user]p3:
5059 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005060 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00005061 // shall have exact match rank.
5062 if (Conversion->getPrimaryTemplate() &&
5063 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5064 Candidate.Viable = false;
5065 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5066 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005067
Douglas Gregorcba72b12011-01-21 05:18:22 +00005068 // C++0x [dcl.init.ref]p5:
5069 // In the second case, if the reference is an rvalue reference and
5070 // the second standard conversion sequence of the user-defined
5071 // conversion sequence includes an lvalue-to-rvalue conversion, the
5072 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005073 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00005074 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5075 Candidate.Viable = false;
5076 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5077 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00005078 break;
5079
5080 case ImplicitConversionSequence::BadConversion:
5081 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00005082 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00005083 break;
5084
5085 default:
David Blaikie83d382b2011-09-23 05:06:16 +00005086 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00005087 "Can only end up with a standard conversion sequence or failure");
5088 }
5089}
5090
Douglas Gregor05155d82009-08-21 23:19:43 +00005091/// \brief Adds a conversion function template specialization
5092/// candidate to the overload set, using template argument deduction
5093/// to deduce the template arguments of the conversion function
5094/// template from the type that we are converting to (C++
5095/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00005096void
Douglas Gregor05155d82009-08-21 23:19:43 +00005097Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00005098 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005099 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00005100 Expr *From, QualType ToType,
5101 OverloadCandidateSet &CandidateSet) {
5102 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5103 "Only conversion function templates permitted here");
5104
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005105 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5106 return;
5107
John McCallbc077cf2010-02-08 23:07:23 +00005108 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00005109 CXXConversionDecl *Specialization = 0;
5110 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00005111 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00005112 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005113 CandidateSet.push_back(OverloadCandidate());
5114 OverloadCandidate &Candidate = CandidateSet.back();
5115 Candidate.FoundDecl = FoundDecl;
5116 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5117 Candidate.Viable = false;
5118 Candidate.FailureKind = ovl_fail_bad_deduction;
5119 Candidate.IsSurrogate = false;
5120 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00005121 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005122 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00005123 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00005124 return;
5125 }
Mike Stump11289f42009-09-09 15:08:12 +00005126
Douglas Gregor05155d82009-08-21 23:19:43 +00005127 // Add the conversion function template specialization produced by
5128 // template argument deduction as a candidate.
5129 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00005130 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00005131 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00005132}
5133
Douglas Gregorab7897a2008-11-19 22:57:39 +00005134/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5135/// converts the given @c Object to a function pointer via the
5136/// conversion function @c Conversion, and then attempts to call it
5137/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5138/// the type of function that we'll eventually be calling.
5139void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00005140 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00005141 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00005142 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00005143 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00005144 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00005145 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00005146 if (!CandidateSet.isNewCandidate(Conversion))
5147 return;
5148
Douglas Gregor27381f32009-11-23 12:27:39 +00005149 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005150 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005151
Douglas Gregorab7897a2008-11-19 22:57:39 +00005152 CandidateSet.push_back(OverloadCandidate());
5153 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00005154 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005155 Candidate.Function = 0;
5156 Candidate.Surrogate = Conversion;
5157 Candidate.Viable = true;
5158 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005159 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005160 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00005161 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005162
5163 // Determine the implicit conversion sequence for the implicit
5164 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00005165 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005166 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005167 Object->Classify(Context),
5168 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005169 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005170 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005171 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005172 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005173 return;
5174 }
5175
5176 // The first conversion is actually a user-defined conversion whose
5177 // first conversion is ObjectInit's standard conversion (which is
5178 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005179 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005180 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005181 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005182 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005183 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005184 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005185 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005186 = Candidate.Conversions[0].UserDefined.Before;
5187 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5188
Mike Stump11289f42009-09-09 15:08:12 +00005189 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005190 unsigned NumArgsInProto = Proto->getNumArgs();
5191
5192 // (C++ 13.3.2p2): A candidate function having fewer than m
5193 // parameters is viable only if it has an ellipsis in its parameter
5194 // list (8.3.5).
5195 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5196 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005197 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005198 return;
5199 }
5200
5201 // Function types don't have any default arguments, so just check if
5202 // we have enough arguments.
5203 if (NumArgs < NumArgsInProto) {
5204 // Not enough arguments.
5205 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005206 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005207 return;
5208 }
5209
5210 // Determine the implicit conversion sequences for each of the
5211 // arguments.
5212 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5213 if (ArgIdx < NumArgsInProto) {
5214 // (C++ 13.3.2p3): for F to be a viable function, there shall
5215 // exist for each argument an implicit conversion sequence
5216 // (13.3.3.1) that converts that argument to the corresponding
5217 // parameter of F.
5218 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005219 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005220 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005221 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005222 /*InOverloadResolution=*/false,
5223 /*AllowObjCWritebackConversion=*/
5224 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005225 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005226 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005227 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005228 break;
5229 }
5230 } else {
5231 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5232 // argument for which there is no corresponding parameter is
5233 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005234 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005235 }
5236 }
5237}
5238
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005239/// \brief Add overload candidates for overloaded operators that are
5240/// member functions.
5241///
5242/// Add the overloaded operator candidates that are member functions
5243/// for the operator Op that was used in an operator expression such
5244/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5245/// CandidateSet will store the added overload candidates. (C++
5246/// [over.match.oper]).
5247void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5248 SourceLocation OpLoc,
5249 Expr **Args, unsigned NumArgs,
5250 OverloadCandidateSet& CandidateSet,
5251 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005252 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5253
5254 // C++ [over.match.oper]p3:
5255 // For a unary operator @ with an operand of a type whose
5256 // cv-unqualified version is T1, and for a binary operator @ with
5257 // a left operand of a type whose cv-unqualified version is T1 and
5258 // a right operand of a type whose cv-unqualified version is T2,
5259 // three sets of candidate functions, designated member
5260 // candidates, non-member candidates and built-in candidates, are
5261 // constructed as follows:
5262 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005263
5264 // -- If T1 is a class type, the set of member candidates is the
5265 // result of the qualified lookup of T1::operator@
5266 // (13.3.1.1.1); otherwise, the set of member candidates is
5267 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005268 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005269 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005270 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005271 return;
Mike Stump11289f42009-09-09 15:08:12 +00005272
John McCall27b18f82009-11-17 02:14:36 +00005273 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5274 LookupQualifiedName(Operators, T1Rec->getDecl());
5275 Operators.suppressDiagnostics();
5276
Mike Stump11289f42009-09-09 15:08:12 +00005277 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005278 OperEnd = Operators.end();
5279 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005280 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005281 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005282 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005283 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005284 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005285 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005286}
5287
Douglas Gregora11693b2008-11-12 17:17:38 +00005288/// AddBuiltinCandidate - Add a candidate for a built-in
5289/// operator. ResultTy and ParamTys are the result and parameter types
5290/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005291/// arguments being passed to the candidate. IsAssignmentOperator
5292/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005293/// operator. NumContextualBoolArguments is the number of arguments
5294/// (at the beginning of the argument list) that will be contextually
5295/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005296void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005297 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005298 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005299 bool IsAssignmentOperator,
5300 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005301 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005302 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005303
Douglas Gregora11693b2008-11-12 17:17:38 +00005304 // Add this candidate
5305 CandidateSet.push_back(OverloadCandidate());
5306 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00005307 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005308 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005309 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005310 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005311 Candidate.BuiltinTypes.ResultTy = ResultTy;
5312 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5313 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5314
5315 // Determine the implicit conversion sequences for each of the
5316 // arguments.
5317 Candidate.Viable = true;
5318 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00005319 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005320 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005321 // C++ [over.match.oper]p4:
5322 // For the built-in assignment operators, conversions of the
5323 // left operand are restricted as follows:
5324 // -- no temporaries are introduced to hold the left operand, and
5325 // -- no user-defined conversions are applied to the left
5326 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005327 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005328 //
5329 // We block these conversions by turning off user-defined
5330 // conversions, since that is the only way that initialization of
5331 // a reference to a non-class type can occur from something that
5332 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005333 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005334 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005335 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005336 Candidate.Conversions[ArgIdx]
5337 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005338 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005339 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005340 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005341 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005342 /*InOverloadResolution=*/false,
5343 /*AllowObjCWritebackConversion=*/
5344 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005345 }
John McCall0d1da222010-01-12 00:44:57 +00005346 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005347 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005348 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005349 break;
5350 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005351 }
5352}
5353
5354/// BuiltinCandidateTypeSet - A set of types that will be used for the
5355/// candidate operator functions for built-in operators (C++
5356/// [over.built]). The types are separated into pointer types and
5357/// enumeration types.
5358class BuiltinCandidateTypeSet {
5359 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005360 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005361
5362 /// PointerTypes - The set of pointer types that will be used in the
5363 /// built-in candidates.
5364 TypeSet PointerTypes;
5365
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005366 /// MemberPointerTypes - The set of member pointer types that will be
5367 /// used in the built-in candidates.
5368 TypeSet MemberPointerTypes;
5369
Douglas Gregora11693b2008-11-12 17:17:38 +00005370 /// EnumerationTypes - The set of enumeration types that will be
5371 /// used in the built-in candidates.
5372 TypeSet EnumerationTypes;
5373
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005374 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005375 /// candidates.
5376 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005377
5378 /// \brief A flag indicating non-record types are viable candidates
5379 bool HasNonRecordTypes;
5380
5381 /// \brief A flag indicating whether either arithmetic or enumeration types
5382 /// were present in the candidate set.
5383 bool HasArithmeticOrEnumeralTypes;
5384
Douglas Gregor80af3132011-05-21 23:15:46 +00005385 /// \brief A flag indicating whether the nullptr type was present in the
5386 /// candidate set.
5387 bool HasNullPtrType;
5388
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005389 /// Sema - The semantic analysis instance where we are building the
5390 /// candidate type set.
5391 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005392
Douglas Gregora11693b2008-11-12 17:17:38 +00005393 /// Context - The AST context in which we will build the type sets.
5394 ASTContext &Context;
5395
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005396 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5397 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005398 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005399
5400public:
5401 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005402 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005403
Mike Stump11289f42009-09-09 15:08:12 +00005404 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005405 : HasNonRecordTypes(false),
5406 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005407 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005408 SemaRef(SemaRef),
5409 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005410
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005411 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005412 SourceLocation Loc,
5413 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005414 bool AllowExplicitConversions,
5415 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005416
5417 /// pointer_begin - First pointer type found;
5418 iterator pointer_begin() { return PointerTypes.begin(); }
5419
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005420 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005421 iterator pointer_end() { return PointerTypes.end(); }
5422
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005423 /// member_pointer_begin - First member pointer type found;
5424 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5425
5426 /// member_pointer_end - Past the last member pointer type found;
5427 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5428
Douglas Gregora11693b2008-11-12 17:17:38 +00005429 /// enumeration_begin - First enumeration type found;
5430 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5431
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005432 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005433 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005434
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005435 iterator vector_begin() { return VectorTypes.begin(); }
5436 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005437
5438 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5439 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005440 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005441};
5442
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005443/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005444/// the set of pointer types along with any more-qualified variants of
5445/// that type. For example, if @p Ty is "int const *", this routine
5446/// will add "int const *", "int const volatile *", "int const
5447/// restrict *", and "int const volatile restrict *" to the set of
5448/// pointer types. Returns true if the add of @p Ty itself succeeded,
5449/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005450///
5451/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005452bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005453BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5454 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00005455
Douglas Gregora11693b2008-11-12 17:17:38 +00005456 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005457 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00005458 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005459
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005460 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00005461 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005462 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005463 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005464 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005465 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005466 buildObjCPtr = true;
5467 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005468 else
David Blaikie83d382b2011-09-23 05:06:16 +00005469 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005470 }
5471 else
5472 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005473
Sebastian Redl4990a632009-11-18 20:39:26 +00005474 // Don't add qualified variants of arrays. For one, they're not allowed
5475 // (the qualifier would sink to the element type), and for another, the
5476 // only overload situation where it matters is subscript or pointer +- int,
5477 // and those shouldn't have qualifier variants anyway.
5478 if (PointeeTy->isArrayType())
5479 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005480 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005481 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005482 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005483 bool hasVolatile = VisibleQuals.hasVolatile();
5484 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005485
John McCall8ccfcb52009-09-24 19:53:00 +00005486 // Iterate through all strict supersets of BaseCVR.
5487 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5488 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005489 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5490 // in the types.
5491 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5492 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005493 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005494 if (!buildObjCPtr)
5495 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5496 else
5497 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005498 }
5499
5500 return true;
5501}
5502
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005503/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5504/// to the set of pointer types along with any more-qualified variants of
5505/// that type. For example, if @p Ty is "int const *", this routine
5506/// will add "int const *", "int const volatile *", "int const
5507/// restrict *", and "int const volatile restrict *" to the set of
5508/// pointer types. Returns true if the add of @p Ty itself succeeded,
5509/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005510///
5511/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005512bool
5513BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5514 QualType Ty) {
5515 // Insert this type.
5516 if (!MemberPointerTypes.insert(Ty))
5517 return false;
5518
John McCall8ccfcb52009-09-24 19:53:00 +00005519 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5520 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005521
John McCall8ccfcb52009-09-24 19:53:00 +00005522 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005523 // Don't add qualified variants of arrays. For one, they're not allowed
5524 // (the qualifier would sink to the element type), and for another, the
5525 // only overload situation where it matters is subscript or pointer +- int,
5526 // and those shouldn't have qualifier variants anyway.
5527 if (PointeeTy->isArrayType())
5528 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005529 const Type *ClassTy = PointerTy->getClass();
5530
5531 // Iterate through all strict supersets of the pointee type's CVR
5532 // qualifiers.
5533 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5534 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5535 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005536
John McCall8ccfcb52009-09-24 19:53:00 +00005537 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005538 MemberPointerTypes.insert(
5539 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005540 }
5541
5542 return true;
5543}
5544
Douglas Gregora11693b2008-11-12 17:17:38 +00005545/// AddTypesConvertedFrom - Add each of the types to which the type @p
5546/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005547/// primarily interested in pointer types and enumeration types. We also
5548/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005549/// AllowUserConversions is true if we should look at the conversion
5550/// functions of a class type, and AllowExplicitConversions if we
5551/// should also include the explicit conversion functions of a class
5552/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005553void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005554BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005555 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005556 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005557 bool AllowExplicitConversions,
5558 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005559 // Only deal with canonical types.
5560 Ty = Context.getCanonicalType(Ty);
5561
5562 // Look through reference types; they aren't part of the type of an
5563 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005564 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005565 Ty = RefTy->getPointeeType();
5566
John McCall33ddac02011-01-19 10:06:00 +00005567 // If we're dealing with an array type, decay to the pointer.
5568 if (Ty->isArrayType())
5569 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5570
5571 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005572 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005573
Chandler Carruth00a38332010-12-13 01:44:01 +00005574 // Flag if we ever add a non-record type.
5575 const RecordType *TyRec = Ty->getAs<RecordType>();
5576 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5577
Chandler Carruth00a38332010-12-13 01:44:01 +00005578 // Flag if we encounter an arithmetic type.
5579 HasArithmeticOrEnumeralTypes =
5580 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5581
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005582 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5583 PointerTypes.insert(Ty);
5584 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005585 // Insert our type, and its more-qualified variants, into the set
5586 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005587 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005588 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005589 } else if (Ty->isMemberPointerType()) {
5590 // Member pointers are far easier, since the pointee can't be converted.
5591 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5592 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005593 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005594 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005595 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005596 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005597 // We treat vector types as arithmetic types in many contexts as an
5598 // extension.
5599 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005600 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005601 } else if (Ty->isNullPtrType()) {
5602 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005603 } else if (AllowUserConversions && TyRec) {
5604 // No conversion functions in incomplete types.
5605 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5606 return;
Mike Stump11289f42009-09-09 15:08:12 +00005607
Chandler Carruth00a38332010-12-13 01:44:01 +00005608 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5609 const UnresolvedSetImpl *Conversions
5610 = ClassDecl->getVisibleConversionFunctions();
5611 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5612 E = Conversions->end(); I != E; ++I) {
5613 NamedDecl *D = I.getDecl();
5614 if (isa<UsingShadowDecl>(D))
5615 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005616
Chandler Carruth00a38332010-12-13 01:44:01 +00005617 // Skip conversion function templates; they don't tell us anything
5618 // about which builtin types we can convert to.
5619 if (isa<FunctionTemplateDecl>(D))
5620 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005621
Chandler Carruth00a38332010-12-13 01:44:01 +00005622 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5623 if (AllowExplicitConversions || !Conv->isExplicit()) {
5624 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5625 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005626 }
5627 }
5628 }
5629}
5630
Douglas Gregor84605ae2009-08-24 13:43:27 +00005631/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5632/// the volatile- and non-volatile-qualified assignment operators for the
5633/// given type to the candidate set.
5634static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5635 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005636 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005637 unsigned NumArgs,
5638 OverloadCandidateSet &CandidateSet) {
5639 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005640
Douglas Gregor84605ae2009-08-24 13:43:27 +00005641 // T& operator=(T&, T)
5642 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5643 ParamTypes[1] = T;
5644 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5645 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005646
Douglas Gregor84605ae2009-08-24 13:43:27 +00005647 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5648 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005649 ParamTypes[0]
5650 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005651 ParamTypes[1] = T;
5652 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005653 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005654 }
5655}
Mike Stump11289f42009-09-09 15:08:12 +00005656
Sebastian Redl1054fae2009-10-25 17:03:50 +00005657/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5658/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005659static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5660 Qualifiers VRQuals;
5661 const RecordType *TyRec;
5662 if (const MemberPointerType *RHSMPType =
5663 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005664 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005665 else
5666 TyRec = ArgExpr->getType()->getAs<RecordType>();
5667 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005668 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005669 VRQuals.addVolatile();
5670 VRQuals.addRestrict();
5671 return VRQuals;
5672 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005673
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005674 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005675 if (!ClassDecl->hasDefinition())
5676 return VRQuals;
5677
John McCallad371252010-01-20 00:46:10 +00005678 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005679 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005680
John McCallad371252010-01-20 00:46:10 +00005681 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005682 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005683 NamedDecl *D = I.getDecl();
5684 if (isa<UsingShadowDecl>(D))
5685 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5686 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005687 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5688 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5689 CanTy = ResTypeRef->getPointeeType();
5690 // Need to go down the pointer/mempointer chain and add qualifiers
5691 // as see them.
5692 bool done = false;
5693 while (!done) {
5694 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5695 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005696 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005697 CanTy->getAs<MemberPointerType>())
5698 CanTy = ResTypeMPtr->getPointeeType();
5699 else
5700 done = true;
5701 if (CanTy.isVolatileQualified())
5702 VRQuals.addVolatile();
5703 if (CanTy.isRestrictQualified())
5704 VRQuals.addRestrict();
5705 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5706 return VRQuals;
5707 }
5708 }
5709 }
5710 return VRQuals;
5711}
John McCall52872982010-11-13 05:51:15 +00005712
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005713namespace {
John McCall52872982010-11-13 05:51:15 +00005714
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005715/// \brief Helper class to manage the addition of builtin operator overload
5716/// candidates. It provides shared state and utility methods used throughout
5717/// the process, as well as a helper method to add each group of builtin
5718/// operator overloads from the standard to a candidate set.
5719class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005720 // Common instance state available to all overload candidate addition methods.
5721 Sema &S;
5722 Expr **Args;
5723 unsigned NumArgs;
5724 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005725 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005726 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005727 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005728
Chandler Carruthc6586e52010-12-12 10:35:00 +00005729 // Define some constants used to index and iterate over the arithemetic types
5730 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005731 // The "promoted arithmetic types" are the arithmetic
5732 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005733 static const unsigned FirstIntegralType = 3;
5734 static const unsigned LastIntegralType = 18;
5735 static const unsigned FirstPromotedIntegralType = 3,
5736 LastPromotedIntegralType = 9;
5737 static const unsigned FirstPromotedArithmeticType = 0,
5738 LastPromotedArithmeticType = 9;
5739 static const unsigned NumArithmeticTypes = 18;
5740
Chandler Carruthc6586e52010-12-12 10:35:00 +00005741 /// \brief Get the canonical type for a given arithmetic type index.
5742 CanQualType getArithmeticType(unsigned index) {
5743 assert(index < NumArithmeticTypes);
5744 static CanQualType ASTContext::* const
5745 ArithmeticTypes[NumArithmeticTypes] = {
5746 // Start of promoted types.
5747 &ASTContext::FloatTy,
5748 &ASTContext::DoubleTy,
5749 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005750
Chandler Carruthc6586e52010-12-12 10:35:00 +00005751 // Start of integral types.
5752 &ASTContext::IntTy,
5753 &ASTContext::LongTy,
5754 &ASTContext::LongLongTy,
5755 &ASTContext::UnsignedIntTy,
5756 &ASTContext::UnsignedLongTy,
5757 &ASTContext::UnsignedLongLongTy,
5758 // End of promoted types.
5759
5760 &ASTContext::BoolTy,
5761 &ASTContext::CharTy,
5762 &ASTContext::WCharTy,
5763 &ASTContext::Char16Ty,
5764 &ASTContext::Char32Ty,
5765 &ASTContext::SignedCharTy,
5766 &ASTContext::ShortTy,
5767 &ASTContext::UnsignedCharTy,
5768 &ASTContext::UnsignedShortTy,
5769 // End of integral types.
5770 // FIXME: What about complex?
5771 };
5772 return S.Context.*ArithmeticTypes[index];
5773 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005774
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005775 /// \brief Gets the canonical type resulting from the usual arithemetic
5776 /// converions for the given arithmetic types.
5777 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5778 // Accelerator table for performing the usual arithmetic conversions.
5779 // The rules are basically:
5780 // - if either is floating-point, use the wider floating-point
5781 // - if same signedness, use the higher rank
5782 // - if same size, use unsigned of the higher rank
5783 // - use the larger type
5784 // These rules, together with the axiom that higher ranks are
5785 // never smaller, are sufficient to precompute all of these results
5786 // *except* when dealing with signed types of higher rank.
5787 // (we could precompute SLL x UI for all known platforms, but it's
5788 // better not to make any assumptions).
5789 enum PromotedType {
5790 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5791 };
5792 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5793 [LastPromotedArithmeticType] = {
5794 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5795 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5796 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5797 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5798 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5799 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5800 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5801 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5802 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5803 };
5804
5805 assert(L < LastPromotedArithmeticType);
5806 assert(R < LastPromotedArithmeticType);
5807 int Idx = ConversionsTable[L][R];
5808
5809 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005810 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005811
5812 // Slow path: we need to compare widths.
5813 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005814 CanQualType LT = getArithmeticType(L),
5815 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005816 unsigned LW = S.Context.getIntWidth(LT),
5817 RW = S.Context.getIntWidth(RT);
5818
5819 // If they're different widths, use the signed type.
5820 if (LW > RW) return LT;
5821 else if (LW < RW) return RT;
5822
5823 // Otherwise, use the unsigned type of the signed type's rank.
5824 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5825 assert(L == SLL || R == SLL);
5826 return S.Context.UnsignedLongLongTy;
5827 }
5828
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005829 /// \brief Helper method to factor out the common pattern of adding overloads
5830 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005831 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5832 bool HasVolatile) {
5833 QualType ParamTypes[2] = {
5834 S.Context.getLValueReferenceType(CandidateTy),
5835 S.Context.IntTy
5836 };
5837
5838 // Non-volatile version.
5839 if (NumArgs == 1)
5840 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5841 else
5842 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5843
5844 // Use a heuristic to reduce number of builtin candidates in the set:
5845 // add volatile version only if there are conversions to a volatile type.
5846 if (HasVolatile) {
5847 ParamTypes[0] =
5848 S.Context.getLValueReferenceType(
5849 S.Context.getVolatileType(CandidateTy));
5850 if (NumArgs == 1)
5851 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5852 else
5853 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5854 }
5855 }
5856
5857public:
5858 BuiltinOperatorOverloadBuilder(
5859 Sema &S, Expr **Args, unsigned NumArgs,
5860 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005861 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005862 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005863 OverloadCandidateSet &CandidateSet)
5864 : S(S), Args(Args), NumArgs(NumArgs),
5865 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005866 HasArithmeticOrEnumeralCandidateType(
5867 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005868 CandidateTypes(CandidateTypes),
5869 CandidateSet(CandidateSet) {
5870 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005871 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005872 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005873 assert(getArithmeticType(LastPromotedIntegralType - 1)
5874 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005875 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005876 assert(getArithmeticType(FirstPromotedArithmeticType)
5877 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005878 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005879 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5880 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005881 "Invalid last promoted arithmetic type");
5882 }
5883
5884 // C++ [over.built]p3:
5885 //
5886 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5887 // is either volatile or empty, there exist candidate operator
5888 // functions of the form
5889 //
5890 // VQ T& operator++(VQ T&);
5891 // T operator++(VQ T&, int);
5892 //
5893 // C++ [over.built]p4:
5894 //
5895 // For every pair (T, VQ), where T is an arithmetic type other
5896 // than bool, and VQ is either volatile or empty, there exist
5897 // candidate operator functions of the form
5898 //
5899 // VQ T& operator--(VQ T&);
5900 // T operator--(VQ T&, int);
5901 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005902 if (!HasArithmeticOrEnumeralCandidateType)
5903 return;
5904
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005905 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5906 Arith < NumArithmeticTypes; ++Arith) {
5907 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005908 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005909 VisibleTypeConversionsQuals.hasVolatile());
5910 }
5911 }
5912
5913 // C++ [over.built]p5:
5914 //
5915 // For every pair (T, VQ), where T is a cv-qualified or
5916 // cv-unqualified object type, and VQ is either volatile or
5917 // empty, there exist candidate operator functions of the form
5918 //
5919 // T*VQ& operator++(T*VQ&);
5920 // T*VQ& operator--(T*VQ&);
5921 // T* operator++(T*VQ&, int);
5922 // T* operator--(T*VQ&, int);
5923 void addPlusPlusMinusMinusPointerOverloads() {
5924 for (BuiltinCandidateTypeSet::iterator
5925 Ptr = CandidateTypes[0].pointer_begin(),
5926 PtrEnd = CandidateTypes[0].pointer_end();
5927 Ptr != PtrEnd; ++Ptr) {
5928 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005929 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005930 continue;
5931
5932 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5933 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5934 VisibleTypeConversionsQuals.hasVolatile()));
5935 }
5936 }
5937
5938 // C++ [over.built]p6:
5939 // For every cv-qualified or cv-unqualified object type T, there
5940 // exist candidate operator functions of the form
5941 //
5942 // T& operator*(T*);
5943 //
5944 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005945 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005946 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005947 // T& operator*(T*);
5948 void addUnaryStarPointerOverloads() {
5949 for (BuiltinCandidateTypeSet::iterator
5950 Ptr = CandidateTypes[0].pointer_begin(),
5951 PtrEnd = CandidateTypes[0].pointer_end();
5952 Ptr != PtrEnd; ++Ptr) {
5953 QualType ParamTy = *Ptr;
5954 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005955 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5956 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005957
Douglas Gregor02824322011-01-26 19:30:28 +00005958 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5959 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5960 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005961
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005962 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5963 &ParamTy, Args, 1, CandidateSet);
5964 }
5965 }
5966
5967 // C++ [over.built]p9:
5968 // For every promoted arithmetic type T, there exist candidate
5969 // operator functions of the form
5970 //
5971 // T operator+(T);
5972 // T operator-(T);
5973 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005974 if (!HasArithmeticOrEnumeralCandidateType)
5975 return;
5976
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005977 for (unsigned Arith = FirstPromotedArithmeticType;
5978 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005979 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005980 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5981 }
5982
5983 // Extension: We also add these operators for vector types.
5984 for (BuiltinCandidateTypeSet::iterator
5985 Vec = CandidateTypes[0].vector_begin(),
5986 VecEnd = CandidateTypes[0].vector_end();
5987 Vec != VecEnd; ++Vec) {
5988 QualType VecTy = *Vec;
5989 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5990 }
5991 }
5992
5993 // C++ [over.built]p8:
5994 // For every type T, there exist candidate operator functions of
5995 // the form
5996 //
5997 // T* operator+(T*);
5998 void addUnaryPlusPointerOverloads() {
5999 for (BuiltinCandidateTypeSet::iterator
6000 Ptr = CandidateTypes[0].pointer_begin(),
6001 PtrEnd = CandidateTypes[0].pointer_end();
6002 Ptr != PtrEnd; ++Ptr) {
6003 QualType ParamTy = *Ptr;
6004 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6005 }
6006 }
6007
6008 // C++ [over.built]p10:
6009 // For every promoted integral type T, there exist candidate
6010 // operator functions of the form
6011 //
6012 // T operator~(T);
6013 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006014 if (!HasArithmeticOrEnumeralCandidateType)
6015 return;
6016
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006017 for (unsigned Int = FirstPromotedIntegralType;
6018 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006019 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006020 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6021 }
6022
6023 // Extension: We also add this operator for vector types.
6024 for (BuiltinCandidateTypeSet::iterator
6025 Vec = CandidateTypes[0].vector_begin(),
6026 VecEnd = CandidateTypes[0].vector_end();
6027 Vec != VecEnd; ++Vec) {
6028 QualType VecTy = *Vec;
6029 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6030 }
6031 }
6032
6033 // C++ [over.match.oper]p16:
6034 // For every pointer to member type T, there exist candidate operator
6035 // functions of the form
6036 //
6037 // bool operator==(T,T);
6038 // bool operator!=(T,T);
6039 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6040 /// Set of (canonical) types that we've already handled.
6041 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6042
6043 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6044 for (BuiltinCandidateTypeSet::iterator
6045 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6046 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6047 MemPtr != MemPtrEnd;
6048 ++MemPtr) {
6049 // Don't add the same builtin candidate twice.
6050 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6051 continue;
6052
6053 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6054 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6055 CandidateSet);
6056 }
6057 }
6058 }
6059
6060 // C++ [over.built]p15:
6061 //
Douglas Gregor80af3132011-05-21 23:15:46 +00006062 // For every T, where T is an enumeration type, a pointer type, or
6063 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006064 //
6065 // bool operator<(T, T);
6066 // bool operator>(T, T);
6067 // bool operator<=(T, T);
6068 // bool operator>=(T, T);
6069 // bool operator==(T, T);
6070 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006071 void addRelationalPointerOrEnumeralOverloads() {
6072 // C++ [over.built]p1:
6073 // If there is a user-written candidate with the same name and parameter
6074 // types as a built-in candidate operator function, the built-in operator
6075 // function is hidden and is not included in the set of candidate
6076 // functions.
6077 //
6078 // The text is actually in a note, but if we don't implement it then we end
6079 // up with ambiguities when the user provides an overloaded operator for
6080 // an enumeration type. Note that only enumeration types have this problem,
6081 // so we track which enumeration types we've seen operators for. Also, the
6082 // only other overloaded operator with enumeration argumenst, operator=,
6083 // cannot be overloaded for enumeration types, so this is the only place
6084 // where we must suppress candidates like this.
6085 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6086 UserDefinedBinaryOperators;
6087
6088 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6089 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6090 CandidateTypes[ArgIdx].enumeration_end()) {
6091 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6092 CEnd = CandidateSet.end();
6093 C != CEnd; ++C) {
6094 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6095 continue;
6096
6097 QualType FirstParamType =
6098 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6099 QualType SecondParamType =
6100 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6101
6102 // Skip if either parameter isn't of enumeral type.
6103 if (!FirstParamType->isEnumeralType() ||
6104 !SecondParamType->isEnumeralType())
6105 continue;
6106
6107 // Add this operator to the set of known user-defined operators.
6108 UserDefinedBinaryOperators.insert(
6109 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6110 S.Context.getCanonicalType(SecondParamType)));
6111 }
6112 }
6113 }
6114
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006115 /// Set of (canonical) types that we've already handled.
6116 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6117
6118 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6119 for (BuiltinCandidateTypeSet::iterator
6120 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6121 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6122 Ptr != PtrEnd; ++Ptr) {
6123 // Don't add the same builtin candidate twice.
6124 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6125 continue;
6126
6127 QualType ParamTypes[2] = { *Ptr, *Ptr };
6128 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6129 CandidateSet);
6130 }
6131 for (BuiltinCandidateTypeSet::iterator
6132 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6133 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6134 Enum != EnumEnd; ++Enum) {
6135 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6136
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006137 // Don't add the same builtin candidate twice, or if a user defined
6138 // candidate exists.
6139 if (!AddedTypes.insert(CanonType) ||
6140 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6141 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006142 continue;
6143
6144 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006145 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6146 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006147 }
Douglas Gregor80af3132011-05-21 23:15:46 +00006148
6149 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6150 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6151 if (AddedTypes.insert(NullPtrTy) &&
6152 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6153 NullPtrTy))) {
6154 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6155 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6156 CandidateSet);
6157 }
6158 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006159 }
6160 }
6161
6162 // C++ [over.built]p13:
6163 //
6164 // For every cv-qualified or cv-unqualified object type T
6165 // there exist candidate operator functions of the form
6166 //
6167 // T* operator+(T*, ptrdiff_t);
6168 // T& operator[](T*, ptrdiff_t); [BELOW]
6169 // T* operator-(T*, ptrdiff_t);
6170 // T* operator+(ptrdiff_t, T*);
6171 // T& operator[](ptrdiff_t, T*); [BELOW]
6172 //
6173 // C++ [over.built]p14:
6174 //
6175 // For every T, where T is a pointer to object type, there
6176 // exist candidate operator functions of the form
6177 //
6178 // ptrdiff_t operator-(T, T);
6179 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6180 /// Set of (canonical) types that we've already handled.
6181 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6182
6183 for (int Arg = 0; Arg < 2; ++Arg) {
6184 QualType AsymetricParamTypes[2] = {
6185 S.Context.getPointerDiffType(),
6186 S.Context.getPointerDiffType(),
6187 };
6188 for (BuiltinCandidateTypeSet::iterator
6189 Ptr = CandidateTypes[Arg].pointer_begin(),
6190 PtrEnd = CandidateTypes[Arg].pointer_end();
6191 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006192 QualType PointeeTy = (*Ptr)->getPointeeType();
6193 if (!PointeeTy->isObjectType())
6194 continue;
6195
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006196 AsymetricParamTypes[Arg] = *Ptr;
6197 if (Arg == 0 || Op == OO_Plus) {
6198 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6199 // T* operator+(ptrdiff_t, T*);
6200 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6201 CandidateSet);
6202 }
6203 if (Op == OO_Minus) {
6204 // ptrdiff_t operator-(T, T);
6205 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6206 continue;
6207
6208 QualType ParamTypes[2] = { *Ptr, *Ptr };
6209 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6210 Args, 2, CandidateSet);
6211 }
6212 }
6213 }
6214 }
6215
6216 // C++ [over.built]p12:
6217 //
6218 // For every pair of promoted arithmetic types L and R, there
6219 // exist candidate operator functions of the form
6220 //
6221 // LR operator*(L, R);
6222 // LR operator/(L, R);
6223 // LR operator+(L, R);
6224 // LR operator-(L, R);
6225 // bool operator<(L, R);
6226 // bool operator>(L, R);
6227 // bool operator<=(L, R);
6228 // bool operator>=(L, R);
6229 // bool operator==(L, R);
6230 // bool operator!=(L, R);
6231 //
6232 // where LR is the result of the usual arithmetic conversions
6233 // between types L and R.
6234 //
6235 // C++ [over.built]p24:
6236 //
6237 // For every pair of promoted arithmetic types L and R, there exist
6238 // candidate operator functions of the form
6239 //
6240 // LR operator?(bool, L, R);
6241 //
6242 // where LR is the result of the usual arithmetic conversions
6243 // between types L and R.
6244 // Our candidates ignore the first parameter.
6245 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006246 if (!HasArithmeticOrEnumeralCandidateType)
6247 return;
6248
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006249 for (unsigned Left = FirstPromotedArithmeticType;
6250 Left < LastPromotedArithmeticType; ++Left) {
6251 for (unsigned Right = FirstPromotedArithmeticType;
6252 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006253 QualType LandR[2] = { getArithmeticType(Left),
6254 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006255 QualType Result =
6256 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006257 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006258 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6259 }
6260 }
6261
6262 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6263 // conditional operator for vector types.
6264 for (BuiltinCandidateTypeSet::iterator
6265 Vec1 = CandidateTypes[0].vector_begin(),
6266 Vec1End = CandidateTypes[0].vector_end();
6267 Vec1 != Vec1End; ++Vec1) {
6268 for (BuiltinCandidateTypeSet::iterator
6269 Vec2 = CandidateTypes[1].vector_begin(),
6270 Vec2End = CandidateTypes[1].vector_end();
6271 Vec2 != Vec2End; ++Vec2) {
6272 QualType LandR[2] = { *Vec1, *Vec2 };
6273 QualType Result = S.Context.BoolTy;
6274 if (!isComparison) {
6275 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6276 Result = *Vec1;
6277 else
6278 Result = *Vec2;
6279 }
6280
6281 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6282 }
6283 }
6284 }
6285
6286 // C++ [over.built]p17:
6287 //
6288 // For every pair of promoted integral types L and R, there
6289 // exist candidate operator functions of the form
6290 //
6291 // LR operator%(L, R);
6292 // LR operator&(L, R);
6293 // LR operator^(L, R);
6294 // LR operator|(L, R);
6295 // L operator<<(L, R);
6296 // L operator>>(L, R);
6297 //
6298 // where LR is the result of the usual arithmetic conversions
6299 // between types L and R.
6300 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006301 if (!HasArithmeticOrEnumeralCandidateType)
6302 return;
6303
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006304 for (unsigned Left = FirstPromotedIntegralType;
6305 Left < LastPromotedIntegralType; ++Left) {
6306 for (unsigned Right = FirstPromotedIntegralType;
6307 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006308 QualType LandR[2] = { getArithmeticType(Left),
6309 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006310 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6311 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006312 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006313 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6314 }
6315 }
6316 }
6317
6318 // C++ [over.built]p20:
6319 //
6320 // For every pair (T, VQ), where T is an enumeration or
6321 // pointer to member type and VQ is either volatile or
6322 // empty, there exist candidate operator functions of the form
6323 //
6324 // VQ T& operator=(VQ T&, T);
6325 void addAssignmentMemberPointerOrEnumeralOverloads() {
6326 /// Set of (canonical) types that we've already handled.
6327 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6328
6329 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6330 for (BuiltinCandidateTypeSet::iterator
6331 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6332 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6333 Enum != EnumEnd; ++Enum) {
6334 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6335 continue;
6336
6337 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6338 CandidateSet);
6339 }
6340
6341 for (BuiltinCandidateTypeSet::iterator
6342 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6343 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6344 MemPtr != MemPtrEnd; ++MemPtr) {
6345 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6346 continue;
6347
6348 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6349 CandidateSet);
6350 }
6351 }
6352 }
6353
6354 // C++ [over.built]p19:
6355 //
6356 // For every pair (T, VQ), where T is any type and VQ is either
6357 // volatile or empty, there exist candidate operator functions
6358 // of the form
6359 //
6360 // T*VQ& operator=(T*VQ&, T*);
6361 //
6362 // C++ [over.built]p21:
6363 //
6364 // For every pair (T, VQ), where T is a cv-qualified or
6365 // cv-unqualified object type and VQ is either volatile or
6366 // empty, there exist candidate operator functions of the form
6367 //
6368 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6369 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6370 void addAssignmentPointerOverloads(bool isEqualOp) {
6371 /// Set of (canonical) types that we've already handled.
6372 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6373
6374 for (BuiltinCandidateTypeSet::iterator
6375 Ptr = CandidateTypes[0].pointer_begin(),
6376 PtrEnd = CandidateTypes[0].pointer_end();
6377 Ptr != PtrEnd; ++Ptr) {
6378 // If this is operator=, keep track of the builtin candidates we added.
6379 if (isEqualOp)
6380 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006381 else if (!(*Ptr)->getPointeeType()->isObjectType())
6382 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006383
6384 // non-volatile version
6385 QualType ParamTypes[2] = {
6386 S.Context.getLValueReferenceType(*Ptr),
6387 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6388 };
6389 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6390 /*IsAssigmentOperator=*/ isEqualOp);
6391
6392 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6393 VisibleTypeConversionsQuals.hasVolatile()) {
6394 // volatile version
6395 ParamTypes[0] =
6396 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6397 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6398 /*IsAssigmentOperator=*/isEqualOp);
6399 }
6400 }
6401
6402 if (isEqualOp) {
6403 for (BuiltinCandidateTypeSet::iterator
6404 Ptr = CandidateTypes[1].pointer_begin(),
6405 PtrEnd = CandidateTypes[1].pointer_end();
6406 Ptr != PtrEnd; ++Ptr) {
6407 // Make sure we don't add the same candidate twice.
6408 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6409 continue;
6410
Chandler Carruth8e543b32010-12-12 08:17:55 +00006411 QualType ParamTypes[2] = {
6412 S.Context.getLValueReferenceType(*Ptr),
6413 *Ptr,
6414 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006415
6416 // non-volatile version
6417 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6418 /*IsAssigmentOperator=*/true);
6419
6420 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6421 VisibleTypeConversionsQuals.hasVolatile()) {
6422 // volatile version
6423 ParamTypes[0] =
6424 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006425 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6426 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006427 }
6428 }
6429 }
6430 }
6431
6432 // C++ [over.built]p18:
6433 //
6434 // For every triple (L, VQ, R), where L is an arithmetic type,
6435 // VQ is either volatile or empty, and R is a promoted
6436 // arithmetic type, there exist candidate operator functions of
6437 // the form
6438 //
6439 // VQ L& operator=(VQ L&, R);
6440 // VQ L& operator*=(VQ L&, R);
6441 // VQ L& operator/=(VQ L&, R);
6442 // VQ L& operator+=(VQ L&, R);
6443 // VQ L& operator-=(VQ L&, R);
6444 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006445 if (!HasArithmeticOrEnumeralCandidateType)
6446 return;
6447
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006448 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6449 for (unsigned Right = FirstPromotedArithmeticType;
6450 Right < LastPromotedArithmeticType; ++Right) {
6451 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006452 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006453
6454 // Add this built-in operator as a candidate (VQ is empty).
6455 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006456 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006457 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6458 /*IsAssigmentOperator=*/isEqualOp);
6459
6460 // Add this built-in operator as a candidate (VQ is 'volatile').
6461 if (VisibleTypeConversionsQuals.hasVolatile()) {
6462 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006463 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006464 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006465 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6466 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006467 /*IsAssigmentOperator=*/isEqualOp);
6468 }
6469 }
6470 }
6471
6472 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6473 for (BuiltinCandidateTypeSet::iterator
6474 Vec1 = CandidateTypes[0].vector_begin(),
6475 Vec1End = CandidateTypes[0].vector_end();
6476 Vec1 != Vec1End; ++Vec1) {
6477 for (BuiltinCandidateTypeSet::iterator
6478 Vec2 = CandidateTypes[1].vector_begin(),
6479 Vec2End = CandidateTypes[1].vector_end();
6480 Vec2 != Vec2End; ++Vec2) {
6481 QualType ParamTypes[2];
6482 ParamTypes[1] = *Vec2;
6483 // Add this built-in operator as a candidate (VQ is empty).
6484 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6485 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6486 /*IsAssigmentOperator=*/isEqualOp);
6487
6488 // Add this built-in operator as a candidate (VQ is 'volatile').
6489 if (VisibleTypeConversionsQuals.hasVolatile()) {
6490 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6491 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006492 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6493 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006494 /*IsAssigmentOperator=*/isEqualOp);
6495 }
6496 }
6497 }
6498 }
6499
6500 // C++ [over.built]p22:
6501 //
6502 // For every triple (L, VQ, R), where L is an integral type, VQ
6503 // is either volatile or empty, and R is a promoted integral
6504 // type, there exist candidate operator functions of the form
6505 //
6506 // VQ L& operator%=(VQ L&, R);
6507 // VQ L& operator<<=(VQ L&, R);
6508 // VQ L& operator>>=(VQ L&, R);
6509 // VQ L& operator&=(VQ L&, R);
6510 // VQ L& operator^=(VQ L&, R);
6511 // VQ L& operator|=(VQ L&, R);
6512 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006513 if (!HasArithmeticOrEnumeralCandidateType)
6514 return;
6515
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006516 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6517 for (unsigned Right = FirstPromotedIntegralType;
6518 Right < LastPromotedIntegralType; ++Right) {
6519 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006520 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006521
6522 // Add this built-in operator as a candidate (VQ is empty).
6523 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006524 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006525 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6526 if (VisibleTypeConversionsQuals.hasVolatile()) {
6527 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006528 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006529 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6530 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6531 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6532 CandidateSet);
6533 }
6534 }
6535 }
6536 }
6537
6538 // C++ [over.operator]p23:
6539 //
6540 // There also exist candidate operator functions of the form
6541 //
6542 // bool operator!(bool);
6543 // bool operator&&(bool, bool);
6544 // bool operator||(bool, bool);
6545 void addExclaimOverload() {
6546 QualType ParamTy = S.Context.BoolTy;
6547 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6548 /*IsAssignmentOperator=*/false,
6549 /*NumContextualBoolArguments=*/1);
6550 }
6551 void addAmpAmpOrPipePipeOverload() {
6552 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6553 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6554 /*IsAssignmentOperator=*/false,
6555 /*NumContextualBoolArguments=*/2);
6556 }
6557
6558 // C++ [over.built]p13:
6559 //
6560 // For every cv-qualified or cv-unqualified object type T there
6561 // exist candidate operator functions of the form
6562 //
6563 // T* operator+(T*, ptrdiff_t); [ABOVE]
6564 // T& operator[](T*, ptrdiff_t);
6565 // T* operator-(T*, ptrdiff_t); [ABOVE]
6566 // T* operator+(ptrdiff_t, T*); [ABOVE]
6567 // T& operator[](ptrdiff_t, T*);
6568 void addSubscriptOverloads() {
6569 for (BuiltinCandidateTypeSet::iterator
6570 Ptr = CandidateTypes[0].pointer_begin(),
6571 PtrEnd = CandidateTypes[0].pointer_end();
6572 Ptr != PtrEnd; ++Ptr) {
6573 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6574 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006575 if (!PointeeType->isObjectType())
6576 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006577
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006578 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6579
6580 // T& operator[](T*, ptrdiff_t)
6581 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6582 }
6583
6584 for (BuiltinCandidateTypeSet::iterator
6585 Ptr = CandidateTypes[1].pointer_begin(),
6586 PtrEnd = CandidateTypes[1].pointer_end();
6587 Ptr != PtrEnd; ++Ptr) {
6588 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6589 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006590 if (!PointeeType->isObjectType())
6591 continue;
6592
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006593 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6594
6595 // T& operator[](ptrdiff_t, T*)
6596 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6597 }
6598 }
6599
6600 // C++ [over.built]p11:
6601 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6602 // C1 is the same type as C2 or is a derived class of C2, T is an object
6603 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6604 // there exist candidate operator functions of the form
6605 //
6606 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6607 //
6608 // where CV12 is the union of CV1 and CV2.
6609 void addArrowStarOverloads() {
6610 for (BuiltinCandidateTypeSet::iterator
6611 Ptr = CandidateTypes[0].pointer_begin(),
6612 PtrEnd = CandidateTypes[0].pointer_end();
6613 Ptr != PtrEnd; ++Ptr) {
6614 QualType C1Ty = (*Ptr);
6615 QualType C1;
6616 QualifierCollector Q1;
6617 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6618 if (!isa<RecordType>(C1))
6619 continue;
6620 // heuristic to reduce number of builtin candidates in the set.
6621 // Add volatile/restrict version only if there are conversions to a
6622 // volatile/restrict type.
6623 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6624 continue;
6625 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6626 continue;
6627 for (BuiltinCandidateTypeSet::iterator
6628 MemPtr = CandidateTypes[1].member_pointer_begin(),
6629 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6630 MemPtr != MemPtrEnd; ++MemPtr) {
6631 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6632 QualType C2 = QualType(mptr->getClass(), 0);
6633 C2 = C2.getUnqualifiedType();
6634 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6635 break;
6636 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6637 // build CV12 T&
6638 QualType T = mptr->getPointeeType();
6639 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6640 T.isVolatileQualified())
6641 continue;
6642 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6643 T.isRestrictQualified())
6644 continue;
6645 T = Q1.apply(S.Context, T);
6646 QualType ResultTy = S.Context.getLValueReferenceType(T);
6647 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6648 }
6649 }
6650 }
6651
6652 // Note that we don't consider the first argument, since it has been
6653 // contextually converted to bool long ago. The candidates below are
6654 // therefore added as binary.
6655 //
6656 // C++ [over.built]p25:
6657 // For every type T, where T is a pointer, pointer-to-member, or scoped
6658 // enumeration type, there exist candidate operator functions of the form
6659 //
6660 // T operator?(bool, T, T);
6661 //
6662 void addConditionalOperatorOverloads() {
6663 /// Set of (canonical) types that we've already handled.
6664 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6665
6666 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6667 for (BuiltinCandidateTypeSet::iterator
6668 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6669 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6670 Ptr != PtrEnd; ++Ptr) {
6671 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6672 continue;
6673
6674 QualType ParamTypes[2] = { *Ptr, *Ptr };
6675 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6676 }
6677
6678 for (BuiltinCandidateTypeSet::iterator
6679 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6680 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6681 MemPtr != MemPtrEnd; ++MemPtr) {
6682 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6683 continue;
6684
6685 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6686 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6687 }
6688
6689 if (S.getLangOptions().CPlusPlus0x) {
6690 for (BuiltinCandidateTypeSet::iterator
6691 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6692 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6693 Enum != EnumEnd; ++Enum) {
6694 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6695 continue;
6696
6697 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6698 continue;
6699
6700 QualType ParamTypes[2] = { *Enum, *Enum };
6701 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6702 }
6703 }
6704 }
6705 }
6706};
6707
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006708} // end anonymous namespace
6709
6710/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6711/// operator overloads to the candidate set (C++ [over.built]), based
6712/// on the operator @p Op and the arguments given. For example, if the
6713/// operator is a binary '+', this routine might add "int
6714/// operator+(int, int)" to cover integer addition.
6715void
6716Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6717 SourceLocation OpLoc,
6718 Expr **Args, unsigned NumArgs,
6719 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006720 // Find all of the types that the arguments can convert to, but only
6721 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006722 // that make use of these types. Also record whether we encounter non-record
6723 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006724 Qualifiers VisibleTypeConversionsQuals;
6725 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006726 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6727 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006728
6729 bool HasNonRecordCandidateType = false;
6730 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006731 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006732 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6733 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6734 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6735 OpLoc,
6736 true,
6737 (Op == OO_Exclaim ||
6738 Op == OO_AmpAmp ||
6739 Op == OO_PipePipe),
6740 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006741 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6742 CandidateTypes[ArgIdx].hasNonRecordTypes();
6743 HasArithmeticOrEnumeralCandidateType =
6744 HasArithmeticOrEnumeralCandidateType ||
6745 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006746 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006747
Chandler Carruth00a38332010-12-13 01:44:01 +00006748 // Exit early when no non-record types have been added to the candidate set
6749 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00006750 //
6751 // We can't exit early for !, ||, or &&, since there we have always have
6752 // 'bool' overloads.
6753 if (!HasNonRecordCandidateType &&
6754 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00006755 return;
6756
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006757 // Setup an object to manage the common state for building overloads.
6758 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6759 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006760 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006761 CandidateTypes, CandidateSet);
6762
6763 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006764 switch (Op) {
6765 case OO_None:
6766 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00006767 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00006768
Chandler Carruth5184de02010-12-12 08:51:33 +00006769 case OO_New:
6770 case OO_Delete:
6771 case OO_Array_New:
6772 case OO_Array_Delete:
6773 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00006774 llvm_unreachable(
6775 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00006776
6777 case OO_Comma:
6778 case OO_Arrow:
6779 // C++ [over.match.oper]p3:
6780 // -- For the operator ',', the unary operator '&', or the
6781 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006782 break;
6783
6784 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006785 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006786 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006787 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006788
6789 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006790 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006791 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006792 } else {
6793 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6794 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6795 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006796 break;
6797
Chandler Carruth5184de02010-12-12 08:51:33 +00006798 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006799 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006800 OpBuilder.addUnaryStarPointerOverloads();
6801 else
6802 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6803 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006804
Chandler Carruth5184de02010-12-12 08:51:33 +00006805 case OO_Slash:
6806 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006807 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006808
6809 case OO_PlusPlus:
6810 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006811 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6812 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006813 break;
6814
Douglas Gregor84605ae2009-08-24 13:43:27 +00006815 case OO_EqualEqual:
6816 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006817 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006818 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006819
Douglas Gregora11693b2008-11-12 17:17:38 +00006820 case OO_Less:
6821 case OO_Greater:
6822 case OO_LessEqual:
6823 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006824 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006825 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6826 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006827
Douglas Gregora11693b2008-11-12 17:17:38 +00006828 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006829 case OO_Caret:
6830 case OO_Pipe:
6831 case OO_LessLess:
6832 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006833 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006834 break;
6835
Chandler Carruth5184de02010-12-12 08:51:33 +00006836 case OO_Amp: // '&' is either unary or binary
6837 if (NumArgs == 1)
6838 // C++ [over.match.oper]p3:
6839 // -- For the operator ',', the unary operator '&', or the
6840 // operator '->', the built-in candidates set is empty.
6841 break;
6842
6843 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6844 break;
6845
6846 case OO_Tilde:
6847 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6848 break;
6849
Douglas Gregora11693b2008-11-12 17:17:38 +00006850 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006851 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006852 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006853
6854 case OO_PlusEqual:
6855 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006856 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006857 // Fall through.
6858
6859 case OO_StarEqual:
6860 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006861 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006862 break;
6863
6864 case OO_PercentEqual:
6865 case OO_LessLessEqual:
6866 case OO_GreaterGreaterEqual:
6867 case OO_AmpEqual:
6868 case OO_CaretEqual:
6869 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006870 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006871 break;
6872
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006873 case OO_Exclaim:
6874 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006875 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006876
Douglas Gregora11693b2008-11-12 17:17:38 +00006877 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006878 case OO_PipePipe:
6879 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006880 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006881
6882 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006883 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006884 break;
6885
6886 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006887 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006888 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006889
6890 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006891 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006892 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6893 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006894 }
6895}
6896
Douglas Gregore254f902009-02-04 00:32:51 +00006897/// \brief Add function candidates found via argument-dependent lookup
6898/// to the set of overloading candidates.
6899///
6900/// This routine performs argument-dependent name lookup based on the
6901/// given function name (which may also be an operator name) and adds
6902/// all of the overload candidates found by ADL to the overload
6903/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006904void
Douglas Gregore254f902009-02-04 00:32:51 +00006905Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006906 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006907 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006908 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006909 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006910 bool PartialOverloading,
6911 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006912 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006913
John McCall91f61fc2010-01-26 06:04:06 +00006914 // FIXME: This approach for uniquing ADL results (and removing
6915 // redundant candidates from the set) relies on pointer-equality,
6916 // which means we need to key off the canonical decl. However,
6917 // always going back to the canonical decl might not get us the
6918 // right set of default arguments. What default arguments are
6919 // we supposed to consider on ADL candidates, anyway?
6920
Douglas Gregorcabea402009-09-22 15:41:20 +00006921 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006922 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6923 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006924
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006925 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006926 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6927 CandEnd = CandidateSet.end();
6928 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006929 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006930 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006931 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006932 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006933 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006934
6935 // For each of the ADL candidates we found, add it to the overload
6936 // set.
John McCall8fe68082010-01-26 07:16:45 +00006937 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006938 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006939 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006940 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006941 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006942
John McCalla0296f72010-03-19 07:35:19 +00006943 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006944 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006945 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006946 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006947 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006948 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006949 }
Douglas Gregore254f902009-02-04 00:32:51 +00006950}
6951
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006952/// isBetterOverloadCandidate - Determines whether the first overload
6953/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006954bool
John McCall5c32be02010-08-24 20:38:10 +00006955isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006956 const OverloadCandidate &Cand1,
6957 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006958 SourceLocation Loc,
6959 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006960 // Define viable functions to be better candidates than non-viable
6961 // functions.
6962 if (!Cand2.Viable)
6963 return Cand1.Viable;
6964 else if (!Cand1.Viable)
6965 return false;
6966
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006967 // C++ [over.match.best]p1:
6968 //
6969 // -- if F is a static member function, ICS1(F) is defined such
6970 // that ICS1(F) is neither better nor worse than ICS1(G) for
6971 // any function G, and, symmetrically, ICS1(G) is neither
6972 // better nor worse than ICS1(F).
6973 unsigned StartArg = 0;
6974 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6975 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006976
Douglas Gregord3cb3562009-07-07 23:38:56 +00006977 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006978 // A viable function F1 is defined to be a better function than another
6979 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006980 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006981 unsigned NumArgs = Cand1.Conversions.size();
6982 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6983 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006984 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006985 switch (CompareImplicitConversionSequences(S,
6986 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006987 Cand2.Conversions[ArgIdx])) {
6988 case ImplicitConversionSequence::Better:
6989 // Cand1 has a better conversion sequence.
6990 HasBetterConversion = true;
6991 break;
6992
6993 case ImplicitConversionSequence::Worse:
6994 // Cand1 can't be better than Cand2.
6995 return false;
6996
6997 case ImplicitConversionSequence::Indistinguishable:
6998 // Do nothing.
6999 break;
7000 }
7001 }
7002
Mike Stump11289f42009-09-09 15:08:12 +00007003 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00007004 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007005 if (HasBetterConversion)
7006 return true;
7007
Mike Stump11289f42009-09-09 15:08:12 +00007008 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00007009 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00007010 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00007011 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7012 return true;
Mike Stump11289f42009-09-09 15:08:12 +00007013
7014 // -- F1 and F2 are function template specializations, and the function
7015 // template for F1 is more specialized than the template for F2
7016 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00007017 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00007018 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00007019 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00007020 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00007021 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7022 Cand2.Function->getPrimaryTemplate(),
7023 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007024 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00007025 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00007026 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00007027 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00007028 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007029
Douglas Gregora1f013e2008-11-07 22:36:19 +00007030 // -- the context is an initialization by user-defined conversion
7031 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7032 // from the return type of F1 to the destination type (i.e.,
7033 // the type of the entity being initialized) is a better
7034 // conversion sequence than the standard conversion sequence
7035 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00007036 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00007037 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00007038 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00007039 switch (CompareStandardConversionSequences(S,
7040 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00007041 Cand2.FinalConversion)) {
7042 case ImplicitConversionSequence::Better:
7043 // Cand1 has a better conversion sequence.
7044 return true;
7045
7046 case ImplicitConversionSequence::Worse:
7047 // Cand1 can't be better than Cand2.
7048 return false;
7049
7050 case ImplicitConversionSequence::Indistinguishable:
7051 // Do nothing
7052 break;
7053 }
7054 }
7055
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007056 return false;
7057}
7058
Mike Stump11289f42009-09-09 15:08:12 +00007059/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007060/// within an overload candidate set.
7061///
7062/// \param CandidateSet the set of candidate functions.
7063///
7064/// \param Loc the location of the function name (or operator symbol) for
7065/// which overload resolution occurs.
7066///
Mike Stump11289f42009-09-09 15:08:12 +00007067/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00007068/// function, Best points to the candidate function found.
7069///
7070/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00007071OverloadingResult
7072OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00007073 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00007074 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007075 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00007076 Best = end();
7077 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7078 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007079 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007080 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007081 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007082 }
7083
7084 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00007085 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007086 return OR_No_Viable_Function;
7087
7088 // Make sure that this function is better than every other viable
7089 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00007090 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00007091 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007092 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007093 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00007094 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00007095 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007096 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00007097 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007098 }
Mike Stump11289f42009-09-09 15:08:12 +00007099
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007100 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00007101 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007102 (Best->Function->isDeleted() ||
7103 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00007104 return OR_Deleted;
7105
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007106 return OR_Success;
7107}
7108
John McCall53262c92010-01-12 02:15:36 +00007109namespace {
7110
7111enum OverloadCandidateKind {
7112 oc_function,
7113 oc_method,
7114 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00007115 oc_function_template,
7116 oc_method_template,
7117 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00007118 oc_implicit_default_constructor,
7119 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007120 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00007121 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00007122 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00007123 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00007124};
7125
John McCalle1ac8d12010-01-13 00:25:19 +00007126OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7127 FunctionDecl *Fn,
7128 std::string &Description) {
7129 bool isTemplate = false;
7130
7131 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7132 isTemplate = true;
7133 Description = S.getTemplateArgumentBindingsText(
7134 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7135 }
John McCallfd0b2f82010-01-06 09:43:14 +00007136
7137 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00007138 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007139 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007140
Sebastian Redl08905022011-02-05 19:23:19 +00007141 if (Ctor->getInheritedConstructor())
7142 return oc_implicit_inherited_constructor;
7143
Alexis Hunt119c10e2011-05-25 23:16:36 +00007144 if (Ctor->isDefaultConstructor())
7145 return oc_implicit_default_constructor;
7146
7147 if (Ctor->isMoveConstructor())
7148 return oc_implicit_move_constructor;
7149
7150 assert(Ctor->isCopyConstructor() &&
7151 "unexpected sort of implicit constructor");
7152 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00007153 }
7154
7155 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7156 // This actually gets spelled 'candidate function' for now, but
7157 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00007158 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00007159 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00007160
Alexis Hunt119c10e2011-05-25 23:16:36 +00007161 if (Meth->isMoveAssignmentOperator())
7162 return oc_implicit_move_assignment;
7163
Douglas Gregorec3bec02010-09-27 22:37:28 +00007164 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00007165 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00007166 return oc_implicit_copy_assignment;
7167 }
7168
John McCalle1ac8d12010-01-13 00:25:19 +00007169 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007170}
7171
Sebastian Redl08905022011-02-05 19:23:19 +00007172void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7173 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7174 if (!Ctor) return;
7175
7176 Ctor = Ctor->getInheritedConstructor();
7177 if (!Ctor) return;
7178
7179 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7180}
7181
John McCall53262c92010-01-12 02:15:36 +00007182} // end anonymous namespace
7183
7184// Notes the location of an overload candidate.
Richard Trieucaff2472011-11-23 22:32:32 +00007185void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCalle1ac8d12010-01-13 00:25:19 +00007186 std::string FnDesc;
7187 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieucaff2472011-11-23 22:32:32 +00007188 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7189 << (unsigned) K << FnDesc;
7190 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7191 Diag(Fn->getLocation(), PD);
Sebastian Redl08905022011-02-05 19:23:19 +00007192 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007193}
7194
Douglas Gregorb491ed32011-02-19 21:32:49 +00007195//Notes the location of all overload candidates designated through
7196// OverloadedExpr
Richard Trieucaff2472011-11-23 22:32:32 +00007197void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007198 assert(OverloadedExpr->getType() == Context.OverloadTy);
7199
7200 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7201 OverloadExpr *OvlExpr = Ovl.Expression;
7202
7203 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7204 IEnd = OvlExpr->decls_end();
7205 I != IEnd; ++I) {
7206 if (FunctionTemplateDecl *FunTmpl =
7207 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007208 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007209 } else if (FunctionDecl *Fun
7210 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieucaff2472011-11-23 22:32:32 +00007211 NoteOverloadCandidate(Fun, DestType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00007212 }
7213 }
7214}
7215
John McCall0d1da222010-01-12 00:44:57 +00007216/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7217/// "lead" diagnostic; it will be given two arguments, the source and
7218/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007219void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7220 Sema &S,
7221 SourceLocation CaretLoc,
7222 const PartialDiagnostic &PDiag) const {
7223 S.Diag(CaretLoc, PDiag)
7224 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007225 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007226 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7227 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007228 }
John McCall12f97bc2010-01-08 04:41:39 +00007229}
7230
John McCall0d1da222010-01-12 00:44:57 +00007231namespace {
7232
John McCall6a61b522010-01-13 09:16:55 +00007233void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7234 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7235 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007236 assert(Cand->Function && "for now, candidate must be a function");
7237 FunctionDecl *Fn = Cand->Function;
7238
7239 // There's a conversion slot for the object argument if this is a
7240 // non-constructor method. Note that 'I' corresponds the
7241 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007242 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007243 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007244 if (I == 0)
7245 isObjectArgument = true;
7246 else
7247 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007248 }
7249
John McCalle1ac8d12010-01-13 00:25:19 +00007250 std::string FnDesc;
7251 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7252
John McCall6a61b522010-01-13 09:16:55 +00007253 Expr *FromExpr = Conv.Bad.FromExpr;
7254 QualType FromTy = Conv.Bad.getFromType();
7255 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007256
John McCallfb7ad0f2010-02-02 02:42:52 +00007257 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007258 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007259 Expr *E = FromExpr->IgnoreParens();
7260 if (isa<UnaryOperator>(E))
7261 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007262 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007263
7264 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7265 << (unsigned) FnKind << FnDesc
7266 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7267 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007268 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007269 return;
7270 }
7271
John McCall6d174642010-01-23 08:10:49 +00007272 // Do some hand-waving analysis to see if the non-viability is due
7273 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007274 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7275 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7276 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7277 CToTy = RT->getPointeeType();
7278 else {
7279 // TODO: detect and diagnose the full richness of const mismatches.
7280 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7281 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7282 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7283 }
7284
7285 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7286 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7287 // It is dumb that we have to do this here.
7288 while (isa<ArrayType>(CFromTy))
7289 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7290 while (isa<ArrayType>(CToTy))
7291 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7292
7293 Qualifiers FromQs = CFromTy.getQualifiers();
7294 Qualifiers ToQs = CToTy.getQualifiers();
7295
7296 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7297 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7298 << (unsigned) FnKind << FnDesc
7299 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7300 << FromTy
7301 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7302 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007303 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007304 return;
7305 }
7306
John McCall31168b02011-06-15 23:02:42 +00007307 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007308 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007309 << (unsigned) FnKind << FnDesc
7310 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7311 << FromTy
7312 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7313 << (unsigned) isObjectArgument << I+1;
7314 MaybeEmitInheritedConstructorNote(S, Fn);
7315 return;
7316 }
7317
Douglas Gregoraec25842011-04-26 23:16:46 +00007318 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7319 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7320 << (unsigned) FnKind << FnDesc
7321 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7322 << FromTy
7323 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7324 << (unsigned) isObjectArgument << I+1;
7325 MaybeEmitInheritedConstructorNote(S, Fn);
7326 return;
7327 }
7328
John McCall47000992010-01-14 03:28:57 +00007329 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7330 assert(CVR && "unexpected qualifiers mismatch");
7331
7332 if (isObjectArgument) {
7333 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7334 << (unsigned) FnKind << FnDesc
7335 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7336 << FromTy << (CVR - 1);
7337 } else {
7338 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7339 << (unsigned) FnKind << FnDesc
7340 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7341 << FromTy << (CVR - 1) << I+1;
7342 }
Sebastian Redl08905022011-02-05 19:23:19 +00007343 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007344 return;
7345 }
7346
Sebastian Redla72462c2011-09-24 17:48:32 +00007347 // Special diagnostic for failure to convert an initializer list, since
7348 // telling the user that it has type void is not useful.
7349 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7350 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7351 << (unsigned) FnKind << FnDesc
7352 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7353 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7354 MaybeEmitInheritedConstructorNote(S, Fn);
7355 return;
7356 }
7357
John McCall6d174642010-01-23 08:10:49 +00007358 // Diagnose references or pointers to incomplete types differently,
7359 // since it's far from impossible that the incompleteness triggered
7360 // the failure.
7361 QualType TempFromTy = FromTy.getNonReferenceType();
7362 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7363 TempFromTy = PTy->getPointeeType();
7364 if (TempFromTy->isIncompleteType()) {
7365 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7366 << (unsigned) FnKind << FnDesc
7367 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7368 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007369 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007370 return;
7371 }
7372
Douglas Gregor56f2e342010-06-30 23:01:39 +00007373 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007374 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007375 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7376 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7377 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7378 FromPtrTy->getPointeeType()) &&
7379 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7380 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007381 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007382 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007383 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007384 }
7385 } else if (const ObjCObjectPointerType *FromPtrTy
7386 = FromTy->getAs<ObjCObjectPointerType>()) {
7387 if (const ObjCObjectPointerType *ToPtrTy
7388 = ToTy->getAs<ObjCObjectPointerType>())
7389 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7390 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7391 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7392 FromPtrTy->getPointeeType()) &&
7393 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007394 BaseToDerivedConversion = 2;
7395 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7396 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7397 !FromTy->isIncompleteType() &&
7398 !ToRefTy->getPointeeType()->isIncompleteType() &&
7399 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7400 BaseToDerivedConversion = 3;
7401 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007402
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007403 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007404 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007405 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007406 << (unsigned) FnKind << FnDesc
7407 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007408 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007409 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007410 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007411 return;
7412 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007413
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007414 if (isa<ObjCObjectPointerType>(CFromTy) &&
7415 isa<PointerType>(CToTy)) {
7416 Qualifiers FromQs = CFromTy.getQualifiers();
7417 Qualifiers ToQs = CToTy.getQualifiers();
7418 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7419 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7420 << (unsigned) FnKind << FnDesc
7421 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7422 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7423 MaybeEmitInheritedConstructorNote(S, Fn);
7424 return;
7425 }
7426 }
7427
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007428 // Emit the generic diagnostic and, optionally, add the hints to it.
7429 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7430 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007431 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007432 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7433 << (unsigned) (Cand->Fix.Kind);
7434
7435 // If we can fix the conversion, suggest the FixIts.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007436 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007437 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7438 HI != HE; ++HI)
7439 FDiag << *HI;
7440 S.Diag(Fn->getLocation(), FDiag);
7441
Sebastian Redl08905022011-02-05 19:23:19 +00007442 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007443}
7444
7445void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7446 unsigned NumFormalArgs) {
7447 // TODO: treat calls to a missing default constructor as a special case
7448
7449 FunctionDecl *Fn = Cand->Function;
7450 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7451
7452 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007453
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00007454 // With invalid overloaded operators, it's possible that we think we
7455 // have an arity mismatch when it fact it looks like we have the
7456 // right number of arguments, because only overloaded operators have
7457 // the weird behavior of overloading member and non-member functions.
7458 // Just don't report anything.
7459 if (Fn->isInvalidDecl() &&
7460 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7461 return;
7462
John McCall6a61b522010-01-13 09:16:55 +00007463 // at least / at most / exactly
7464 unsigned mode, modeCount;
7465 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007466 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7467 (Cand->FailureKind == ovl_fail_bad_deduction &&
7468 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007469 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00007470 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00007471 mode = 0; // "at least"
7472 else
7473 mode = 2; // "exactly"
7474 modeCount = MinParams;
7475 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007476 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7477 (Cand->FailureKind == ovl_fail_bad_deduction &&
7478 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00007479 if (MinParams != FnTy->getNumArgs())
7480 mode = 1; // "at most"
7481 else
7482 mode = 2; // "exactly"
7483 modeCount = FnTy->getNumArgs();
7484 }
7485
7486 std::string Description;
7487 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7488
7489 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007490 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00007491 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00007492 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007493}
7494
John McCall8b9ed552010-02-01 18:53:26 +00007495/// Diagnose a failed template-argument deduction.
7496void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7497 Expr **Args, unsigned NumArgs) {
7498 FunctionDecl *Fn = Cand->Function; // pattern
7499
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007500 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007501 NamedDecl *ParamD;
7502 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7503 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7504 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007505 switch (Cand->DeductionFailure.Result) {
7506 case Sema::TDK_Success:
7507 llvm_unreachable("TDK_success while diagnosing bad deduction");
7508
7509 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007510 assert(ParamD && "no parameter found for incomplete deduction result");
7511 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7512 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007513 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007514 return;
7515 }
7516
John McCall42d7d192010-08-05 09:05:08 +00007517 case Sema::TDK_Underqualified: {
7518 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7519 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7520
7521 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7522
7523 // Param will have been canonicalized, but it should just be a
7524 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007525 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007526 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007527 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007528 assert(S.Context.hasSameType(Param, NonCanonParam));
7529
7530 // Arg has also been canonicalized, but there's nothing we can do
7531 // about that. It also doesn't matter as much, because it won't
7532 // have any template parameters in it (because deduction isn't
7533 // done on dependent types).
7534 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7535
7536 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7537 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007538 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007539 return;
7540 }
7541
7542 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007543 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007544 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007545 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007546 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007547 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007548 which = 1;
7549 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007550 which = 2;
7551 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007552
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007553 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007554 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007555 << *Cand->DeductionFailure.getFirstArg()
7556 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007557 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007558 return;
7559 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007560
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007561 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007562 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007563 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007564 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007565 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7566 << ParamD->getDeclName();
7567 else {
7568 int index = 0;
7569 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7570 index = TTP->getIndex();
7571 else if (NonTypeTemplateParmDecl *NTTP
7572 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7573 index = NTTP->getIndex();
7574 else
7575 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007576 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007577 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7578 << (index + 1);
7579 }
Sebastian Redl08905022011-02-05 19:23:19 +00007580 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007581 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007582
Douglas Gregor02eb4832010-05-08 18:13:28 +00007583 case Sema::TDK_TooManyArguments:
7584 case Sema::TDK_TooFewArguments:
7585 DiagnoseArityMismatch(S, Cand, NumArgs);
7586 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007587
7588 case Sema::TDK_InstantiationDepth:
7589 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007590 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007591 return;
7592
7593 case Sema::TDK_SubstitutionFailure: {
7594 std::string ArgString;
7595 if (TemplateArgumentList *Args
7596 = Cand->DeductionFailure.getTemplateArgumentList())
7597 ArgString = S.getTemplateArgumentBindingsText(
7598 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7599 *Args);
7600 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7601 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007602 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007603 return;
7604 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007605
John McCall8b9ed552010-02-01 18:53:26 +00007606 // TODO: diagnose these individually, then kill off
7607 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007608 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007609 case Sema::TDK_FailedOverloadResolution:
7610 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007611 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007612 return;
7613 }
7614}
7615
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007616/// CUDA: diagnose an invalid call across targets.
7617void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7618 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7619 FunctionDecl *Callee = Cand->Function;
7620
7621 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7622 CalleeTarget = S.IdentifyCUDATarget(Callee);
7623
7624 std::string FnDesc;
7625 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7626
7627 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7628 << (unsigned) FnKind << CalleeTarget << CallerTarget;
7629}
7630
John McCall8b9ed552010-02-01 18:53:26 +00007631/// Generates a 'note' diagnostic for an overload candidate. We've
7632/// already generated a primary error at the call site.
7633///
7634/// It really does need to be a single diagnostic with its caret
7635/// pointed at the candidate declaration. Yes, this creates some
7636/// major challenges of technical writing. Yes, this makes pointing
7637/// out problems with specific arguments quite awkward. It's still
7638/// better than generating twenty screens of text for every failed
7639/// overload.
7640///
7641/// It would be great to be able to express per-candidate problems
7642/// more richly for those diagnostic clients that cared, but we'd
7643/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007644void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7645 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007646 FunctionDecl *Fn = Cand->Function;
7647
John McCall12f97bc2010-01-08 04:41:39 +00007648 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007649 if (Cand->Viable && (Fn->isDeleted() ||
7650 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007651 std::string FnDesc;
7652 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007653
7654 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007655 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007656 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007657 return;
John McCall12f97bc2010-01-08 04:41:39 +00007658 }
7659
John McCalle1ac8d12010-01-13 00:25:19 +00007660 // We don't really have anything else to say about viable candidates.
7661 if (Cand->Viable) {
7662 S.NoteOverloadCandidate(Fn);
7663 return;
7664 }
John McCall0d1da222010-01-12 00:44:57 +00007665
John McCall6a61b522010-01-13 09:16:55 +00007666 switch (Cand->FailureKind) {
7667 case ovl_fail_too_many_arguments:
7668 case ovl_fail_too_few_arguments:
7669 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007670
John McCall6a61b522010-01-13 09:16:55 +00007671 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007672 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7673
John McCallfe796dd2010-01-23 05:17:32 +00007674 case ovl_fail_trivial_conversion:
7675 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007676 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007677 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007678
John McCall65eb8792010-02-25 01:37:24 +00007679 case ovl_fail_bad_conversion: {
7680 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7681 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007682 if (Cand->Conversions[I].isBad())
7683 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007684
John McCall6a61b522010-01-13 09:16:55 +00007685 // FIXME: this currently happens when we're called from SemaInit
7686 // when user-conversion overload fails. Figure out how to handle
7687 // those conditions and diagnose them well.
7688 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007689 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007690
7691 case ovl_fail_bad_target:
7692 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00007693 }
John McCalld3224162010-01-08 00:58:21 +00007694}
7695
7696void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7697 // Desugar the type of the surrogate down to a function type,
7698 // retaining as many typedefs as possible while still showing
7699 // the function type (and, therefore, its parameter types).
7700 QualType FnType = Cand->Surrogate->getConversionType();
7701 bool isLValueReference = false;
7702 bool isRValueReference = false;
7703 bool isPointer = false;
7704 if (const LValueReferenceType *FnTypeRef =
7705 FnType->getAs<LValueReferenceType>()) {
7706 FnType = FnTypeRef->getPointeeType();
7707 isLValueReference = true;
7708 } else if (const RValueReferenceType *FnTypeRef =
7709 FnType->getAs<RValueReferenceType>()) {
7710 FnType = FnTypeRef->getPointeeType();
7711 isRValueReference = true;
7712 }
7713 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7714 FnType = FnTypePtr->getPointeeType();
7715 isPointer = true;
7716 }
7717 // Desugar down to a function type.
7718 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7719 // Reconstruct the pointer/reference as appropriate.
7720 if (isPointer) FnType = S.Context.getPointerType(FnType);
7721 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7722 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7723
7724 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7725 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007726 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007727}
7728
7729void NoteBuiltinOperatorCandidate(Sema &S,
7730 const char *Opc,
7731 SourceLocation OpLoc,
7732 OverloadCandidate *Cand) {
7733 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7734 std::string TypeStr("operator");
7735 TypeStr += Opc;
7736 TypeStr += "(";
7737 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7738 if (Cand->Conversions.size() == 1) {
7739 TypeStr += ")";
7740 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7741 } else {
7742 TypeStr += ", ";
7743 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7744 TypeStr += ")";
7745 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7746 }
7747}
7748
7749void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7750 OverloadCandidate *Cand) {
7751 unsigned NoOperands = Cand->Conversions.size();
7752 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7753 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007754 if (ICS.isBad()) break; // all meaningless after first invalid
7755 if (!ICS.isAmbiguous()) continue;
7756
John McCall5c32be02010-08-24 20:38:10 +00007757 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007758 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007759 }
7760}
7761
John McCall3712d9e2010-01-15 23:32:50 +00007762SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7763 if (Cand->Function)
7764 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007765 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007766 return Cand->Surrogate->getLocation();
7767 return SourceLocation();
7768}
7769
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007770static unsigned
7771RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00007772 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007773 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00007774 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007775
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007776 case Sema::TDK_Incomplete:
7777 return 1;
7778
7779 case Sema::TDK_Underqualified:
7780 case Sema::TDK_Inconsistent:
7781 return 2;
7782
7783 case Sema::TDK_SubstitutionFailure:
7784 case Sema::TDK_NonDeducedMismatch:
7785 return 3;
7786
7787 case Sema::TDK_InstantiationDepth:
7788 case Sema::TDK_FailedOverloadResolution:
7789 return 4;
7790
7791 case Sema::TDK_InvalidExplicitArguments:
7792 return 5;
7793
7794 case Sema::TDK_TooManyArguments:
7795 case Sema::TDK_TooFewArguments:
7796 return 6;
7797 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007798 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007799}
7800
John McCallad2587a2010-01-12 00:48:53 +00007801struct CompareOverloadCandidatesForDisplay {
7802 Sema &S;
7803 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007804
7805 bool operator()(const OverloadCandidate *L,
7806 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007807 // Fast-path this check.
7808 if (L == R) return false;
7809
John McCall12f97bc2010-01-08 04:41:39 +00007810 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007811 if (L->Viable) {
7812 if (!R->Viable) return true;
7813
7814 // TODO: introduce a tri-valued comparison for overload
7815 // candidates. Would be more worthwhile if we had a sort
7816 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007817 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7818 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007819 } else if (R->Viable)
7820 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007821
John McCall3712d9e2010-01-15 23:32:50 +00007822 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007823
John McCall3712d9e2010-01-15 23:32:50 +00007824 // Criteria by which we can sort non-viable candidates:
7825 if (!L->Viable) {
7826 // 1. Arity mismatches come after other candidates.
7827 if (L->FailureKind == ovl_fail_too_many_arguments ||
7828 L->FailureKind == ovl_fail_too_few_arguments)
7829 return false;
7830 if (R->FailureKind == ovl_fail_too_many_arguments ||
7831 R->FailureKind == ovl_fail_too_few_arguments)
7832 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007833
John McCallfe796dd2010-01-23 05:17:32 +00007834 // 2. Bad conversions come first and are ordered by the number
7835 // of bad conversions and quality of good conversions.
7836 if (L->FailureKind == ovl_fail_bad_conversion) {
7837 if (R->FailureKind != ovl_fail_bad_conversion)
7838 return true;
7839
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007840 // The conversion that can be fixed with a smaller number of changes,
7841 // comes first.
7842 unsigned numLFixes = L->Fix.NumConversionsFixed;
7843 unsigned numRFixes = R->Fix.NumConversionsFixed;
7844 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7845 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007846 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007847 if (numLFixes < numRFixes)
7848 return true;
7849 else
7850 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007851 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007852
John McCallfe796dd2010-01-23 05:17:32 +00007853 // If there's any ordering between the defined conversions...
7854 // FIXME: this might not be transitive.
7855 assert(L->Conversions.size() == R->Conversions.size());
7856
7857 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007858 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7859 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007860 switch (CompareImplicitConversionSequences(S,
7861 L->Conversions[I],
7862 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007863 case ImplicitConversionSequence::Better:
7864 leftBetter++;
7865 break;
7866
7867 case ImplicitConversionSequence::Worse:
7868 leftBetter--;
7869 break;
7870
7871 case ImplicitConversionSequence::Indistinguishable:
7872 break;
7873 }
7874 }
7875 if (leftBetter > 0) return true;
7876 if (leftBetter < 0) return false;
7877
7878 } else if (R->FailureKind == ovl_fail_bad_conversion)
7879 return false;
7880
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007881 if (L->FailureKind == ovl_fail_bad_deduction) {
7882 if (R->FailureKind != ovl_fail_bad_deduction)
7883 return true;
7884
7885 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7886 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00007887 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00007888 } else if (R->FailureKind == ovl_fail_bad_deduction)
7889 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007890
John McCall3712d9e2010-01-15 23:32:50 +00007891 // TODO: others?
7892 }
7893
7894 // Sort everything else by location.
7895 SourceLocation LLoc = GetLocationForCandidate(L);
7896 SourceLocation RLoc = GetLocationForCandidate(R);
7897
7898 // Put candidates without locations (e.g. builtins) at the end.
7899 if (LLoc.isInvalid()) return false;
7900 if (RLoc.isInvalid()) return true;
7901
7902 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007903 }
7904};
7905
John McCallfe796dd2010-01-23 05:17:32 +00007906/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007907/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00007908void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7909 Expr **Args, unsigned NumArgs) {
7910 assert(!Cand->Viable);
7911
7912 // Don't do anything on failures other than bad conversion.
7913 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7914
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007915 // We only want the FixIts if all the arguments can be corrected.
7916 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00007917 // Use a implicit copy initialization to check conversion fixes.
7918 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007919
John McCallfe796dd2010-01-23 05:17:32 +00007920 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007921 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007922 unsigned ConvCount = Cand->Conversions.size();
7923 while (true) {
7924 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7925 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007926 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00007927 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00007928 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007929 }
John McCallfe796dd2010-01-23 05:17:32 +00007930 }
7931
7932 if (ConvIdx == ConvCount)
7933 return;
7934
John McCall65eb8792010-02-25 01:37:24 +00007935 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7936 "remaining conversion is initialized?");
7937
Douglas Gregoradc7a702010-04-16 17:45:54 +00007938 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007939 // operation somehow.
7940 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007941
7942 const FunctionProtoType* Proto;
7943 unsigned ArgIdx = ConvIdx;
7944
7945 if (Cand->IsSurrogate) {
7946 QualType ConvType
7947 = Cand->Surrogate->getConversionType().getNonReferenceType();
7948 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7949 ConvType = ConvPtrType->getPointeeType();
7950 Proto = ConvType->getAs<FunctionProtoType>();
7951 ArgIdx--;
7952 } else if (Cand->Function) {
7953 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7954 if (isa<CXXMethodDecl>(Cand->Function) &&
7955 !isa<CXXConstructorDecl>(Cand->Function))
7956 ArgIdx--;
7957 } else {
7958 // Builtin binary operator with a bad first conversion.
7959 assert(ConvCount <= 3);
7960 for (; ConvIdx != ConvCount; ++ConvIdx)
7961 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007962 = TryCopyInitialization(S, Args[ConvIdx],
7963 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007964 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007965 /*InOverloadResolution*/ true,
7966 /*AllowObjCWritebackConversion=*/
7967 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00007968 return;
7969 }
7970
7971 // Fill in the rest of the conversions.
7972 unsigned NumArgsInProto = Proto->getNumArgs();
7973 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007974 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00007975 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007976 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007977 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007978 /*InOverloadResolution=*/true,
7979 /*AllowObjCWritebackConversion=*/
7980 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007981 // Store the FixIt in the candidate if it exists.
7982 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00007983 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007984 }
John McCallfe796dd2010-01-23 05:17:32 +00007985 else
7986 Cand->Conversions[ConvIdx].setEllipsis();
7987 }
7988}
7989
John McCalld3224162010-01-08 00:58:21 +00007990} // end anonymous namespace
7991
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007992/// PrintOverloadCandidates - When overload resolution fails, prints
7993/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007994/// set.
John McCall5c32be02010-08-24 20:38:10 +00007995void OverloadCandidateSet::NoteCandidates(Sema &S,
7996 OverloadCandidateDisplayKind OCD,
7997 Expr **Args, unsigned NumArgs,
7998 const char *Opc,
7999 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00008000 // Sort the candidates by viability and position. Sorting directly would
8001 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008002 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00008003 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8004 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00008005 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00008006 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00008007 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00008008 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008009 if (Cand->Function || Cand->IsSurrogate)
8010 Cands.push_back(Cand);
8011 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8012 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00008013 }
8014 }
8015
John McCallad2587a2010-01-12 00:48:53 +00008016 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00008017 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008018
John McCall0d1da222010-01-12 00:44:57 +00008019 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00008020
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008021 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00008022 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8023 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008024 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00008025 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8026 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00008027
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008028 // Set an arbitrary limit on the number of candidate functions we'll spam
8029 // the user with. FIXME: This limit should depend on details of the
8030 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00008031 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008032 break;
8033 }
8034 ++CandsShown;
8035
John McCalld3224162010-01-08 00:58:21 +00008036 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00008037 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00008038 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00008039 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008040 else {
8041 assert(Cand->Viable &&
8042 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00008043 // Generally we only see ambiguities including viable builtin
8044 // operators if overload resolution got screwed up by an
8045 // ambiguous user-defined conversion.
8046 //
8047 // FIXME: It's quite possible for different conversions to see
8048 // different ambiguities, though.
8049 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00008050 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00008051 ReportedAmbiguousConversions = true;
8052 }
John McCalld3224162010-01-08 00:58:21 +00008053
John McCall0d1da222010-01-12 00:44:57 +00008054 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00008055 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00008056 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008057 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00008058
8059 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00008060 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008061}
8062
Douglas Gregorb491ed32011-02-19 21:32:49 +00008063// [PossiblyAFunctionType] --> [Return]
8064// NonFunctionType --> NonFunctionType
8065// R (A) --> R(A)
8066// R (*)(A) --> R (A)
8067// R (&)(A) --> R (A)
8068// R (S::*)(A) --> R (A)
8069QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8070 QualType Ret = PossiblyAFunctionType;
8071 if (const PointerType *ToTypePtr =
8072 PossiblyAFunctionType->getAs<PointerType>())
8073 Ret = ToTypePtr->getPointeeType();
8074 else if (const ReferenceType *ToTypeRef =
8075 PossiblyAFunctionType->getAs<ReferenceType>())
8076 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008077 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008078 PossiblyAFunctionType->getAs<MemberPointerType>())
8079 Ret = MemTypePtr->getPointeeType();
8080 Ret =
8081 Context.getCanonicalType(Ret).getUnqualifiedType();
8082 return Ret;
8083}
Douglas Gregorcd695e52008-11-10 20:40:00 +00008084
Douglas Gregorb491ed32011-02-19 21:32:49 +00008085// A helper class to help with address of function resolution
8086// - allows us to avoid passing around all those ugly parameters
8087class AddressOfFunctionResolver
8088{
8089 Sema& S;
8090 Expr* SourceExpr;
8091 const QualType& TargetType;
8092 QualType TargetFunctionType; // Extracted function type from target type
8093
8094 bool Complain;
8095 //DeclAccessPair& ResultFunctionAccessPair;
8096 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008097
Douglas Gregorb491ed32011-02-19 21:32:49 +00008098 bool TargetTypeIsNonStaticMemberFunction;
8099 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008100
Douglas Gregorb491ed32011-02-19 21:32:49 +00008101 OverloadExpr::FindResult OvlExprInfo;
8102 OverloadExpr *OvlExpr;
8103 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00008104 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008105
Douglas Gregorb491ed32011-02-19 21:32:49 +00008106public:
8107 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8108 const QualType& TargetType, bool Complain)
8109 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8110 Complain(Complain), Context(S.getASTContext()),
8111 TargetTypeIsNonStaticMemberFunction(
8112 !!TargetType->getAs<MemberPointerType>()),
8113 FoundNonTemplateFunction(false),
8114 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8115 OvlExpr(OvlExprInfo.Expression)
8116 {
8117 ExtractUnqualifiedFunctionTypeFromTargetType();
8118
8119 if (!TargetFunctionType->isFunctionType()) {
8120 if (OvlExpr->hasExplicitTemplateArgs()) {
8121 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00008122 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00008123 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00008124
8125 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8126 if (!Method->isStatic()) {
8127 // If the target type is a non-function type and the function
8128 // found is a non-static member function, pretend as if that was
8129 // the target, it's the only possible type to end up with.
8130 TargetTypeIsNonStaticMemberFunction = true;
8131
8132 // And skip adding the function if its not in the proper form.
8133 // We'll diagnose this due to an empty set of functions.
8134 if (!OvlExprInfo.HasFormOfMemberPointer)
8135 return;
8136 }
8137 }
8138
Douglas Gregorb491ed32011-02-19 21:32:49 +00008139 Matches.push_back(std::make_pair(dap,Fn));
8140 }
Douglas Gregor9b146582009-07-08 20:55:45 +00008141 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008142 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00008143 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008144
8145 if (OvlExpr->hasExplicitTemplateArgs())
8146 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00008147
Douglas Gregorb491ed32011-02-19 21:32:49 +00008148 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8149 // C++ [over.over]p4:
8150 // If more than one function is selected, [...]
8151 if (Matches.size() > 1) {
8152 if (FoundNonTemplateFunction)
8153 EliminateAllTemplateMatches();
8154 else
8155 EliminateAllExceptMostSpecializedTemplate();
8156 }
8157 }
8158 }
8159
8160private:
8161 bool isTargetTypeAFunction() const {
8162 return TargetFunctionType->isFunctionType();
8163 }
8164
8165 // [ToType] [Return]
8166
8167 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8168 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8169 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8170 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8171 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8172 }
8173
8174 // return true if any matching specializations were found
8175 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8176 const DeclAccessPair& CurAccessFunPair) {
8177 if (CXXMethodDecl *Method
8178 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8179 // Skip non-static function templates when converting to pointer, and
8180 // static when converting to member pointer.
8181 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8182 return false;
8183 }
8184 else if (TargetTypeIsNonStaticMemberFunction)
8185 return false;
8186
8187 // C++ [over.over]p2:
8188 // If the name is a function template, template argument deduction is
8189 // done (14.8.2.2), and if the argument deduction succeeds, the
8190 // resulting template argument list is used to generate a single
8191 // function template specialization, which is added to the set of
8192 // overloaded functions considered.
8193 FunctionDecl *Specialization = 0;
8194 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8195 if (Sema::TemplateDeductionResult Result
8196 = S.DeduceTemplateArguments(FunctionTemplate,
8197 &OvlExplicitTemplateArgs,
8198 TargetFunctionType, Specialization,
8199 Info)) {
8200 // FIXME: make a note of the failed deduction for diagnostics.
8201 (void)Result;
8202 return false;
8203 }
8204
8205 // Template argument deduction ensures that we have an exact match.
8206 // This function template specicalization works.
8207 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8208 assert(TargetFunctionType
8209 == Context.getCanonicalType(Specialization->getType()));
8210 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8211 return true;
8212 }
8213
8214 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8215 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008216 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008217 // Skip non-static functions when converting to pointer, and static
8218 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008219 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8220 return false;
8221 }
8222 else if (TargetTypeIsNonStaticMemberFunction)
8223 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008224
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008225 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008226 if (S.getLangOptions().CUDA)
8227 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8228 if (S.CheckCUDATarget(Caller, FunDecl))
8229 return false;
8230
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008231 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008232 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8233 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008234 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8235 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008236 Matches.push_back(std::make_pair(CurAccessFunPair,
8237 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008238 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008239 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008240 }
Mike Stump11289f42009-09-09 15:08:12 +00008241 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008242
8243 return false;
8244 }
8245
8246 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8247 bool Ret = false;
8248
8249 // If the overload expression doesn't have the form of a pointer to
8250 // member, don't try to convert it to a pointer-to-member type.
8251 if (IsInvalidFormOfPointerToMemberFunction())
8252 return false;
8253
8254 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8255 E = OvlExpr->decls_end();
8256 I != E; ++I) {
8257 // Look through any using declarations to find the underlying function.
8258 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8259
8260 // C++ [over.over]p3:
8261 // Non-member functions and static member functions match
8262 // targets of type "pointer-to-function" or "reference-to-function."
8263 // Nonstatic member functions match targets of
8264 // type "pointer-to-member-function."
8265 // Note that according to DR 247, the containing class does not matter.
8266 if (FunctionTemplateDecl *FunctionTemplate
8267 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8268 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8269 Ret = true;
8270 }
8271 // If we have explicit template arguments supplied, skip non-templates.
8272 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8273 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8274 Ret = true;
8275 }
8276 assert(Ret || Matches.empty());
8277 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008278 }
8279
Douglas Gregorb491ed32011-02-19 21:32:49 +00008280 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008281 // [...] and any given function template specialization F1 is
8282 // eliminated if the set contains a second function template
8283 // specialization whose function template is more specialized
8284 // than the function template of F1 according to the partial
8285 // ordering rules of 14.5.5.2.
8286
8287 // The algorithm specified above is quadratic. We instead use a
8288 // two-pass algorithm (similar to the one used to identify the
8289 // best viable function in an overload set) that identifies the
8290 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008291
8292 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8293 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8294 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008295
John McCall58cc69d2010-01-27 01:50:18 +00008296 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008297 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8298 TPOC_Other, 0, SourceExpr->getLocStart(),
8299 S.PDiag(),
8300 S.PDiag(diag::err_addr_ovl_ambiguous)
8301 << Matches[0].second->getDeclName(),
8302 S.PDiag(diag::note_ovl_candidate)
8303 << (unsigned) oc_function_template,
Richard Trieucaff2472011-11-23 22:32:32 +00008304 Complain, TargetFunctionType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008305
Douglas Gregorb491ed32011-02-19 21:32:49 +00008306 if (Result != MatchesCopy.end()) {
8307 // Make it the first and only element
8308 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8309 Matches[0].second = cast<FunctionDecl>(*Result);
8310 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008311 }
8312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008313
Douglas Gregorb491ed32011-02-19 21:32:49 +00008314 void EliminateAllTemplateMatches() {
8315 // [...] any function template specializations in the set are
8316 // eliminated if the set also contains a non-template function, [...]
8317 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8318 if (Matches[I].second->getPrimaryTemplate() == 0)
8319 ++I;
8320 else {
8321 Matches[I] = Matches[--N];
8322 Matches.set_size(N);
8323 }
8324 }
8325 }
8326
8327public:
8328 void ComplainNoMatchesFound() const {
8329 assert(Matches.empty());
8330 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8331 << OvlExpr->getName() << TargetFunctionType
8332 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008333 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008334 }
8335
8336 bool IsInvalidFormOfPointerToMemberFunction() const {
8337 return TargetTypeIsNonStaticMemberFunction &&
8338 !OvlExprInfo.HasFormOfMemberPointer;
8339 }
8340
8341 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8342 // TODO: Should we condition this on whether any functions might
8343 // have matched, or is it more appropriate to do that in callers?
8344 // TODO: a fixit wouldn't hurt.
8345 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8346 << TargetType << OvlExpr->getSourceRange();
8347 }
8348
8349 void ComplainOfInvalidConversion() const {
8350 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8351 << OvlExpr->getName() << TargetType;
8352 }
8353
8354 void ComplainMultipleMatchesFound() const {
8355 assert(Matches.size() > 1);
8356 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8357 << OvlExpr->getName()
8358 << OvlExpr->getSourceRange();
Richard Trieucaff2472011-11-23 22:32:32 +00008359 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008360 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008361
8362 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8363
Douglas Gregorb491ed32011-02-19 21:32:49 +00008364 int getNumMatches() const { return Matches.size(); }
8365
8366 FunctionDecl* getMatchingFunctionDecl() const {
8367 if (Matches.size() != 1) return 0;
8368 return Matches[0].second;
8369 }
8370
8371 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8372 if (Matches.size() != 1) return 0;
8373 return &Matches[0].first;
8374 }
8375};
8376
8377/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8378/// an overloaded function (C++ [over.over]), where @p From is an
8379/// expression with overloaded function type and @p ToType is the type
8380/// we're trying to resolve to. For example:
8381///
8382/// @code
8383/// int f(double);
8384/// int f(int);
8385///
8386/// int (*pfd)(double) = f; // selects f(double)
8387/// @endcode
8388///
8389/// This routine returns the resulting FunctionDecl if it could be
8390/// resolved, and NULL otherwise. When @p Complain is true, this
8391/// routine will emit diagnostics if there is an error.
8392FunctionDecl *
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008393Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8394 QualType TargetType,
8395 bool Complain,
8396 DeclAccessPair &FoundResult,
8397 bool *pHadMultipleCandidates) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008398 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008399
8400 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8401 Complain);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008402 int NumMatches = Resolver.getNumMatches();
8403 FunctionDecl* Fn = 0;
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008404 if (NumMatches == 0 && Complain) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008405 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8406 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8407 else
8408 Resolver.ComplainNoMatchesFound();
8409 }
8410 else if (NumMatches > 1 && Complain)
8411 Resolver.ComplainMultipleMatchesFound();
8412 else if (NumMatches == 1) {
8413 Fn = Resolver.getMatchingFunctionDecl();
8414 assert(Fn);
8415 FoundResult = *Resolver.getMatchingFunctionAccessPair();
8416 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00008417 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00008418 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00008419 }
Abramo Bagnara5001caa2011-11-19 11:44:21 +00008420
8421 if (pHadMultipleCandidates)
8422 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregorb491ed32011-02-19 21:32:49 +00008423 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008424}
8425
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008426/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008427/// resolve that overloaded function expression down to a single function.
8428///
8429/// This routine can only resolve template-ids that refer to a single function
8430/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008431/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008432/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00008433FunctionDecl *
8434Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8435 bool Complain,
8436 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008437 // C++ [over.over]p1:
8438 // [...] [Note: any redundant set of parentheses surrounding the
8439 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008440 // C++ [over.over]p1:
8441 // [...] The overloaded function name can be preceded by the &
8442 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008443
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008444 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00008445 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008446 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00008447
8448 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00008449 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008450
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008451 // Look through all of the overloaded functions, searching for one
8452 // whose type matches exactly.
8453 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008454 for (UnresolvedSetIterator I = ovl->decls_begin(),
8455 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008456 // C++0x [temp.arg.explicit]p3:
8457 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008458 // where deduction is not done, if a template argument list is
8459 // specified and it, along with any default template arguments,
8460 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008461 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00008462 FunctionTemplateDecl *FunctionTemplate
8463 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008464
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008465 // C++ [over.over]p2:
8466 // If the name is a function template, template argument deduction is
8467 // done (14.8.2.2), and if the argument deduction succeeds, the
8468 // resulting template argument list is used to generate a single
8469 // function template specialization, which is added to the set of
8470 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008471 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008472 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008473 if (TemplateDeductionResult Result
8474 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8475 Specialization, Info)) {
8476 // FIXME: make a note of the failed deduction for diagnostics.
8477 (void)Result;
8478 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008479 }
8480
John McCall0009fcc2011-04-26 20:42:42 +00008481 assert(Specialization && "no specialization and no error?");
8482
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008483 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008484 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008485 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00008486 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8487 << ovl->getName();
8488 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008489 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008490 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00008491 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008492
John McCall0009fcc2011-04-26 20:42:42 +00008493 Matched = Specialization;
8494 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008495 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008496
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008497 return Matched;
8498}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008499
Douglas Gregor1beec452011-03-12 01:48:56 +00008500
8501
8502
John McCall50a2c2c2011-10-11 23:14:30 +00008503// Resolve and fix an overloaded expression that can be resolved
8504// because it identifies a single function template specialization.
8505//
Douglas Gregor1beec452011-03-12 01:48:56 +00008506// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00008507//
8508// Return true if it was logically possible to so resolve the
8509// expression, regardless of whether or not it succeeded. Always
8510// returns true if 'complain' is set.
8511bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8512 ExprResult &SrcExpr, bool doFunctionPointerConverion,
8513 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00008514 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00008515 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00008516 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00008517
John McCall50a2c2c2011-10-11 23:14:30 +00008518 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00008519
John McCall0009fcc2011-04-26 20:42:42 +00008520 DeclAccessPair found;
8521 ExprResult SingleFunctionExpression;
8522 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8523 ovl.Expression, /*complain*/ false, &found)) {
John McCall50a2c2c2011-10-11 23:14:30 +00008524 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8525 SrcExpr = ExprError();
8526 return true;
8527 }
John McCall0009fcc2011-04-26 20:42:42 +00008528
8529 // It is only correct to resolve to an instance method if we're
8530 // resolving a form that's permitted to be a pointer to member.
8531 // Otherwise we'll end up making a bound member expression, which
8532 // is illegal in all the contexts we resolve like this.
8533 if (!ovl.HasFormOfMemberPointer &&
8534 isa<CXXMethodDecl>(fn) &&
8535 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00008536 if (!complain) return false;
8537
8538 Diag(ovl.Expression->getExprLoc(),
8539 diag::err_bound_member_function)
8540 << 0 << ovl.Expression->getSourceRange();
8541
8542 // TODO: I believe we only end up here if there's a mix of
8543 // static and non-static candidates (otherwise the expression
8544 // would have 'bound member' type, not 'overload' type).
8545 // Ideally we would note which candidate was chosen and why
8546 // the static candidates were rejected.
8547 SrcExpr = ExprError();
8548 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008549 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008550
John McCall0009fcc2011-04-26 20:42:42 +00008551 // Fix the expresion to refer to 'fn'.
8552 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00008553 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00008554
8555 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00008556 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00008557 SingleFunctionExpression =
8558 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00008559 if (SingleFunctionExpression.isInvalid()) {
8560 SrcExpr = ExprError();
8561 return true;
8562 }
8563 }
John McCall0009fcc2011-04-26 20:42:42 +00008564 }
8565
8566 if (!SingleFunctionExpression.isUsable()) {
8567 if (complain) {
8568 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8569 << ovl.Expression->getName()
8570 << DestTypeForComplaining
8571 << OpRangeForComplaining
8572 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00008573 NoteAllOverloadCandidates(SrcExpr.get());
8574
8575 SrcExpr = ExprError();
8576 return true;
8577 }
8578
8579 return false;
John McCall0009fcc2011-04-26 20:42:42 +00008580 }
8581
John McCall50a2c2c2011-10-11 23:14:30 +00008582 SrcExpr = SingleFunctionExpression;
8583 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008584}
8585
Douglas Gregorcabea402009-09-22 15:41:20 +00008586/// \brief Add a single candidate to the overload set.
8587static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00008588 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008589 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008590 Expr **Args, unsigned NumArgs,
8591 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008592 bool PartialOverloading,
8593 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00008594 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00008595 if (isa<UsingShadowDecl>(Callee))
8596 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8597
Douglas Gregorcabea402009-09-22 15:41:20 +00008598 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00008599 if (ExplicitTemplateArgs) {
8600 assert(!KnownValid && "Explicit template arguments?");
8601 return;
8602 }
John McCalla0296f72010-03-19 07:35:19 +00008603 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00008604 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008605 return;
John McCalld14a8642009-11-21 08:51:07 +00008606 }
8607
8608 if (FunctionTemplateDecl *FuncTemplate
8609 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00008610 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8611 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00008612 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00008613 return;
8614 }
8615
Richard Smith95ce4f62011-06-26 22:19:54 +00008616 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00008617}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008618
Douglas Gregorcabea402009-09-22 15:41:20 +00008619/// \brief Add the overload candidates named by callee and/or found by argument
8620/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00008621void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00008622 Expr **Args, unsigned NumArgs,
8623 OverloadCandidateSet &CandidateSet,
8624 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00008625
8626#ifndef NDEBUG
8627 // Verify that ArgumentDependentLookup is consistent with the rules
8628 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00008629 //
Douglas Gregorcabea402009-09-22 15:41:20 +00008630 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8631 // and let Y be the lookup set produced by argument dependent
8632 // lookup (defined as follows). If X contains
8633 //
8634 // -- a declaration of a class member, or
8635 //
8636 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00008637 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00008638 //
8639 // -- a declaration that is neither a function or a function
8640 // template
8641 //
8642 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00008643
John McCall57500772009-12-16 12:17:52 +00008644 if (ULE->requiresADL()) {
8645 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8646 E = ULE->decls_end(); I != E; ++I) {
8647 assert(!(*I)->getDeclContext()->isRecord());
8648 assert(isa<UsingShadowDecl>(*I) ||
8649 !(*I)->getDeclContext()->isFunctionOrMethod());
8650 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008651 }
8652 }
8653#endif
8654
John McCall57500772009-12-16 12:17:52 +00008655 // It would be nice to avoid this copy.
8656 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008657 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008658 if (ULE->hasExplicitTemplateArgs()) {
8659 ULE->copyTemplateArgumentsInto(TABuffer);
8660 ExplicitTemplateArgs = &TABuffer;
8661 }
8662
8663 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8664 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008665 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008666 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008667 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008668
John McCall57500772009-12-16 12:17:52 +00008669 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008670 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8671 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008672 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008673 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008674 PartialOverloading,
8675 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008676}
John McCalld681c392009-12-16 08:11:27 +00008677
Richard Smith998a5912011-06-05 22:42:48 +00008678/// Attempt to recover from an ill-formed use of a non-dependent name in a
8679/// template, where the non-dependent name was declared after the template
8680/// was defined. This is common in code written for a compilers which do not
8681/// correctly implement two-stage name lookup.
8682///
8683/// Returns true if a viable candidate was found and a diagnostic was issued.
8684static bool
8685DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8686 const CXXScopeSpec &SS, LookupResult &R,
8687 TemplateArgumentListInfo *ExplicitTemplateArgs,
8688 Expr **Args, unsigned NumArgs) {
8689 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8690 return false;
8691
8692 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8693 SemaRef.LookupQualifiedName(R, DC);
8694
8695 if (!R.empty()) {
8696 R.suppressDiagnostics();
8697
8698 if (isa<CXXRecordDecl>(DC)) {
8699 // Don't diagnose names we find in classes; we get much better
8700 // diagnostics for these from DiagnoseEmptyLookup.
8701 R.clear();
8702 return false;
8703 }
8704
8705 OverloadCandidateSet Candidates(FnLoc);
8706 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8707 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8708 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008709 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008710
8711 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008712 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008713 // No viable functions. Don't bother the user with notes for functions
8714 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008715 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008716 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008717 }
Richard Smith998a5912011-06-05 22:42:48 +00008718
8719 // Find the namespaces where ADL would have looked, and suggest
8720 // declaring the function there instead.
8721 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8722 Sema::AssociatedClassSet AssociatedClasses;
8723 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8724 AssociatedNamespaces,
8725 AssociatedClasses);
8726 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008727 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008728 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008729 for (Sema::AssociatedNamespaceSet::iterator
8730 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008731 end = AssociatedNamespaces.end(); it != end; ++it) {
8732 if (!Std->Encloses(*it))
8733 SuggestedNamespaces.insert(*it);
8734 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008735 } else {
8736 // Lacking the 'std::' namespace, use all of the associated namespaces.
8737 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008738 }
8739
8740 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8741 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008742 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008743 SemaRef.Diag(Best->Function->getLocation(),
8744 diag::note_not_found_by_two_phase_lookup)
8745 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008746 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008747 SemaRef.Diag(Best->Function->getLocation(),
8748 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008749 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008750 } else {
8751 // FIXME: It would be useful to list the associated namespaces here,
8752 // but the diagnostics infrastructure doesn't provide a way to produce
8753 // a localized representation of a list of items.
8754 SemaRef.Diag(Best->Function->getLocation(),
8755 diag::note_not_found_by_two_phase_lookup)
8756 << R.getLookupName() << 2;
8757 }
8758
8759 // Try to recover by calling this function.
8760 return true;
8761 }
8762
8763 R.clear();
8764 }
8765
8766 return false;
8767}
8768
8769/// Attempt to recover from ill-formed use of a non-dependent operator in a
8770/// template, where the non-dependent operator was declared after the template
8771/// was defined.
8772///
8773/// Returns true if a viable candidate was found and a diagnostic was issued.
8774static bool
8775DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8776 SourceLocation OpLoc,
8777 Expr **Args, unsigned NumArgs) {
8778 DeclarationName OpName =
8779 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8780 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8781 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8782 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8783}
8784
John McCalld681c392009-12-16 08:11:27 +00008785/// Attempts to recover from a call where no functions were found.
8786///
8787/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008788static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008789BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008790 UnresolvedLookupExpr *ULE,
8791 SourceLocation LParenLoc,
8792 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008793 SourceLocation RParenLoc,
8794 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008795
8796 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008797 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008798
John McCall57500772009-12-16 12:17:52 +00008799 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008800 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008801 if (ULE->hasExplicitTemplateArgs()) {
8802 ULE->copyTemplateArgumentsInto(TABuffer);
8803 ExplicitTemplateArgs = &TABuffer;
8804 }
8805
John McCalld681c392009-12-16 08:11:27 +00008806 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8807 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008808 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8809 ExplicitTemplateArgs, Args, NumArgs) &&
8810 (!EmptyLookup ||
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00008811 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00008812 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00008813 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008814
John McCall57500772009-12-16 12:17:52 +00008815 assert(!R.empty() && "lookup results empty despite recovery");
8816
8817 // Build an implicit member call if appropriate. Just drop the
8818 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008819 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008820 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008821 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8822 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008823 else if (ExplicitTemplateArgs)
8824 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8825 else
8826 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8827
8828 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008829 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008830
8831 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008832 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008833 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008834 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008835 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008836}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008837
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008838/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008839/// (which eventually refers to the declaration Func) and the call
8840/// arguments Args/NumArgs, attempt to resolve the function call down
8841/// to a specific function. If overload resolution succeeds, returns
8842/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008843/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008844/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008845ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008846Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008847 SourceLocation LParenLoc,
8848 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008849 SourceLocation RParenLoc,
8850 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008851#ifndef NDEBUG
8852 if (ULE->requiresADL()) {
8853 // To do ADL, we must have found an unqualified name.
8854 assert(!ULE->getQualifier() && "qualified name with ADL");
8855
8856 // We don't perform ADL for implicit declarations of builtins.
8857 // Verify that this was correctly set up.
8858 FunctionDecl *F;
8859 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8860 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8861 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00008862 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008863
John McCall57500772009-12-16 12:17:52 +00008864 // We don't perform ADL in C.
8865 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008866 } else
8867 assert(!ULE->isStdAssociatedNamespace() &&
8868 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008869#endif
8870
John McCall4124c492011-10-17 18:40:02 +00008871 UnbridgedCastsSet UnbridgedCasts;
8872 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
8873 return ExprError();
8874
John McCallbc077cf2010-02-08 23:07:23 +00008875 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008876
John McCall57500772009-12-16 12:17:52 +00008877 // Add the functions denoted by the callee to the set of candidate
8878 // functions, including those from argument-dependent lookup.
8879 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008880
8881 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008882 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8883 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00008884 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008885 // In Microsoft mode, if we are inside a template class member function then
8886 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00008887 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008888 // classes.
Francois Pichetf707ae62011-11-11 00:12:11 +00008889 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetde232cb2011-11-25 01:10:54 +00008890 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008891 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8892 Context.DependentTy, VK_RValue,
8893 RParenLoc);
8894 CE->setTypeDependent(true);
8895 return Owned(CE);
8896 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008897 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008898 RParenLoc, /*EmptyLookup=*/true);
Francois Pichetbcf64712011-09-07 00:14:57 +00008899 }
John McCalld681c392009-12-16 08:11:27 +00008900
John McCall4124c492011-10-17 18:40:02 +00008901 UnbridgedCasts.restore();
8902
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008903 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008904 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008905 case OR_Success: {
8906 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008907 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008908 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00008909 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008910 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008911 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8912 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008913 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008914
Richard Smith998a5912011-06-05 22:42:48 +00008915 case OR_No_Viable_Function: {
8916 // Try to recover by looking for viable functions which the user might
8917 // have meant to call.
8918 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8919 Args, NumArgs, RParenLoc,
8920 /*EmptyLookup=*/false);
8921 if (!Recovery.isInvalid())
8922 return Recovery;
8923
Chris Lattner45d9d602009-02-17 07:29:20 +00008924 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008925 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008926 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008927 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008928 break;
Richard Smith998a5912011-06-05 22:42:48 +00008929 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008930
8931 case OR_Ambiguous:
8932 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008933 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008934 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008935 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008936
8937 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008938 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008939 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8940 << Best->Function->isDeleted()
8941 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008942 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008943 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008944 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00008945
8946 // We emitted an error for the unvailable/deleted function call but keep
8947 // the call in the AST.
8948 FunctionDecl *FDecl = Best->Function;
8949 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
8950 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
8951 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008952 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008953 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008954 }
8955
Douglas Gregorb412e172010-07-25 18:17:45 +00008956 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00008957 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008958}
8959
John McCall4c4c1df2010-01-26 03:27:55 +00008960static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00008961 return Functions.size() > 1 ||
8962 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8963}
8964
Douglas Gregor084d8552009-03-13 23:49:33 +00008965/// \brief Create a unary operation that may resolve to an overloaded
8966/// operator.
8967///
8968/// \param OpLoc The location of the operator itself (e.g., '*').
8969///
8970/// \param OpcIn The UnaryOperator::Opcode that describes this
8971/// operator.
8972///
8973/// \param Functions The set of non-member functions that will be
8974/// considered by overload resolution. The caller needs to build this
8975/// set based on the context using, e.g.,
8976/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8977/// set should not contain any member functions; those will be added
8978/// by CreateOverloadedUnaryOp().
8979///
8980/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00008981ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00008982Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8983 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00008984 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008985 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00008986
8987 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8988 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8989 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008990 // TODO: provide better source location info.
8991 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008992
John McCall4124c492011-10-17 18:40:02 +00008993 if (checkPlaceholderForOverload(*this, Input))
8994 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00008995
Douglas Gregor084d8552009-03-13 23:49:33 +00008996 Expr *Args[2] = { Input, 0 };
8997 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00008998
Douglas Gregor084d8552009-03-13 23:49:33 +00008999 // For post-increment and post-decrement, add the implicit '0' as
9000 // the second argument, so that we know this is a post-increment or
9001 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00009002 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009003 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00009004 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9005 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00009006 NumArgs = 2;
9007 }
9008
9009 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00009010 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00009011 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009012 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00009013 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009014 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00009015 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009016
John McCall58cc69d2010-01-27 01:50:18 +00009017 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00009018 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009019 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009020 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009021 /*ADL*/ true, IsOverloaded(Fns),
9022 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00009023 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009024 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00009025 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009026 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00009027 OpLoc));
9028 }
9029
9030 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009031 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00009032
9033 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009034 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00009035
9036 // Add operator candidates that are member functions.
9037 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9038
John McCall4c4c1df2010-01-26 03:27:55 +00009039 // Add candidates from ADL.
9040 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00009041 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00009042 /*ExplicitTemplateArgs*/ 0,
9043 CandidateSet);
9044
Douglas Gregor084d8552009-03-13 23:49:33 +00009045 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009046 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00009047
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009048 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9049
Douglas Gregor084d8552009-03-13 23:49:33 +00009050 // Perform overload resolution.
9051 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009052 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00009053 case OR_Success: {
9054 // We found a built-in operator or an overloaded operator.
9055 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00009056
Douglas Gregor084d8552009-03-13 23:49:33 +00009057 if (FnDecl) {
9058 // We matched an overloaded operator. Build a call to that
9059 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00009060
Chandler Carruth30141632011-02-25 19:41:05 +00009061 MarkDeclarationReferenced(OpLoc, FnDecl);
9062
Douglas Gregor084d8552009-03-13 23:49:33 +00009063 // Convert the arguments.
9064 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00009065 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009066
John Wiegley01296292011-04-08 18:41:53 +00009067 ExprResult InputRes =
9068 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9069 Best->FoundDecl, Method);
9070 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009071 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009072 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009073 } else {
9074 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009075 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00009076 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009077 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00009078 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009079 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00009080 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00009081 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00009082 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00009083 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009084 }
9085
John McCall4fa0d5f2010-05-06 18:15:07 +00009086 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9087
John McCall7decc9e2010-11-18 06:31:45 +00009088 // Determine the result type.
9089 QualType ResultTy = FnDecl->getResultType();
9090 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9091 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00009092
Douglas Gregor084d8552009-03-13 23:49:33 +00009093 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009094 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9095 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00009096 if (FnExpr.isInvalid())
9097 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00009098
Eli Friedman030eee42009-11-18 03:58:17 +00009099 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00009100 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009101 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009102 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00009103
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009104 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00009105 FnDecl))
9106 return ExprError();
9107
John McCallb268a282010-08-23 23:25:46 +00009108 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00009109 } else {
9110 // We matched a built-in operator. Convert the arguments, then
9111 // break out so that we will build the appropriate built-in
9112 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009113 ExprResult InputRes =
9114 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9115 Best->Conversions[0], AA_Passing);
9116 if (InputRes.isInvalid())
9117 return ExprError();
9118 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00009119 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00009120 }
John Wiegley01296292011-04-08 18:41:53 +00009121 }
9122
9123 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00009124 // This is an erroneous use of an operator which can be overloaded by
9125 // a non-member function. Check for non-member operators which were
9126 // defined too late to be candidates.
9127 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
9128 // FIXME: Recover by calling the found function.
9129 return ExprError();
9130
John Wiegley01296292011-04-08 18:41:53 +00009131 // No viable function; fall through to handling this as a
9132 // built-in operator, which will produce an error message for us.
9133 break;
9134
9135 case OR_Ambiguous:
9136 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9137 << UnaryOperator::getOpcodeStr(Opc)
9138 << Input->getType()
9139 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009140 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00009141 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9142 return ExprError();
9143
9144 case OR_Deleted:
9145 Diag(OpLoc, diag::err_ovl_deleted_oper)
9146 << Best->Function->isDeleted()
9147 << UnaryOperator::getOpcodeStr(Opc)
9148 << getDeletedOrUnavailableSuffix(Best->Function)
9149 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009150 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
9151 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009152 return ExprError();
9153 }
Douglas Gregor084d8552009-03-13 23:49:33 +00009154
9155 // Either we found no viable overloaded operator or we matched a
9156 // built-in operator. In either case, fall through to trying to
9157 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00009158 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00009159}
9160
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009161/// \brief Create a binary operation that may resolve to an overloaded
9162/// operator.
9163///
9164/// \param OpLoc The location of the operator itself (e.g., '+').
9165///
9166/// \param OpcIn The BinaryOperator::Opcode that describes this
9167/// operator.
9168///
9169/// \param Functions The set of non-member functions that will be
9170/// considered by overload resolution. The caller needs to build this
9171/// set based on the context using, e.g.,
9172/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9173/// set should not contain any member functions; those will be added
9174/// by CreateOverloadedBinOp().
9175///
9176/// \param LHS Left-hand argument.
9177/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009178ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009179Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009180 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009181 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009182 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009183 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009184 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009185
9186 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9187 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9188 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9189
9190 // If either side is type-dependent, create an appropriate dependent
9191 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009192 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009193 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009194 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009195 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009196 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009197 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009198 Context.DependentTy,
9199 VK_RValue, OK_Ordinary,
9200 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009201
Douglas Gregor5287f092009-11-05 00:51:44 +00009202 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9203 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009204 VK_LValue,
9205 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009206 Context.DependentTy,
9207 Context.DependentTy,
9208 OpLoc));
9209 }
John McCall4c4c1df2010-01-26 03:27:55 +00009210
9211 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009212 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009213 // TODO: provide better source location info in DNLoc component.
9214 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009215 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009216 = UnresolvedLookupExpr::Create(Context, NamingClass,
9217 NestedNameSpecifierLoc(), OpNameInfo,
9218 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009219 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009220 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009221 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009222 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009223 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009224 OpLoc));
9225 }
9226
John McCall4124c492011-10-17 18:40:02 +00009227 // Always do placeholder-like conversions on the RHS.
9228 if (checkPlaceholderForOverload(*this, Args[1]))
9229 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009230
John McCall526ab472011-10-25 17:37:35 +00009231 // Do placeholder-like conversion on the LHS; note that we should
9232 // not get here with a PseudoObject LHS.
9233 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +00009234 if (checkPlaceholderForOverload(*this, Args[0]))
9235 return ExprError();
9236
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009237 // If this is the assignment operator, we only perform overload resolution
9238 // if the left-hand side is a class or enumeration type. This is actually
9239 // a hack. The standard requires that we do overload resolution between the
9240 // various built-in candidates, but as DR507 points out, this can lead to
9241 // problems. So we do it this way, which pretty much follows what GCC does.
9242 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009243 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009244 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009245
John McCalle26a8722010-12-04 08:14:53 +00009246 // If this is the .* operator, which is not overloadable, just
9247 // create a built-in binary operator.
9248 if (Opc == BO_PtrMemD)
9249 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9250
Douglas Gregor084d8552009-03-13 23:49:33 +00009251 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009252 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009253
9254 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009255 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009256
9257 // Add operator candidates that are member functions.
9258 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9259
John McCall4c4c1df2010-01-26 03:27:55 +00009260 // Add candidates from ADL.
9261 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9262 Args, 2,
9263 /*ExplicitTemplateArgs*/ 0,
9264 CandidateSet);
9265
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009266 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009267 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009268
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009269 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9270
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009271 // Perform overload resolution.
9272 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009273 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009274 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009275 // We found a built-in operator or an overloaded operator.
9276 FunctionDecl *FnDecl = Best->Function;
9277
9278 if (FnDecl) {
9279 // We matched an overloaded operator. Build a call to that
9280 // operator.
9281
Chandler Carruth30141632011-02-25 19:41:05 +00009282 MarkDeclarationReferenced(OpLoc, FnDecl);
9283
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009284 // Convert the arguments.
9285 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009286 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009287 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009288
Chandler Carruth8e543b32010-12-12 08:17:55 +00009289 ExprResult Arg1 =
9290 PerformCopyInitialization(
9291 InitializedEntity::InitializeParameter(Context,
9292 FnDecl->getParamDecl(0)),
9293 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009294 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009295 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009296
John Wiegley01296292011-04-08 18:41:53 +00009297 ExprResult Arg0 =
9298 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9299 Best->FoundDecl, Method);
9300 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009301 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009302 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009303 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009304 } else {
9305 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009306 ExprResult Arg0 = PerformCopyInitialization(
9307 InitializedEntity::InitializeParameter(Context,
9308 FnDecl->getParamDecl(0)),
9309 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009310 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009311 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009312
Chandler Carruth8e543b32010-12-12 08:17:55 +00009313 ExprResult Arg1 =
9314 PerformCopyInitialization(
9315 InitializedEntity::InitializeParameter(Context,
9316 FnDecl->getParamDecl(1)),
9317 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009318 if (Arg1.isInvalid())
9319 return ExprError();
9320 Args[0] = LHS = Arg0.takeAs<Expr>();
9321 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009322 }
9323
John McCall4fa0d5f2010-05-06 18:15:07 +00009324 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9325
John McCall7decc9e2010-11-18 06:31:45 +00009326 // Determine the result type.
9327 QualType ResultTy = FnDecl->getResultType();
9328 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9329 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009330
9331 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009332 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9333 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009334 if (FnExpr.isInvalid())
9335 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009336
John McCallb268a282010-08-23 23:25:46 +00009337 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009338 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009339 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009340
9341 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009342 FnDecl))
9343 return ExprError();
9344
John McCallb268a282010-08-23 23:25:46 +00009345 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009346 } else {
9347 // We matched a built-in operator. Convert the arguments, then
9348 // break out so that we will build the appropriate built-in
9349 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009350 ExprResult ArgsRes0 =
9351 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9352 Best->Conversions[0], AA_Passing);
9353 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009354 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009355 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009356
John Wiegley01296292011-04-08 18:41:53 +00009357 ExprResult ArgsRes1 =
9358 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9359 Best->Conversions[1], AA_Passing);
9360 if (ArgsRes1.isInvalid())
9361 return ExprError();
9362 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009363 break;
9364 }
9365 }
9366
Douglas Gregor66950a32009-09-30 21:46:01 +00009367 case OR_No_Viable_Function: {
9368 // C++ [over.match.oper]p9:
9369 // If the operator is the operator , [...] and there are no
9370 // viable functions, then the operator is assumed to be the
9371 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00009372 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00009373 break;
9374
Chandler Carruth8e543b32010-12-12 08:17:55 +00009375 // For class as left operand for assignment or compound assigment
9376 // operator do not fall through to handling in built-in, but report that
9377 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00009378 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009379 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00009380 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00009381 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9382 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00009383 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00009384 } else {
Richard Smith998a5912011-06-05 22:42:48 +00009385 // This is an erroneous use of an operator which can be overloaded by
9386 // a non-member function. Check for non-member operators which were
9387 // defined too late to be candidates.
9388 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9389 // FIXME: Recover by calling the found function.
9390 return ExprError();
9391
Douglas Gregor66950a32009-09-30 21:46:01 +00009392 // No viable function; try to create a built-in operation, which will
9393 // produce an error. Then, show the non-viable candidates.
9394 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00009395 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009396 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00009397 "C++ binary operator overloading is missing candidates!");
9398 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00009399 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9400 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00009401 return move(Result);
9402 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009403
9404 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009405 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009406 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00009407 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00009408 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009409 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9410 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009411 return ExprError();
9412
9413 case OR_Deleted:
9414 Diag(OpLoc, diag::err_ovl_deleted_oper)
9415 << Best->Function->isDeleted()
9416 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009417 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00009418 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009419 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9420 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009421 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00009422 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009423
Douglas Gregor66950a32009-09-30 21:46:01 +00009424 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00009425 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009426}
9427
John McCalldadc5752010-08-24 06:29:42 +00009428ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00009429Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9430 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00009431 Expr *Base, Expr *Idx) {
9432 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00009433 DeclarationName OpName =
9434 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9435
9436 // If either side is type-dependent, create an appropriate dependent
9437 // expression.
9438 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9439
John McCall58cc69d2010-01-27 01:50:18 +00009440 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009441 // CHECKME: no 'operator' keyword?
9442 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9443 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00009444 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009445 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009446 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009447 /*ADL*/ true, /*Overloaded*/ false,
9448 UnresolvedSetIterator(),
9449 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00009450 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00009451
Sebastian Redladba46e2009-10-29 20:17:01 +00009452 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9453 Args, 2,
9454 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009455 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00009456 RLoc));
9457 }
9458
John McCall4124c492011-10-17 18:40:02 +00009459 // Handle placeholders on both operands.
9460 if (checkPlaceholderForOverload(*this, Args[0]))
9461 return ExprError();
9462 if (checkPlaceholderForOverload(*this, Args[1]))
9463 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009464
Sebastian Redladba46e2009-10-29 20:17:01 +00009465 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009466 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009467
9468 // Subscript can only be overloaded as a member function.
9469
9470 // Add operator candidates that are member functions.
9471 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9472
9473 // Add builtin operator candidates.
9474 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9475
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009476 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9477
Sebastian Redladba46e2009-10-29 20:17:01 +00009478 // Perform overload resolution.
9479 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009480 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00009481 case OR_Success: {
9482 // We found a built-in operator or an overloaded operator.
9483 FunctionDecl *FnDecl = Best->Function;
9484
9485 if (FnDecl) {
9486 // We matched an overloaded operator. Build a call to that
9487 // operator.
9488
Chandler Carruth30141632011-02-25 19:41:05 +00009489 MarkDeclarationReferenced(LLoc, FnDecl);
9490
John McCalla0296f72010-03-19 07:35:19 +00009491 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009492 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00009493
Sebastian Redladba46e2009-10-29 20:17:01 +00009494 // Convert the arguments.
9495 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00009496 ExprResult Arg0 =
9497 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9498 Best->FoundDecl, Method);
9499 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009500 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009501 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009502
Anders Carlssona68e51e2010-01-29 18:37:50 +00009503 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009504 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00009505 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009506 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00009507 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009508 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00009509 Owned(Args[1]));
9510 if (InputInit.isInvalid())
9511 return ExprError();
9512
9513 Args[1] = InputInit.takeAs<Expr>();
9514
Sebastian Redladba46e2009-10-29 20:17:01 +00009515 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00009516 QualType ResultTy = FnDecl->getResultType();
9517 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9518 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00009519
9520 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00009521 DeclarationNameLoc LocInfo;
9522 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9523 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009524 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9525 HadMultipleCandidates,
9526 LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00009527 if (FnExpr.isInvalid())
9528 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009529
John McCallb268a282010-08-23 23:25:46 +00009530 CXXOperatorCallExpr *TheCall =
9531 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00009532 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00009533 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009534
John McCallb268a282010-08-23 23:25:46 +00009535 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00009536 FnDecl))
9537 return ExprError();
9538
John McCallb268a282010-08-23 23:25:46 +00009539 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00009540 } else {
9541 // We matched a built-in operator. Convert the arguments, then
9542 // break out so that we will build the appropriate built-in
9543 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009544 ExprResult ArgsRes0 =
9545 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9546 Best->Conversions[0], AA_Passing);
9547 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009548 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009549 Args[0] = ArgsRes0.take();
9550
9551 ExprResult ArgsRes1 =
9552 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9553 Best->Conversions[1], AA_Passing);
9554 if (ArgsRes1.isInvalid())
9555 return ExprError();
9556 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009557
9558 break;
9559 }
9560 }
9561
9562 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00009563 if (CandidateSet.empty())
9564 Diag(LLoc, diag::err_ovl_no_oper)
9565 << Args[0]->getType() << /*subscript*/ 0
9566 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9567 else
9568 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9569 << Args[0]->getType()
9570 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009571 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9572 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00009573 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009574 }
9575
9576 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009577 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009578 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00009579 << Args[0]->getType() << Args[1]->getType()
9580 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009581 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9582 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009583 return ExprError();
9584
9585 case OR_Deleted:
9586 Diag(LLoc, diag::err_ovl_deleted_oper)
9587 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009588 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00009589 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009590 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9591 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009592 return ExprError();
9593 }
9594
9595 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00009596 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009597}
9598
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009599/// BuildCallToMemberFunction - Build a call to a member
9600/// function. MemExpr is the expression that refers to the member
9601/// function (and includes the object parameter), Args/NumArgs are the
9602/// arguments to the function call (not including the object
9603/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00009604/// expression refers to a non-static member function or an overloaded
9605/// member function.
John McCalldadc5752010-08-24 06:29:42 +00009606ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00009607Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9608 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009609 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00009610 assert(MemExprE->getType() == Context.BoundMemberTy ||
9611 MemExprE->getType() == Context.OverloadTy);
9612
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009613 // Dig out the member expression. This holds both the object
9614 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00009615 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009616
John McCall0009fcc2011-04-26 20:42:42 +00009617 // Determine whether this is a call to a pointer-to-member function.
9618 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9619 assert(op->getType() == Context.BoundMemberTy);
9620 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9621
9622 QualType fnType =
9623 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9624
9625 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9626 QualType resultType = proto->getCallResultType(Context);
9627 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9628
9629 // Check that the object type isn't more qualified than the
9630 // member function we're calling.
9631 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9632
9633 QualType objectType = op->getLHS()->getType();
9634 if (op->getOpcode() == BO_PtrMemI)
9635 objectType = objectType->castAs<PointerType>()->getPointeeType();
9636 Qualifiers objectQuals = objectType.getQualifiers();
9637
9638 Qualifiers difference = objectQuals - funcQuals;
9639 difference.removeObjCGCAttr();
9640 difference.removeAddressSpace();
9641 if (difference) {
9642 std::string qualsString = difference.getAsString();
9643 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9644 << fnType.getUnqualifiedType()
9645 << qualsString
9646 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9647 }
9648
9649 CXXMemberCallExpr *call
9650 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9651 resultType, valueKind, RParenLoc);
9652
9653 if (CheckCallReturnType(proto->getResultType(),
9654 op->getRHS()->getSourceRange().getBegin(),
9655 call, 0))
9656 return ExprError();
9657
9658 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9659 return ExprError();
9660
9661 return MaybeBindToTemporary(call);
9662 }
9663
John McCall4124c492011-10-17 18:40:02 +00009664 UnbridgedCastsSet UnbridgedCasts;
9665 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9666 return ExprError();
9667
John McCall10eae182009-11-30 22:42:35 +00009668 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009669 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009670 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009671 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009672 if (isa<MemberExpr>(NakedMemExpr)) {
9673 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009674 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009675 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009676 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +00009677 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +00009678 } else {
9679 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009680 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009681
John McCall6e9f8f62009-12-03 04:06:58 +00009682 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009683 Expr::Classification ObjectClassification
9684 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9685 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009686
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009687 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009688 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009689
John McCall2d74de92009-12-01 22:10:20 +00009690 // FIXME: avoid copy.
9691 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9692 if (UnresExpr->hasExplicitTemplateArgs()) {
9693 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9694 TemplateArgs = &TemplateArgsBuffer;
9695 }
9696
John McCall10eae182009-11-30 22:42:35 +00009697 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9698 E = UnresExpr->decls_end(); I != E; ++I) {
9699
John McCall6e9f8f62009-12-03 04:06:58 +00009700 NamedDecl *Func = *I;
9701 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9702 if (isa<UsingShadowDecl>(Func))
9703 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9704
Douglas Gregor02824322011-01-26 19:30:28 +00009705
Francois Pichet64225792011-01-18 05:04:39 +00009706 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +00009707 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +00009708 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9709 CandidateSet);
9710 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009711 // If explicit template arguments were provided, we can't call a
9712 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009713 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009714 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009715
John McCalla0296f72010-03-19 07:35:19 +00009716 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009717 ObjectClassification,
9718 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009719 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009720 } else {
John McCall10eae182009-11-30 22:42:35 +00009721 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009722 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009723 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009724 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009725 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009726 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009727 }
Mike Stump11289f42009-09-09 15:08:12 +00009728
John McCall10eae182009-11-30 22:42:35 +00009729 DeclarationName DeclName = UnresExpr->getMemberName();
9730
John McCall4124c492011-10-17 18:40:02 +00009731 UnbridgedCasts.restore();
9732
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009733 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009734 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009735 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009736 case OR_Success:
9737 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009738 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009739 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009740 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009741 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009742 break;
9743
9744 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009745 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009746 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009747 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009748 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009749 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009750 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009751
9752 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009753 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009754 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009755 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009756 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009757 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009758
9759 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009760 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009761 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009762 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009763 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009764 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009765 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009766 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009767 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009768 }
9769
John McCall16df1e52010-03-30 21:47:33 +00009770 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009771
John McCall2d74de92009-12-01 22:10:20 +00009772 // If overload resolution picked a static member, build a
9773 // non-member call based on that function.
9774 if (Method->isStatic()) {
9775 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9776 Args, NumArgs, RParenLoc);
9777 }
9778
John McCall10eae182009-11-30 22:42:35 +00009779 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009780 }
9781
John McCall7decc9e2010-11-18 06:31:45 +00009782 QualType ResultType = Method->getResultType();
9783 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9784 ResultType = ResultType.getNonLValueExprType(Context);
9785
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009786 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009787 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009788 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009789 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009790
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009791 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009792 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009793 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009794 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009795
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009796 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009797 // We only need to do this if there was actually an overload; otherwise
9798 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009799 if (!Method->isStatic()) {
9800 ExprResult ObjectArg =
9801 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9802 FoundDecl, Method);
9803 if (ObjectArg.isInvalid())
9804 return ExprError();
9805 MemExpr->setBase(ObjectArg.take());
9806 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009807
9808 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009809 const FunctionProtoType *Proto =
9810 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009811 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009812 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009813 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009814
John McCallb268a282010-08-23 23:25:46 +00009815 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009816 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009817
Anders Carlsson47061ee2011-05-06 14:25:31 +00009818 if ((isa<CXXConstructorDecl>(CurContext) ||
9819 isa<CXXDestructorDecl>(CurContext)) &&
9820 TheCall->getMethodDecl()->isPure()) {
9821 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9822
Chandler Carruth59259262011-06-27 08:31:58 +00009823 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009824 Diag(MemExpr->getLocStart(),
9825 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9826 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9827 << MD->getParent()->getDeclName();
9828
9829 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009830 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009831 }
John McCallb268a282010-08-23 23:25:46 +00009832 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009833}
9834
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009835/// BuildCallToObjectOfClassType - Build a call to an object of class
9836/// type (C++ [over.call.object]), which can end up invoking an
9837/// overloaded function call operator (@c operator()) or performing a
9838/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009839ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009840Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009841 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009842 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009843 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +00009844 if (checkPlaceholderForOverload(*this, Obj))
9845 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009846 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +00009847
9848 UnbridgedCastsSet UnbridgedCasts;
9849 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9850 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009851
John Wiegley01296292011-04-08 18:41:53 +00009852 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9853 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009854
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009855 // C++ [over.call.object]p1:
9856 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009857 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009858 // candidate functions includes at least the function call
9859 // operators of T. The function call operators of T are obtained by
9860 // ordinary lookup of the name operator() in the context of
9861 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009862 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009863 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009864
John Wiegley01296292011-04-08 18:41:53 +00009865 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009866 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009867 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009868 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009869
John McCall27b18f82009-11-17 02:14:36 +00009870 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9871 LookupQualifiedName(R, Record->getDecl());
9872 R.suppressDiagnostics();
9873
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009874 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009875 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009876 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9877 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009878 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009879 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009880
Douglas Gregorab7897a2008-11-19 22:57:39 +00009881 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009882 // In addition, for each (non-explicit in C++0x) conversion function
9883 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +00009884 //
9885 // operator conversion-type-id () cv-qualifier;
9886 //
9887 // where cv-qualifier is the same cv-qualification as, or a
9888 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009889 // denotes the type "pointer to function of (P1,...,Pn) returning
9890 // R", or the type "reference to pointer to function of
9891 // (P1,...,Pn) returning R", or the type "reference to function
9892 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009893 // is also considered as a candidate function. Similarly,
9894 // surrogate call functions are added to the set of candidate
9895 // functions for each conversion function declared in an
9896 // accessible base class provided the function is not hidden
9897 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009898 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009899 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009900 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009901 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009902 NamedDecl *D = *I;
9903 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9904 if (isa<UsingShadowDecl>(D))
9905 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009906
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009907 // Skip over templated conversion functions; they aren't
9908 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009909 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009910 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009911
John McCall6e9f8f62009-12-03 04:06:58 +00009912 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009913 if (!Conv->isExplicit()) {
9914 // Strip the reference type (if any) and then the pointer type (if
9915 // any) to get down to what might be a function type.
9916 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9917 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9918 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +00009919
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009920 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9921 {
9922 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9923 Object.get(), Args, NumArgs, CandidateSet);
9924 }
9925 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00009926 }
Mike Stump11289f42009-09-09 15:08:12 +00009927
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009928 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9929
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009930 // Perform overload resolution.
9931 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009932 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009933 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009934 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009935 // Overload resolution succeeded; we'll build the appropriate call
9936 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009937 break;
9938
9939 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009940 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009941 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9942 << Object.get()->getType() << /*call*/ 1
9943 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009944 else
John Wiegley01296292011-04-08 18:41:53 +00009945 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009946 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009947 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009948 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009949 break;
9950
9951 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009952 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009953 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009954 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009955 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009956 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009957
9958 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00009959 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00009960 diag::err_ovl_deleted_object_call)
9961 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +00009962 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009963 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +00009964 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009965 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009966 break;
Mike Stump11289f42009-09-09 15:08:12 +00009967 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009968
Douglas Gregorb412e172010-07-25 18:17:45 +00009969 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009970 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009971
John McCall4124c492011-10-17 18:40:02 +00009972 UnbridgedCasts.restore();
9973
Douglas Gregorab7897a2008-11-19 22:57:39 +00009974 if (Best->Function == 0) {
9975 // Since there is no function declaration, this is one of the
9976 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00009977 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00009978 = cast<CXXConversionDecl>(
9979 Best->Conversions[0].UserDefined.ConversionFunction);
9980
John Wiegley01296292011-04-08 18:41:53 +00009981 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009982 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009983
Douglas Gregorab7897a2008-11-19 22:57:39 +00009984 // We selected one of the surrogate functions that converts the
9985 // object parameter to a function pointer. Perform the conversion
9986 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009987
Fariborz Jahanian774cf792009-09-28 18:35:46 +00009988 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00009989 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009990 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
9991 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00009992 if (Call.isInvalid())
9993 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00009994 // Record usage of conversion in an implicit cast.
9995 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
9996 CK_UserDefinedConversion,
9997 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009998
Douglas Gregor668443e2011-01-20 00:18:04 +00009999 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +000010000 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +000010001 }
10002
Chandler Carruth30141632011-02-25 19:41:05 +000010003 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010004 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010005 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +000010006
Douglas Gregorab7897a2008-11-19 22:57:39 +000010007 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10008 // that calls this method, using Object for the implicit object
10009 // parameter and passing along the remaining arguments.
10010 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +000010011 const FunctionProtoType *Proto =
10012 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010013
10014 unsigned NumArgsInProto = Proto->getNumArgs();
10015 unsigned NumArgsToCheck = NumArgs;
10016
10017 // Build the full argument list for the method call (the
10018 // implicit object parameter is placed at the beginning of the
10019 // list).
10020 Expr **MethodArgs;
10021 if (NumArgs < NumArgsInProto) {
10022 NumArgsToCheck = NumArgsInProto;
10023 MethodArgs = new Expr*[NumArgsInProto + 1];
10024 } else {
10025 MethodArgs = new Expr*[NumArgs + 1];
10026 }
John Wiegley01296292011-04-08 18:41:53 +000010027 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010028 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10029 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +000010030
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010031 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
10032 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010033 if (NewFn.isInvalid())
10034 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010035
10036 // Once we've built TheCall, all of the expressions are properly
10037 // owned.
John McCall7decc9e2010-11-18 06:31:45 +000010038 QualType ResultTy = Method->getResultType();
10039 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10040 ResultTy = ResultTy.getNonLValueExprType(Context);
10041
John McCallb268a282010-08-23 23:25:46 +000010042 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010043 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +000010044 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +000010045 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010046 delete [] MethodArgs;
10047
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010048 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +000010049 Method))
10050 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010051
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010052 // We may have default arguments. If so, we need to allocate more
10053 // slots in the call for them.
10054 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +000010055 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010056 else if (NumArgs > NumArgsInProto)
10057 NumArgsToCheck = NumArgsInProto;
10058
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010059 bool IsError = false;
10060
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010061 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +000010062 ExprResult ObjRes =
10063 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10064 Best->FoundDecl, Method);
10065 if (ObjRes.isInvalid())
10066 IsError = true;
10067 else
10068 Object = move(ObjRes);
10069 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010070
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010071 // Check the argument types.
10072 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010073 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010074 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010075 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +000010076
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010077 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010078
John McCalldadc5752010-08-24 06:29:42 +000010079 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010080 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +000010081 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010082 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +000010083 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010084
Anders Carlsson7c5fe482010-01-29 18:43:53 +000010085 IsError |= InputInit.isInvalid();
10086 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010087 } else {
John McCalldadc5752010-08-24 06:29:42 +000010088 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010089 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10090 if (DefArg.isInvalid()) {
10091 IsError = true;
10092 break;
10093 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010094
Douglas Gregor1bc688d2009-11-09 19:27:57 +000010095 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +000010096 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010097
10098 TheCall->setArg(i + 1, Arg);
10099 }
10100
10101 // If this is a variadic call, handle args passed through "...".
10102 if (Proto->isVariadic()) {
10103 // Promote the arguments (C99 6.5.2.2p7).
10104 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +000010105 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10106 IsError |= Arg.isInvalid();
10107 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010108 }
10109 }
10110
Chris Lattnera8a7d0f2009-04-12 08:11:20 +000010111 if (IsError) return true;
10112
John McCallb268a282010-08-23 23:25:46 +000010113 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +000010114 return true;
10115
John McCalle172be52010-08-24 06:09:16 +000010116 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +000010117}
10118
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010119/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +000010120/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010121/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +000010122ExprResult
John McCallb268a282010-08-23 23:25:46 +000010123Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +000010124 assert(Base->getType()->isRecordType() &&
10125 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +000010126
John McCall4124c492011-10-17 18:40:02 +000010127 if (checkPlaceholderForOverload(*this, Base))
10128 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +000010129
John McCallbc077cf2010-02-08 23:07:23 +000010130 SourceLocation Loc = Base->getExprLoc();
10131
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010132 // C++ [over.ref]p1:
10133 //
10134 // [...] An expression x->m is interpreted as (x.operator->())->m
10135 // for a class object x of type T if T::operator->() exists and if
10136 // the operator is selected as the best match function by the
10137 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +000010138 DeclarationName OpName =
10139 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +000010140 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +000010141 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +000010142
John McCallbc077cf2010-02-08 23:07:23 +000010143 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +000010144 PDiag(diag::err_typecheck_incomplete_tag)
10145 << Base->getSourceRange()))
10146 return ExprError();
10147
John McCall27b18f82009-11-17 02:14:36 +000010148 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10149 LookupQualifiedName(R, BaseRecord->getDecl());
10150 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +000010151
10152 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +000010153 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +000010154 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10155 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +000010156 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010157
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010158 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10159
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010160 // Perform overload resolution.
10161 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +000010162 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010163 case OR_Success:
10164 // Overload resolution succeeded; we'll build the call below.
10165 break;
10166
10167 case OR_No_Viable_Function:
10168 if (CandidateSet.empty())
10169 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +000010170 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010171 else
10172 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +000010173 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010174 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010175 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010176
10177 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010178 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10179 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010180 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010181 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010182
10183 case OR_Deleted:
10184 Diag(OpLoc, diag::err_ovl_deleted_oper)
10185 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010186 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010187 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010188 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010189 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010190 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010191 }
10192
Chandler Carruth30141632011-02-25 19:41:05 +000010193 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010194 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010195 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010196
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010197 // Convert the object parameter.
10198 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010199 ExprResult BaseResult =
10200 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10201 Best->FoundDecl, Method);
10202 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010203 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010204 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010205
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010206 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010207 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
10208 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010209 if (FnExpr.isInvalid())
10210 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010211
John McCall7decc9e2010-11-18 06:31:45 +000010212 QualType ResultTy = Method->getResultType();
10213 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10214 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010215 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010216 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010217 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010218
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010219 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010220 Method))
10221 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010222
10223 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010224}
10225
Douglas Gregorcd695e52008-11-10 20:40:00 +000010226/// FixOverloadedFunctionReference - E is an expression that refers to
10227/// a C++ overloaded function (possibly with some parentheses and
10228/// perhaps a '&' around it). We have resolved the overloaded function
10229/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000010230/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000010231Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000010232 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000010233 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010234 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10235 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010236 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010237 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010238
Douglas Gregor51c538b2009-11-20 19:42:02 +000010239 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010240 }
10241
Douglas Gregor51c538b2009-11-20 19:42:02 +000010242 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010243 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10244 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010245 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000010246 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000010247 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000010248 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000010249 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010250 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010251
10252 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000010253 ICE->getCastKind(),
10254 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000010255 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010256 }
10257
Douglas Gregor51c538b2009-11-20 19:42:02 +000010258 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000010259 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000010260 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010261 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10262 if (Method->isStatic()) {
10263 // Do nothing: static member functions aren't any different
10264 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000010265 } else {
John McCalle66edc12009-11-24 19:00:30 +000010266 // Fix the sub expression, which really has to be an
10267 // UnresolvedLookupExpr holding an overloaded member function
10268 // or template.
John McCall16df1e52010-03-30 21:47:33 +000010269 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10270 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000010271 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010272 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010273
John McCalld14a8642009-11-21 08:51:07 +000010274 assert(isa<DeclRefExpr>(SubExpr)
10275 && "fixed to something other than a decl ref");
10276 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10277 && "fixed to a member ref with no nested name qualifier");
10278
10279 // We have taken the address of a pointer to member
10280 // function. Perform the computation here so that we get the
10281 // appropriate pointer to member type.
10282 QualType ClassType
10283 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10284 QualType MemPtrType
10285 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10286
John McCall7decc9e2010-11-18 06:31:45 +000010287 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10288 VK_RValue, OK_Ordinary,
10289 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010290 }
10291 }
John McCall16df1e52010-03-30 21:47:33 +000010292 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10293 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010294 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010295 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010296
John McCalle3027922010-08-25 11:45:40 +000010297 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010298 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000010299 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010300 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010301 }
John McCalld14a8642009-11-21 08:51:07 +000010302
10303 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000010304 // FIXME: avoid copy.
10305 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000010306 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000010307 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10308 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000010309 }
10310
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010311 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10312 ULE->getQualifierLoc(),
10313 Fn,
10314 ULE->getNameLoc(),
10315 Fn->getType(),
10316 VK_LValue,
10317 Found.getDecl(),
10318 TemplateArgs);
10319 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10320 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000010321 }
10322
John McCall10eae182009-11-30 22:42:35 +000010323 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000010324 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000010325 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10326 if (MemExpr->hasExplicitTemplateArgs()) {
10327 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10328 TemplateArgs = &TemplateArgsBuffer;
10329 }
John McCall6b51f282009-11-23 01:53:49 +000010330
John McCall2d74de92009-12-01 22:10:20 +000010331 Expr *Base;
10332
John McCall7decc9e2010-11-18 06:31:45 +000010333 // If we're filling in a static method where we used to have an
10334 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000010335 if (MemExpr->isImplicitAccess()) {
10336 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010337 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10338 MemExpr->getQualifierLoc(),
10339 Fn,
10340 MemExpr->getMemberLoc(),
10341 Fn->getType(),
10342 VK_LValue,
10343 Found.getDecl(),
10344 TemplateArgs);
10345 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10346 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000010347 } else {
10348 SourceLocation Loc = MemExpr->getMemberLoc();
10349 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000010350 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +000010351 Base = new (Context) CXXThisExpr(Loc,
10352 MemExpr->getBaseType(),
10353 /*isImplicit=*/true);
10354 }
John McCall2d74de92009-12-01 22:10:20 +000010355 } else
John McCallc3007a22010-10-26 07:05:15 +000010356 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000010357
John McCall4adb38c2011-04-27 00:36:17 +000010358 ExprValueKind valueKind;
10359 QualType type;
10360 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10361 valueKind = VK_LValue;
10362 type = Fn->getType();
10363 } else {
10364 valueKind = VK_RValue;
10365 type = Context.BoundMemberTy;
10366 }
10367
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010368 MemberExpr *ME = MemberExpr::Create(Context, Base,
10369 MemExpr->isArrow(),
10370 MemExpr->getQualifierLoc(),
10371 Fn,
10372 Found,
10373 MemExpr->getMemberNameInfo(),
10374 TemplateArgs,
10375 type, valueKind, OK_Ordinary);
10376 ME->setHadMultipleCandidates(true);
10377 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010378 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010379
John McCallc3007a22010-10-26 07:05:15 +000010380 llvm_unreachable("Invalid reference to overloaded function");
10381 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010382}
10383
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010384ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000010385 DeclAccessPair Found,
10386 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000010387 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000010388}
10389
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010390} // end namespace clang