blob: adf4dcae1b0d902f133b598abd499b9fc2d66d48 [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
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002166/// FunctionArgTypesAreEqual - This routine checks two function proto types
2167/// for equlity of their argument types. Caller has already checked that
2168/// they have same number of arguments. This routine assumes that Objective-C
2169/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002170bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00002171 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002172 if (!getLangOptions().ObjC1)
2173 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2174 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002175
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002176 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2177 N = NewType->arg_type_begin(),
2178 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2179 QualType ToType = (*O);
2180 QualType FromType = (*N);
2181 if (ToType != FromType) {
2182 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2183 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002184 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2185 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2186 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2187 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002188 continue;
2189 }
John McCall8b07ec22010-05-15 11:32:37 +00002190 else if (const ObjCObjectPointerType *PTTo =
2191 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002192 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002193 FromType->getAs<ObjCObjectPointerType>())
2194 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2195 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002196 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002197 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002198 }
2199 }
2200 return true;
2201}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002202
Douglas Gregor39c16d42008-10-24 04:54:22 +00002203/// CheckPointerConversion - Check the pointer conversion from the
2204/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002205/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002206/// conversions for which IsPointerConversion has already returned
2207/// true. It returns true and produces a diagnostic if there was an
2208/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002209bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002210 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002211 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002212 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002213 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002214 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002215
John McCall8cb679e2010-11-15 09:13:47 +00002216 Kind = CK_BitCast;
2217
Chandler Carruthffab8732011-04-09 07:32:05 +00002218 if (!IsCStyleOrFunctionalCast &&
2219 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2220 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2221 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002222 PDiag(diag::warn_impcast_bool_to_null_pointer)
2223 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002224
John McCall9320b872011-09-09 05:25:32 +00002225 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2226 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002227 QualType FromPointeeType = FromPtrType->getPointeeType(),
2228 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002229
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002230 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2231 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002232 // We must have a derived-to-base conversion. Check an
2233 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002234 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2235 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002236 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002237 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002238 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002239
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002240 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002241 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002242 }
2243 }
John McCall9320b872011-09-09 05:25:32 +00002244 } else if (const ObjCObjectPointerType *ToPtrType =
2245 ToType->getAs<ObjCObjectPointerType>()) {
2246 if (const ObjCObjectPointerType *FromPtrType =
2247 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002248 // Objective-C++ conversions are always okay.
2249 // FIXME: We should have a different class of conversions for the
2250 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002251 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002252 return false;
John McCall9320b872011-09-09 05:25:32 +00002253 } else if (FromType->isBlockPointerType()) {
2254 Kind = CK_BlockPointerToObjCPointerCast;
2255 } else {
2256 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002257 }
John McCall9320b872011-09-09 05:25:32 +00002258 } else if (ToType->isBlockPointerType()) {
2259 if (!FromType->isBlockPointerType())
2260 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002261 }
John McCall8cb679e2010-11-15 09:13:47 +00002262
2263 // We shouldn't fall into this case unless it's valid for other
2264 // reasons.
2265 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2266 Kind = CK_NullToPointer;
2267
Douglas Gregor39c16d42008-10-24 04:54:22 +00002268 return false;
2269}
2270
Sebastian Redl72b597d2009-01-25 19:43:20 +00002271/// IsMemberPointerConversion - Determines whether the conversion of the
2272/// expression From, which has the (possibly adjusted) type FromType, can be
2273/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2274/// If so, returns true and places the converted type (that might differ from
2275/// ToType in its cv-qualifiers at some level) into ConvertedType.
2276bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002277 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002278 bool InOverloadResolution,
2279 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002280 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002281 if (!ToTypePtr)
2282 return false;
2283
2284 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002285 if (From->isNullPointerConstant(Context,
2286 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2287 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002288 ConvertedType = ToType;
2289 return true;
2290 }
2291
2292 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002293 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002294 if (!FromTypePtr)
2295 return false;
2296
2297 // A pointer to member of B can be converted to a pointer to member of D,
2298 // where D is derived from B (C++ 4.11p2).
2299 QualType FromClass(FromTypePtr->getClass(), 0);
2300 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002301
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002302 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2303 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2304 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002305 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2306 ToClass.getTypePtr());
2307 return true;
2308 }
2309
2310 return false;
2311}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002312
Sebastian Redl72b597d2009-01-25 19:43:20 +00002313/// CheckMemberPointerConversion - Check the member pointer conversion from the
2314/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002315/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002316/// for which IsMemberPointerConversion has already returned true. It returns
2317/// true and produces a diagnostic if there was an error, or returns false
2318/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002319bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002320 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002321 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002322 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002323 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002324 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002325 if (!FromPtrType) {
2326 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002327 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002328 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002329 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002330 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002331 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002332 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002333
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002334 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002335 assert(ToPtrType && "No member pointer cast has a target type "
2336 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002337
Sebastian Redled8f2002009-01-28 18:33:18 +00002338 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2339 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002340
Sebastian Redled8f2002009-01-28 18:33:18 +00002341 // FIXME: What about dependent types?
2342 assert(FromClass->isRecordType() && "Pointer into non-class.");
2343 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002344
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002345 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002346 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002347 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2348 assert(DerivationOkay &&
2349 "Should not have been called if derivation isn't OK.");
2350 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002351
Sebastian Redled8f2002009-01-28 18:33:18 +00002352 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2353 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002354 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2355 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2356 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2357 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002358 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002359
Douglas Gregor89ee6822009-02-28 01:32:25 +00002360 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002361 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2362 << FromClass << ToClass << QualType(VBase, 0)
2363 << From->getSourceRange();
2364 return true;
2365 }
2366
John McCall5b0829a2010-02-10 09:31:12 +00002367 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002368 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2369 Paths.front(),
2370 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002371
Anders Carlssond7923c62009-08-22 23:33:40 +00002372 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002373 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002374 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002375 return false;
2376}
2377
Douglas Gregor9a657932008-10-21 23:43:52 +00002378/// IsQualificationConversion - Determines whether the conversion from
2379/// an rvalue of type FromType to ToType is a qualification conversion
2380/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002381///
2382/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2383/// when the qualification conversion involves a change in the Objective-C
2384/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002385bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002386Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002387 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002388 FromType = Context.getCanonicalType(FromType);
2389 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002390 ObjCLifetimeConversion = false;
2391
Douglas Gregor9a657932008-10-21 23:43:52 +00002392 // If FromType and ToType are the same type, this is not a
2393 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002394 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002395 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002396
Douglas Gregor9a657932008-10-21 23:43:52 +00002397 // (C++ 4.4p4):
2398 // A conversion can add cv-qualifiers at levels other than the first
2399 // in multi-level pointers, subject to the following rules: [...]
2400 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002401 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002402 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002403 // Within each iteration of the loop, we check the qualifiers to
2404 // determine if this still looks like a qualification
2405 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002406 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002407 // until there are no more pointers or pointers-to-members left to
2408 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002409 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002410
Douglas Gregor90609aa2011-04-25 18:40:17 +00002411 Qualifiers FromQuals = FromType.getQualifiers();
2412 Qualifiers ToQuals = ToType.getQualifiers();
2413
John McCall31168b02011-06-15 23:02:42 +00002414 // Objective-C ARC:
2415 // Check Objective-C lifetime conversions.
2416 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2417 UnwrappedAnyPointer) {
2418 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2419 ObjCLifetimeConversion = true;
2420 FromQuals.removeObjCLifetime();
2421 ToQuals.removeObjCLifetime();
2422 } else {
2423 // Qualification conversions cannot cast between different
2424 // Objective-C lifetime qualifiers.
2425 return false;
2426 }
2427 }
2428
Douglas Gregorf30053d2011-05-08 06:09:53 +00002429 // Allow addition/removal of GC attributes but not changing GC attributes.
2430 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2431 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2432 FromQuals.removeObjCGCAttr();
2433 ToQuals.removeObjCGCAttr();
2434 }
2435
Douglas Gregor9a657932008-10-21 23:43:52 +00002436 // -- for every j > 0, if const is in cv 1,j then const is in cv
2437 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002438 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002439 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002440
Douglas Gregor9a657932008-10-21 23:43:52 +00002441 // -- if the cv 1,j and cv 2,j are different, then const is in
2442 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002443 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002444 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002445 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002446
Douglas Gregor9a657932008-10-21 23:43:52 +00002447 // Keep track of whether all prior cv-qualifiers in the "to" type
2448 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002449 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002450 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002451 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002452
2453 // We are left with FromType and ToType being the pointee types
2454 // after unwrapping the original FromType and ToType the same number
2455 // of types. If we unwrapped any pointers, and if FromType and
2456 // ToType have the same unqualified type (since we checked
2457 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002458 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002459}
2460
Douglas Gregor576e98c2009-01-30 23:27:23 +00002461/// Determines whether there is a user-defined conversion sequence
2462/// (C++ [over.ics.user]) that converts expression From to the type
2463/// ToType. If such a conversion exists, User will contain the
2464/// user-defined conversion sequence that performs such a conversion
2465/// and this routine will return true. Otherwise, this routine returns
2466/// false and User is unspecified.
2467///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002468/// \param AllowExplicit true if the conversion should consider C++0x
2469/// "explicit" conversion functions as well as non-explicit conversion
2470/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002471static OverloadingResult
2472IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2473 UserDefinedConversionSequence& User,
2474 OverloadCandidateSet& CandidateSet,
2475 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002476 // Whether we will only visit constructors.
2477 bool ConstructorsOnly = false;
2478
2479 // If the type we are conversion to is a class type, enumerate its
2480 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002481 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002482 // C++ [over.match.ctor]p1:
2483 // When objects of class type are direct-initialized (8.5), or
2484 // copy-initialized from an expression of the same or a
2485 // derived class type (8.5), overload resolution selects the
2486 // constructor. [...] For copy-initialization, the candidate
2487 // functions are all the converting constructors (12.3.1) of
2488 // that class. The argument list is the expression-list within
2489 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002490 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002491 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002492 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002493 ConstructorsOnly = true;
2494
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002495 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2496 // RequireCompleteType may have returned true due to some invalid decl
2497 // during template instantiation, but ToType may be complete enough now
2498 // to try to recover.
2499 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002500 // We're not going to find any constructors.
2501 } else if (CXXRecordDecl *ToRecordDecl
2502 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002503 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002504 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002505 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002506 NamedDecl *D = *Con;
2507 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2508
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002509 // Find the constructor (which may be a template).
2510 CXXConstructorDecl *Constructor = 0;
2511 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002512 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002513 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002514 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002515 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2516 else
John McCalla0296f72010-03-19 07:35:19 +00002517 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002518
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002519 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002520 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002521 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002522 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2523 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002524 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002525 /*SuppressUserConversions=*/
2526 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002527 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002528 // Allow one user-defined conversion when user specifies a
2529 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002530 S.AddOverloadCandidate(Constructor, FoundDecl,
2531 &From, 1, CandidateSet,
2532 /*SuppressUserConversions=*/
2533 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002534 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002535 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002536 }
2537 }
2538
Douglas Gregor5ab11652010-04-17 22:01:05 +00002539 // Enumerate conversion functions, if we're allowed to.
2540 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002541 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2542 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002543 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002544 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002545 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002546 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002547 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2548 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002549 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002550 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002551 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002552 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002553 DeclAccessPair FoundDecl = I.getPair();
2554 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002555 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2556 if (isa<UsingShadowDecl>(D))
2557 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2558
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002559 CXXConversionDecl *Conv;
2560 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002561 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2562 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002563 else
John McCallda4458e2010-03-31 01:36:47 +00002564 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002565
2566 if (AllowExplicit || !Conv->isExplicit()) {
2567 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002568 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2569 ActingContext, From, ToType,
2570 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002571 else
John McCall5c32be02010-08-24 20:38:10 +00002572 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2573 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002574 }
2575 }
2576 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002577 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002578
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002579 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2580
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002581 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002582 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002583 case OR_Success:
2584 // Record the standard conversion we used and the conversion function.
2585 if (CXXConstructorDecl *Constructor
2586 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002587 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2588
John McCall5c32be02010-08-24 20:38:10 +00002589 // C++ [over.ics.user]p1:
2590 // If the user-defined conversion is specified by a
2591 // constructor (12.3.1), the initial standard conversion
2592 // sequence converts the source type to the type required by
2593 // the argument of the constructor.
2594 //
2595 QualType ThisType = Constructor->getThisType(S.Context);
2596 if (Best->Conversions[0].isEllipsis())
2597 User.EllipsisConversion = true;
2598 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002599 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002600 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002601 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002602 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002603 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00002604 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002605 User.After.setAsIdentityConversion();
2606 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2607 User.After.setAllToTypes(ToType);
2608 return OR_Success;
2609 } else if (CXXConversionDecl *Conversion
2610 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002611 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2612
John McCall5c32be02010-08-24 20:38:10 +00002613 // C++ [over.ics.user]p1:
2614 //
2615 // [...] If the user-defined conversion is specified by a
2616 // conversion function (12.3.2), the initial standard
2617 // conversion sequence converts the source type to the
2618 // implicit object parameter of the conversion function.
2619 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002620 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002621 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00002622 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002623 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002624
John McCall5c32be02010-08-24 20:38:10 +00002625 // C++ [over.ics.user]p2:
2626 // The second standard conversion sequence converts the
2627 // result of the user-defined conversion to the target type
2628 // for the sequence. Since an implicit conversion sequence
2629 // is an initialization, the special rules for
2630 // initialization by user-defined conversion apply when
2631 // selecting the best user-defined conversion for a
2632 // user-defined conversion sequence (see 13.3.3 and
2633 // 13.3.3.1).
2634 User.After = Best->FinalConversion;
2635 return OR_Success;
2636 } else {
2637 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002638 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002639 }
2640
John McCall5c32be02010-08-24 20:38:10 +00002641 case OR_No_Viable_Function:
2642 return OR_No_Viable_Function;
2643 case OR_Deleted:
2644 // No conversion here! We're done.
2645 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002646
John McCall5c32be02010-08-24 20:38:10 +00002647 case OR_Ambiguous:
2648 return OR_Ambiguous;
2649 }
2650
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002651 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002652}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002653
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002654bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002655Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002656 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002657 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002658 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002659 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002660 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002661 if (OvResult == OR_Ambiguous)
2662 Diag(From->getSourceRange().getBegin(),
2663 diag::err_typecheck_ambiguous_condition)
2664 << From->getType() << ToType << From->getSourceRange();
2665 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2666 Diag(From->getSourceRange().getBegin(),
2667 diag::err_typecheck_nonviable_condition)
2668 << From->getType() << ToType << From->getSourceRange();
2669 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002670 return false;
John McCall5c32be02010-08-24 20:38:10 +00002671 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002672 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002673}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002674
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002675/// CompareImplicitConversionSequences - Compare two implicit
2676/// conversion sequences to determine whether one is better than the
2677/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002678static ImplicitConversionSequence::CompareKind
2679CompareImplicitConversionSequences(Sema &S,
2680 const ImplicitConversionSequence& ICS1,
2681 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002682{
2683 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2684 // conversion sequences (as defined in 13.3.3.1)
2685 // -- a standard conversion sequence (13.3.3.1.1) is a better
2686 // conversion sequence than a user-defined conversion sequence or
2687 // an ellipsis conversion sequence, and
2688 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2689 // conversion sequence than an ellipsis conversion sequence
2690 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002691 //
John McCall0d1da222010-01-12 00:44:57 +00002692 // C++0x [over.best.ics]p10:
2693 // For the purpose of ranking implicit conversion sequences as
2694 // described in 13.3.3.2, the ambiguous conversion sequence is
2695 // treated as a user-defined sequence that is indistinguishable
2696 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002697 if (ICS1.getKindRank() < ICS2.getKindRank())
2698 return ImplicitConversionSequence::Better;
2699 else if (ICS2.getKindRank() < ICS1.getKindRank())
2700 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002701
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002702 // The following checks require both conversion sequences to be of
2703 // the same kind.
2704 if (ICS1.getKind() != ICS2.getKind())
2705 return ImplicitConversionSequence::Indistinguishable;
2706
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002707 ImplicitConversionSequence::CompareKind Result =
2708 ImplicitConversionSequence::Indistinguishable;
2709
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002710 // Two implicit conversion sequences of the same form are
2711 // indistinguishable conversion sequences unless one of the
2712 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002713 if (ICS1.isStandard())
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002714 Result = CompareStandardConversionSequences(S,
2715 ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002716 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002717 // User-defined conversion sequence U1 is a better conversion
2718 // sequence than another user-defined conversion sequence U2 if
2719 // they contain the same user-defined conversion function or
2720 // constructor and if the second standard conversion sequence of
2721 // U1 is better than the second standard conversion sequence of
2722 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002723 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002724 ICS2.UserDefined.ConversionFunction)
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002725 Result = CompareStandardConversionSequences(S,
2726 ICS1.UserDefined.After,
2727 ICS2.UserDefined.After);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002728 }
2729
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00002730 // List-initialization sequence L1 is a better conversion sequence than
2731 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
2732 // for some X and L2 does not.
2733 if (Result == ImplicitConversionSequence::Indistinguishable &&
2734 ICS1.isListInitializationSequence() &&
2735 ICS2.isListInitializationSequence()) {
2736 // FIXME: Find out if ICS1 converts to initializer_list and ICS2 doesn't.
2737 }
2738
2739 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002740}
2741
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002742static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2743 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2744 Qualifiers Quals;
2745 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002746 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002747 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002748
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002749 return Context.hasSameUnqualifiedType(T1, T2);
2750}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002751
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002752// Per 13.3.3.2p3, compare the given standard conversion sequences to
2753// determine if one is a proper subset of the other.
2754static ImplicitConversionSequence::CompareKind
2755compareStandardConversionSubsets(ASTContext &Context,
2756 const StandardConversionSequence& SCS1,
2757 const StandardConversionSequence& SCS2) {
2758 ImplicitConversionSequence::CompareKind Result
2759 = ImplicitConversionSequence::Indistinguishable;
2760
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002761 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002762 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00002763 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2764 return ImplicitConversionSequence::Better;
2765 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2766 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002767
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002768 if (SCS1.Second != SCS2.Second) {
2769 if (SCS1.Second == ICK_Identity)
2770 Result = ImplicitConversionSequence::Better;
2771 else if (SCS2.Second == ICK_Identity)
2772 Result = ImplicitConversionSequence::Worse;
2773 else
2774 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002775 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002776 return ImplicitConversionSequence::Indistinguishable;
2777
2778 if (SCS1.Third == SCS2.Third) {
2779 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2780 : ImplicitConversionSequence::Indistinguishable;
2781 }
2782
2783 if (SCS1.Third == ICK_Identity)
2784 return Result == ImplicitConversionSequence::Worse
2785 ? ImplicitConversionSequence::Indistinguishable
2786 : ImplicitConversionSequence::Better;
2787
2788 if (SCS2.Third == ICK_Identity)
2789 return Result == ImplicitConversionSequence::Better
2790 ? ImplicitConversionSequence::Indistinguishable
2791 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002792
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002793 return ImplicitConversionSequence::Indistinguishable;
2794}
2795
Douglas Gregore696ebb2011-01-26 14:52:12 +00002796/// \brief Determine whether one of the given reference bindings is better
2797/// than the other based on what kind of bindings they are.
2798static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2799 const StandardConversionSequence &SCS2) {
2800 // C++0x [over.ics.rank]p3b4:
2801 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2802 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002803 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002804 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002805 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002806 // reference*.
2807 //
2808 // FIXME: Rvalue references. We're going rogue with the above edits,
2809 // because the semantics in the current C++0x working paper (N3225 at the
2810 // time of this writing) break the standard definition of std::forward
2811 // and std::reference_wrapper when dealing with references to functions.
2812 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002813 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2814 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2815 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002816
Douglas Gregore696ebb2011-01-26 14:52:12 +00002817 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2818 SCS2.IsLvalueReference) ||
2819 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2820 !SCS2.IsLvalueReference);
2821}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002822
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002823/// CompareStandardConversionSequences - Compare two standard
2824/// conversion sequences to determine whether one is better than the
2825/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002826static ImplicitConversionSequence::CompareKind
2827CompareStandardConversionSequences(Sema &S,
2828 const StandardConversionSequence& SCS1,
2829 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002830{
2831 // Standard conversion sequence S1 is a better conversion sequence
2832 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2833
2834 // -- S1 is a proper subsequence of S2 (comparing the conversion
2835 // sequences in the canonical form defined by 13.3.3.1.1,
2836 // excluding any Lvalue Transformation; the identity conversion
2837 // sequence is considered to be a subsequence of any
2838 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002839 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002840 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002841 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002842
2843 // -- the rank of S1 is better than the rank of S2 (by the rules
2844 // defined below), or, if not that,
2845 ImplicitConversionRank Rank1 = SCS1.getRank();
2846 ImplicitConversionRank Rank2 = SCS2.getRank();
2847 if (Rank1 < Rank2)
2848 return ImplicitConversionSequence::Better;
2849 else if (Rank2 < Rank1)
2850 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002851
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002852 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2853 // are indistinguishable unless one of the following rules
2854 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002855
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002856 // A conversion that is not a conversion of a pointer, or
2857 // pointer to member, to bool is better than another conversion
2858 // that is such a conversion.
2859 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2860 return SCS2.isPointerConversionToBool()
2861 ? ImplicitConversionSequence::Better
2862 : ImplicitConversionSequence::Worse;
2863
Douglas Gregor5c407d92008-10-23 00:40:37 +00002864 // C++ [over.ics.rank]p4b2:
2865 //
2866 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002867 // conversion of B* to A* is better than conversion of B* to
2868 // void*, and conversion of A* to void* is better than conversion
2869 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002870 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002871 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002872 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002873 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002874 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2875 // Exactly one of the conversion sequences is a conversion to
2876 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002877 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2878 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002879 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2880 // Neither conversion sequence converts to a void pointer; compare
2881 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002882 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002883 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002884 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002885 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2886 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002887 // Both conversion sequences are conversions to void
2888 // pointers. Compare the source types to determine if there's an
2889 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002890 QualType FromType1 = SCS1.getFromType();
2891 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002892
2893 // Adjust the types we're converting from via the array-to-pointer
2894 // conversion, if we need to.
2895 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002896 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002897 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002898 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002899
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002900 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2901 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002902
John McCall5c32be02010-08-24 20:38:10 +00002903 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002904 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002905 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002906 return ImplicitConversionSequence::Worse;
2907
2908 // Objective-C++: If one interface is more specific than the
2909 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002910 const ObjCObjectPointerType* FromObjCPtr1
2911 = FromType1->getAs<ObjCObjectPointerType>();
2912 const ObjCObjectPointerType* FromObjCPtr2
2913 = FromType2->getAs<ObjCObjectPointerType>();
2914 if (FromObjCPtr1 && FromObjCPtr2) {
2915 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2916 FromObjCPtr2);
2917 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2918 FromObjCPtr1);
2919 if (AssignLeft != AssignRight) {
2920 return AssignLeft? ImplicitConversionSequence::Better
2921 : ImplicitConversionSequence::Worse;
2922 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002923 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002924 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002925
2926 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2927 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002928 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002929 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002930 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002931
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002932 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002933 // Check for a better reference binding based on the kind of bindings.
2934 if (isBetterReferenceBindingKind(SCS1, SCS2))
2935 return ImplicitConversionSequence::Better;
2936 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2937 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002938
Sebastian Redlb28b4072009-03-22 23:49:27 +00002939 // C++ [over.ics.rank]p3b4:
2940 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2941 // which the references refer are the same type except for
2942 // top-level cv-qualifiers, and the type to which the reference
2943 // initialized by S2 refers is more cv-qualified than the type
2944 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002945 QualType T1 = SCS1.getToType(2);
2946 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002947 T1 = S.Context.getCanonicalType(T1);
2948 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002949 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002950 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2951 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002952 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00002953 // Objective-C++ ARC: If the references refer to objects with different
2954 // lifetimes, prefer bindings that don't change lifetime.
2955 if (SCS1.ObjCLifetimeConversionBinding !=
2956 SCS2.ObjCLifetimeConversionBinding) {
2957 return SCS1.ObjCLifetimeConversionBinding
2958 ? ImplicitConversionSequence::Worse
2959 : ImplicitConversionSequence::Better;
2960 }
2961
Chandler Carruth8e543b32010-12-12 08:17:55 +00002962 // If the type is an array type, promote the element qualifiers to the
2963 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002964 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002965 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002966 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002967 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002968 if (T2.isMoreQualifiedThan(T1))
2969 return ImplicitConversionSequence::Better;
2970 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00002971 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002972 }
2973 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002974
Francois Pichet08d2fa02011-09-18 21:37:37 +00002975 // In Microsoft mode, prefer an integral conversion to a
2976 // floating-to-integral conversion if the integral conversion
2977 // is between types of the same size.
2978 // For example:
2979 // void f(float);
2980 // void f(int);
2981 // int main {
2982 // long a;
2983 // f(a);
2984 // }
2985 // Here, MSVC will call f(int) instead of generating a compile error
2986 // as clang will do in standard mode.
2987 if (S.getLangOptions().MicrosoftMode &&
2988 SCS1.Second == ICK_Integral_Conversion &&
2989 SCS2.Second == ICK_Floating_Integral &&
2990 S.Context.getTypeSize(SCS1.getFromType()) ==
2991 S.Context.getTypeSize(SCS1.getToType(2)))
2992 return ImplicitConversionSequence::Better;
2993
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002994 return ImplicitConversionSequence::Indistinguishable;
2995}
2996
2997/// CompareQualificationConversions - Compares two standard conversion
2998/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002999/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3000ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003001CompareQualificationConversions(Sema &S,
3002 const StandardConversionSequence& SCS1,
3003 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00003004 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003005 // -- S1 and S2 differ only in their qualification conversion and
3006 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3007 // cv-qualification signature of type T1 is a proper subset of
3008 // the cv-qualification signature of type T2, and S1 is not the
3009 // deprecated string literal array-to-pointer conversion (4.2).
3010 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3011 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3012 return ImplicitConversionSequence::Indistinguishable;
3013
3014 // FIXME: the example in the standard doesn't use a qualification
3015 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003016 QualType T1 = SCS1.getToType(2);
3017 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003018 T1 = S.Context.getCanonicalType(T1);
3019 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003020 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003021 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3022 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003023
3024 // If the types are the same, we won't learn anything by unwrapped
3025 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003026 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003027 return ImplicitConversionSequence::Indistinguishable;
3028
Chandler Carruth607f38e2009-12-29 07:16:59 +00003029 // If the type is an array type, promote the element qualifiers to the type
3030 // for comparison.
3031 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003032 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003033 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003034 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003035
Mike Stump11289f42009-09-09 15:08:12 +00003036 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003037 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003038
3039 // Objective-C++ ARC:
3040 // Prefer qualification conversions not involving a change in lifetime
3041 // to qualification conversions that do not change lifetime.
3042 if (SCS1.QualificationIncludesObjCLifetime !=
3043 SCS2.QualificationIncludesObjCLifetime) {
3044 Result = SCS1.QualificationIncludesObjCLifetime
3045 ? ImplicitConversionSequence::Worse
3046 : ImplicitConversionSequence::Better;
3047 }
3048
John McCall5c32be02010-08-24 20:38:10 +00003049 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003050 // Within each iteration of the loop, we check the qualifiers to
3051 // determine if this still looks like a qualification
3052 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003053 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003054 // until there are no more pointers or pointers-to-members left
3055 // to unwrap. This essentially mimics what
3056 // IsQualificationConversion does, but here we're checking for a
3057 // strict subset of qualifiers.
3058 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3059 // The qualifiers are the same, so this doesn't tell us anything
3060 // about how the sequences rank.
3061 ;
3062 else if (T2.isMoreQualifiedThan(T1)) {
3063 // T1 has fewer qualifiers, so it could be the better sequence.
3064 if (Result == ImplicitConversionSequence::Worse)
3065 // Neither has qualifiers that are a subset of the other's
3066 // qualifiers.
3067 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003068
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003069 Result = ImplicitConversionSequence::Better;
3070 } else if (T1.isMoreQualifiedThan(T2)) {
3071 // T2 has fewer qualifiers, so it could be the better sequence.
3072 if (Result == ImplicitConversionSequence::Better)
3073 // Neither has qualifiers that are a subset of the other's
3074 // qualifiers.
3075 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003076
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003077 Result = ImplicitConversionSequence::Worse;
3078 } else {
3079 // Qualifiers are disjoint.
3080 return ImplicitConversionSequence::Indistinguishable;
3081 }
3082
3083 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003084 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003085 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003086 }
3087
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003088 // Check that the winning standard conversion sequence isn't using
3089 // the deprecated string literal array to pointer conversion.
3090 switch (Result) {
3091 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003092 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003093 Result = ImplicitConversionSequence::Indistinguishable;
3094 break;
3095
3096 case ImplicitConversionSequence::Indistinguishable:
3097 break;
3098
3099 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003100 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003101 Result = ImplicitConversionSequence::Indistinguishable;
3102 break;
3103 }
3104
3105 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003106}
3107
Douglas Gregor5c407d92008-10-23 00:40:37 +00003108/// CompareDerivedToBaseConversions - Compares two standard conversion
3109/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003110/// various kinds of derived-to-base conversions (C++
3111/// [over.ics.rank]p4b3). As part of these checks, we also look at
3112/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003113ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003114CompareDerivedToBaseConversions(Sema &S,
3115 const StandardConversionSequence& SCS1,
3116 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003117 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003118 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003119 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003120 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003121
3122 // Adjust the types we're converting from via the array-to-pointer
3123 // conversion, if we need to.
3124 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003125 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003126 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003127 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003128
3129 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003130 FromType1 = S.Context.getCanonicalType(FromType1);
3131 ToType1 = S.Context.getCanonicalType(ToType1);
3132 FromType2 = S.Context.getCanonicalType(FromType2);
3133 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003134
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003135 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003136 //
3137 // If class B is derived directly or indirectly from class A and
3138 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003139 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003140 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003141 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003142 SCS2.Second == ICK_Pointer_Conversion &&
3143 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3144 FromType1->isPointerType() && FromType2->isPointerType() &&
3145 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003146 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003147 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003148 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003149 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003150 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003151 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003152 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003153 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003154
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003155 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003156 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003157 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003158 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003159 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003160 return ImplicitConversionSequence::Worse;
3161 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003162
3163 // -- conversion of B* to A* is better than conversion of C* to A*,
3164 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003165 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003166 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003167 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003168 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003169 }
3170 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3171 SCS2.Second == ICK_Pointer_Conversion) {
3172 const ObjCObjectPointerType *FromPtr1
3173 = FromType1->getAs<ObjCObjectPointerType>();
3174 const ObjCObjectPointerType *FromPtr2
3175 = FromType2->getAs<ObjCObjectPointerType>();
3176 const ObjCObjectPointerType *ToPtr1
3177 = ToType1->getAs<ObjCObjectPointerType>();
3178 const ObjCObjectPointerType *ToPtr2
3179 = ToType2->getAs<ObjCObjectPointerType>();
3180
3181 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3182 // Apply the same conversion ranking rules for Objective-C pointer types
3183 // that we do for C++ pointers to class types. However, we employ the
3184 // Objective-C pseudo-subtyping relationship used for assignment of
3185 // Objective-C pointer types.
3186 bool FromAssignLeft
3187 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3188 bool FromAssignRight
3189 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3190 bool ToAssignLeft
3191 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3192 bool ToAssignRight
3193 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3194
3195 // A conversion to an a non-id object pointer type or qualified 'id'
3196 // type is better than a conversion to 'id'.
3197 if (ToPtr1->isObjCIdType() &&
3198 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3199 return ImplicitConversionSequence::Worse;
3200 if (ToPtr2->isObjCIdType() &&
3201 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3202 return ImplicitConversionSequence::Better;
3203
3204 // A conversion to a non-id object pointer type is better than a
3205 // conversion to a qualified 'id' type
3206 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3207 return ImplicitConversionSequence::Worse;
3208 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3209 return ImplicitConversionSequence::Better;
3210
3211 // A conversion to an a non-Class object pointer type or qualified 'Class'
3212 // type is better than a conversion to 'Class'.
3213 if (ToPtr1->isObjCClassType() &&
3214 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3215 return ImplicitConversionSequence::Worse;
3216 if (ToPtr2->isObjCClassType() &&
3217 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3218 return ImplicitConversionSequence::Better;
3219
3220 // A conversion to a non-Class object pointer type is better than a
3221 // conversion to a qualified 'Class' type.
3222 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3223 return ImplicitConversionSequence::Worse;
3224 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3225 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003226
Douglas Gregor058d3de2011-01-31 18:51:41 +00003227 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3228 if (S.Context.hasSameType(FromType1, FromType2) &&
3229 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3230 (ToAssignLeft != ToAssignRight))
3231 return ToAssignLeft? ImplicitConversionSequence::Worse
3232 : ImplicitConversionSequence::Better;
3233
3234 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3235 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3236 (FromAssignLeft != FromAssignRight))
3237 return FromAssignLeft? ImplicitConversionSequence::Better
3238 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003239 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003240 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003241
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003242 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003243 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3244 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3245 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003246 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003247 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003248 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003249 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003250 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003251 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003252 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003253 ToType2->getAs<MemberPointerType>();
3254 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3255 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3256 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3257 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3258 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3259 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3260 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3261 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003262 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003263 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003264 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003265 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003266 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003267 return ImplicitConversionSequence::Better;
3268 }
3269 // conversion of B::* to C::* is better than conversion of A::* to C::*
3270 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003271 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003272 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003273 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003274 return ImplicitConversionSequence::Worse;
3275 }
3276 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003277
Douglas Gregor5ab11652010-04-17 22:01:05 +00003278 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003279 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003280 // -- binding of an expression of type C to a reference of type
3281 // B& is better than binding an expression of type C to a
3282 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003283 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3284 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3285 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003286 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003287 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003288 return ImplicitConversionSequence::Worse;
3289 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003290
Douglas Gregor2fe98832008-11-03 19:09:14 +00003291 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003292 // -- binding of an expression of type B to a reference of type
3293 // A& is better than binding an expression of type C to a
3294 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003295 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3296 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3297 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003298 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003299 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003300 return ImplicitConversionSequence::Worse;
3301 }
3302 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003303
Douglas Gregor5c407d92008-10-23 00:40:37 +00003304 return ImplicitConversionSequence::Indistinguishable;
3305}
3306
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003307/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3308/// determine whether they are reference-related,
3309/// reference-compatible, reference-compatible with added
3310/// qualification, or incompatible, for use in C++ initialization by
3311/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3312/// type, and the first type (T1) is the pointee type of the reference
3313/// type being initialized.
3314Sema::ReferenceCompareResult
3315Sema::CompareReferenceRelationship(SourceLocation Loc,
3316 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003317 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003318 bool &ObjCConversion,
3319 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003320 assert(!OrigT1->isReferenceType() &&
3321 "T1 must be the pointee type of the reference type");
3322 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3323
3324 QualType T1 = Context.getCanonicalType(OrigT1);
3325 QualType T2 = Context.getCanonicalType(OrigT2);
3326 Qualifiers T1Quals, T2Quals;
3327 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3328 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3329
3330 // C++ [dcl.init.ref]p4:
3331 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3332 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3333 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003334 DerivedToBase = false;
3335 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003336 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003337 if (UnqualT1 == UnqualT2) {
3338 // Nothing to do.
3339 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003340 IsDerivedFrom(UnqualT2, UnqualT1))
3341 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003342 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3343 UnqualT2->isObjCObjectOrInterfaceType() &&
3344 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3345 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003346 else
3347 return Ref_Incompatible;
3348
3349 // At this point, we know that T1 and T2 are reference-related (at
3350 // least).
3351
3352 // If the type is an array type, promote the element qualifiers to the type
3353 // for comparison.
3354 if (isa<ArrayType>(T1) && T1Quals)
3355 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3356 if (isa<ArrayType>(T2) && T2Quals)
3357 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3358
3359 // C++ [dcl.init.ref]p4:
3360 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3361 // reference-related to T2 and cv1 is the same cv-qualification
3362 // as, or greater cv-qualification than, cv2. For purposes of
3363 // overload resolution, cases for which cv1 is greater
3364 // cv-qualification than cv2 are identified as
3365 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003366 //
3367 // Note that we also require equivalence of Objective-C GC and address-space
3368 // qualifiers when performing these computations, so that e.g., an int in
3369 // address space 1 is not reference-compatible with an int in address
3370 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003371 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3372 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3373 T1Quals.removeObjCLifetime();
3374 T2Quals.removeObjCLifetime();
3375 ObjCLifetimeConversion = true;
3376 }
3377
Douglas Gregord517d552011-04-28 17:56:11 +00003378 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003379 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003380 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003381 return Ref_Compatible_With_Added_Qualification;
3382 else
3383 return Ref_Related;
3384}
3385
Douglas Gregor836a7e82010-08-11 02:15:33 +00003386/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003387/// with DeclType. Return true if something definite is found.
3388static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003389FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3390 QualType DeclType, SourceLocation DeclLoc,
3391 Expr *Init, QualType T2, bool AllowRvalues,
3392 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003393 assert(T2->isRecordType() && "Can only find conversions of record types.");
3394 CXXRecordDecl *T2RecordDecl
3395 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3396
3397 OverloadCandidateSet CandidateSet(DeclLoc);
3398 const UnresolvedSetImpl *Conversions
3399 = T2RecordDecl->getVisibleConversionFunctions();
3400 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3401 E = Conversions->end(); I != E; ++I) {
3402 NamedDecl *D = *I;
3403 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3404 if (isa<UsingShadowDecl>(D))
3405 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3406
3407 FunctionTemplateDecl *ConvTemplate
3408 = dyn_cast<FunctionTemplateDecl>(D);
3409 CXXConversionDecl *Conv;
3410 if (ConvTemplate)
3411 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3412 else
3413 Conv = cast<CXXConversionDecl>(D);
3414
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003415 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003416 // explicit conversions, skip it.
3417 if (!AllowExplicit && Conv->isExplicit())
3418 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003419
Douglas Gregor836a7e82010-08-11 02:15:33 +00003420 if (AllowRvalues) {
3421 bool DerivedToBase = false;
3422 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003423 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003424
3425 // If we are initializing an rvalue reference, don't permit conversion
3426 // functions that return lvalues.
3427 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3428 const ReferenceType *RefType
3429 = Conv->getConversionType()->getAs<LValueReferenceType>();
3430 if (RefType && !RefType->getPointeeType()->isFunctionType())
3431 continue;
3432 }
3433
Douglas Gregor836a7e82010-08-11 02:15:33 +00003434 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003435 S.CompareReferenceRelationship(
3436 DeclLoc,
3437 Conv->getConversionType().getNonReferenceType()
3438 .getUnqualifiedType(),
3439 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003440 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003441 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003442 continue;
3443 } else {
3444 // If the conversion function doesn't return a reference type,
3445 // it can't be considered for this conversion. An rvalue reference
3446 // is only acceptable if its referencee is a function type.
3447
3448 const ReferenceType *RefType =
3449 Conv->getConversionType()->getAs<ReferenceType>();
3450 if (!RefType ||
3451 (!RefType->isLValueReferenceType() &&
3452 !RefType->getPointeeType()->isFunctionType()))
3453 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003454 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003455
Douglas Gregor836a7e82010-08-11 02:15:33 +00003456 if (ConvTemplate)
3457 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003458 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003459 else
3460 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003461 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003462 }
3463
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003464 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3465
Sebastian Redld92badf2010-06-30 18:13:39 +00003466 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003467 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003468 case OR_Success:
3469 // C++ [over.ics.ref]p1:
3470 //
3471 // [...] If the parameter binds directly to the result of
3472 // applying a conversion function to the argument
3473 // expression, the implicit conversion sequence is a
3474 // user-defined conversion sequence (13.3.3.1.2), with the
3475 // second standard conversion sequence either an identity
3476 // conversion or, if the conversion function returns an
3477 // entity of a type that is a derived class of the parameter
3478 // type, a derived-to-base Conversion.
3479 if (!Best->FinalConversion.DirectBinding)
3480 return false;
3481
Chandler Carruth30141632011-02-25 19:41:05 +00003482 if (Best->Function)
3483 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003484 ICS.setUserDefined();
3485 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3486 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003487 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003488 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003489 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003490 ICS.UserDefined.EllipsisConversion = false;
3491 assert(ICS.UserDefined.After.ReferenceBinding &&
3492 ICS.UserDefined.After.DirectBinding &&
3493 "Expected a direct reference binding!");
3494 return true;
3495
3496 case OR_Ambiguous:
3497 ICS.setAmbiguous();
3498 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3499 Cand != CandidateSet.end(); ++Cand)
3500 if (Cand->Viable)
3501 ICS.Ambiguous.addConversion(Cand->Function);
3502 return true;
3503
3504 case OR_No_Viable_Function:
3505 case OR_Deleted:
3506 // There was no suitable conversion, or we found a deleted
3507 // conversion; continue with other checks.
3508 return false;
3509 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003510
Eric Christopheraba9fb22010-06-30 18:36:32 +00003511 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003512}
3513
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003514/// \brief Compute an implicit conversion sequence for reference
3515/// initialization.
3516static ImplicitConversionSequence
3517TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3518 SourceLocation DeclLoc,
3519 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003520 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003521 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3522
3523 // Most paths end in a failed conversion.
3524 ImplicitConversionSequence ICS;
3525 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3526
3527 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3528 QualType T2 = Init->getType();
3529
3530 // If the initializer is the address of an overloaded function, try
3531 // to resolve the overloaded function. If all goes well, T2 is the
3532 // type of the resulting function.
3533 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3534 DeclAccessPair Found;
3535 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3536 false, Found))
3537 T2 = Fn->getType();
3538 }
3539
3540 // Compute some basic properties of the types and the initializer.
3541 bool isRValRef = DeclType->isRValueReferenceType();
3542 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003543 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003544 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003545 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003546 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003547 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003548 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003549
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003550
Sebastian Redld92badf2010-06-30 18:13:39 +00003551 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003552 // A reference to type "cv1 T1" is initialized by an expression
3553 // of type "cv2 T2" as follows:
3554
Sebastian Redld92badf2010-06-30 18:13:39 +00003555 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003556 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003557 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3558 // reference-compatible with "cv2 T2," or
3559 //
3560 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3561 if (InitCategory.isLValue() &&
3562 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003563 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003564 // When a parameter of reference type binds directly (8.5.3)
3565 // to an argument expression, the implicit conversion sequence
3566 // is the identity conversion, unless the argument expression
3567 // has a type that is a derived class of the parameter type,
3568 // in which case the implicit conversion sequence is a
3569 // derived-to-base Conversion (13.3.3.1).
3570 ICS.setStandard();
3571 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003572 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3573 : ObjCConversion? ICK_Compatible_Conversion
3574 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003575 ICS.Standard.Third = ICK_Identity;
3576 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3577 ICS.Standard.setToType(0, T2);
3578 ICS.Standard.setToType(1, T1);
3579 ICS.Standard.setToType(2, T1);
3580 ICS.Standard.ReferenceBinding = true;
3581 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003582 ICS.Standard.IsLvalueReference = !isRValRef;
3583 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3584 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003585 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003586 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003587 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003588
Sebastian Redld92badf2010-06-30 18:13:39 +00003589 // Nothing more to do: the inaccessibility/ambiguity check for
3590 // derived-to-base conversions is suppressed when we're
3591 // computing the implicit conversion sequence (C++
3592 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003593 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003594 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003595
Sebastian Redld92badf2010-06-30 18:13:39 +00003596 // -- has a class type (i.e., T2 is a class type), where T1 is
3597 // not reference-related to T2, and can be implicitly
3598 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3599 // is reference-compatible with "cv3 T3" 92) (this
3600 // conversion is selected by enumerating the applicable
3601 // conversion functions (13.3.1.6) and choosing the best
3602 // one through overload resolution (13.3)),
3603 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003604 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003605 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003606 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3607 Init, T2, /*AllowRvalues=*/false,
3608 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003609 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003610 }
3611 }
3612
Sebastian Redld92badf2010-06-30 18:13:39 +00003613 // -- Otherwise, the reference shall be an lvalue reference to a
3614 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003615 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003616 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003617 // We actually handle one oddity of C++ [over.ics.ref] at this
3618 // point, which is that, due to p2 (which short-circuits reference
3619 // binding by only attempting a simple conversion for non-direct
3620 // bindings) and p3's strange wording, we allow a const volatile
3621 // reference to bind to an rvalue. Hence the check for the presence
3622 // of "const" rather than checking for "const" being the only
3623 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003624 // This is also the point where rvalue references and lvalue inits no longer
3625 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003626 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003627 return ICS;
3628
Douglas Gregorf143cd52011-01-24 16:14:37 +00003629 // -- If the initializer expression
3630 //
3631 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003632 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003633 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3634 (InitCategory.isXValue() ||
3635 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3636 (InitCategory.isLValue() && T2->isFunctionType()))) {
3637 ICS.setStandard();
3638 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003639 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003640 : ObjCConversion? ICK_Compatible_Conversion
3641 : ICK_Identity;
3642 ICS.Standard.Third = ICK_Identity;
3643 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3644 ICS.Standard.setToType(0, T2);
3645 ICS.Standard.setToType(1, T1);
3646 ICS.Standard.setToType(2, T1);
3647 ICS.Standard.ReferenceBinding = true;
3648 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3649 // binding unless we're binding to a class prvalue.
3650 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3651 // allow the use of rvalue references in C++98/03 for the benefit of
3652 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003653 ICS.Standard.DirectBinding =
3654 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003655 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003656 ICS.Standard.IsLvalueReference = !isRValRef;
3657 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003658 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003659 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003660 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003661 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003662 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003663 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003664
Douglas Gregorf143cd52011-01-24 16:14:37 +00003665 // -- has a class type (i.e., T2 is a class type), where T1 is not
3666 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003667 // an xvalue, class prvalue, or function lvalue of type
3668 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003669 // "cv3 T3",
3670 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003671 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003672 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003673 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003674 // class subobject).
3675 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003676 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003677 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3678 Init, T2, /*AllowRvalues=*/true,
3679 AllowExplicit)) {
3680 // In the second case, if the reference is an rvalue reference
3681 // and the second standard conversion sequence of the
3682 // user-defined conversion sequence includes an lvalue-to-rvalue
3683 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003684 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003685 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3686 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3687
Douglas Gregor95273c32011-01-21 16:36:05 +00003688 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003689 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003690
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003691 // -- Otherwise, a temporary of type "cv1 T1" is created and
3692 // initialized from the initializer expression using the
3693 // rules for a non-reference copy initialization (8.5). The
3694 // reference is then bound to the temporary. If T1 is
3695 // reference-related to T2, cv1 must be the same
3696 // cv-qualification as, or greater cv-qualification than,
3697 // cv2; otherwise, the program is ill-formed.
3698 if (RefRelationship == Sema::Ref_Related) {
3699 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3700 // we would be reference-compatible or reference-compatible with
3701 // added qualification. But that wasn't the case, so the reference
3702 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00003703 //
3704 // Note that we only want to check address spaces and cvr-qualifiers here.
3705 // ObjC GC and lifetime qualifiers aren't important.
3706 Qualifiers T1Quals = T1.getQualifiers();
3707 Qualifiers T2Quals = T2.getQualifiers();
3708 T1Quals.removeObjCGCAttr();
3709 T1Quals.removeObjCLifetime();
3710 T2Quals.removeObjCGCAttr();
3711 T2Quals.removeObjCLifetime();
3712 if (!T1Quals.compatiblyIncludes(T2Quals))
3713 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003714 }
3715
3716 // If at least one of the types is a class type, the types are not
3717 // related, and we aren't allowed any user conversions, the
3718 // reference binding fails. This case is important for breaking
3719 // recursion, since TryImplicitConversion below will attempt to
3720 // create a temporary through the use of a copy constructor.
3721 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3722 (T1->isRecordType() || T2->isRecordType()))
3723 return ICS;
3724
Douglas Gregorcba72b12011-01-21 05:18:22 +00003725 // If T1 is reference-related to T2 and the reference is an rvalue
3726 // reference, the initializer expression shall not be an lvalue.
3727 if (RefRelationship >= Sema::Ref_Related &&
3728 isRValRef && Init->Classify(S.Context).isLValue())
3729 return ICS;
3730
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003731 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003732 // When a parameter of reference type is not bound directly to
3733 // an argument expression, the conversion sequence is the one
3734 // required to convert the argument expression to the
3735 // underlying type of the reference according to
3736 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3737 // to copy-initializing a temporary of the underlying type with
3738 // the argument expression. Any difference in top-level
3739 // cv-qualification is subsumed by the initialization itself
3740 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003741 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3742 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003743 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003744 /*CStyle=*/false,
3745 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003746
3747 // Of course, that's still a reference binding.
3748 if (ICS.isStandard()) {
3749 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003750 ICS.Standard.IsLvalueReference = !isRValRef;
3751 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3752 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003753 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003754 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003755 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003756 // Don't allow rvalue references to bind to lvalues.
3757 if (DeclType->isRValueReferenceType()) {
3758 if (const ReferenceType *RefType
3759 = ICS.UserDefined.ConversionFunction->getResultType()
3760 ->getAs<LValueReferenceType>()) {
3761 if (!RefType->getPointeeType()->isFunctionType()) {
3762 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
3763 DeclType);
3764 return ICS;
3765 }
3766 }
3767 }
3768
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003769 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00003770 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3771 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3772 ICS.UserDefined.After.BindsToRvalue = true;
3773 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3774 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003775 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003776
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003777 return ICS;
3778}
3779
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003780static ImplicitConversionSequence
3781TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
3782 bool SuppressUserConversions,
3783 bool InOverloadResolution,
3784 bool AllowObjCWritebackConversion);
3785
3786/// TryListConversion - Try to copy-initialize a value of type ToType from the
3787/// initializer list From.
3788static ImplicitConversionSequence
3789TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
3790 bool SuppressUserConversions,
3791 bool InOverloadResolution,
3792 bool AllowObjCWritebackConversion) {
3793 // C++11 [over.ics.list]p1:
3794 // When an argument is an initializer list, it is not an expression and
3795 // special rules apply for converting it to a parameter type.
3796
3797 ImplicitConversionSequence Result;
3798 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003799 Result.setListInitializationSequence();
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003800
3801 // C++11 [over.ics.list]p2:
3802 // If the parameter type is std::initializer_list<X> or "array of X" and
3803 // all the elements can be implicitly converted to X, the implicit
3804 // conversion sequence is the worst conversion necessary to convert an
3805 // element of the list to X.
3806 // FIXME: Recognize std::initializer_list.
3807 // FIXME: Arrays don't make sense until we can deal with references.
3808 if (ToType->isArrayType())
3809 return Result;
3810
3811 // C++11 [over.ics.list]p3:
3812 // Otherwise, if the parameter is a non-aggregate class X and overload
3813 // resolution chooses a single best constructor [...] the implicit
3814 // conversion sequence is a user-defined conversion sequence. If multiple
3815 // constructors are viable but none is better than the others, the
3816 // implicit conversion sequence is a user-defined conversion sequence.
3817 // FIXME: Implement this.
3818 if (ToType->isRecordType() && !ToType->isAggregateType())
3819 return Result;
3820
3821 // C++11 [over.ics.list]p4:
3822 // Otherwise, if the parameter has an aggregate type which can be
3823 // initialized from the initializer list [...] the implicit conversion
3824 // sequence is a user-defined conversion sequence.
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003825 if (ToType->isAggregateType()) {
Sebastian Redl72ef7bc2011-11-01 15:53:09 +00003826 // Type is an aggregate, argument is an init list. At this point it comes
3827 // down to checking whether the initialization works.
3828 // FIXME: Find out whether this parameter is consumed or not.
3829 InitializedEntity Entity =
3830 InitializedEntity::InitializeParameter(S.Context, ToType,
3831 /*Consumed=*/false);
3832 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
3833 Result.setUserDefined();
3834 Result.UserDefined.Before.setAsIdentityConversion();
3835 // Initializer lists don't have a type.
3836 Result.UserDefined.Before.setFromType(QualType());
3837 Result.UserDefined.Before.setAllToTypes(QualType());
3838
3839 Result.UserDefined.After.setAsIdentityConversion();
3840 Result.UserDefined.After.setFromType(ToType);
3841 Result.UserDefined.After.setAllToTypes(ToType);
3842 }
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003843 return Result;
3844 }
3845
3846 // C++11 [over.ics.list]p5:
3847 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
3848 // FIXME: Implement this.
3849 if (ToType->isReferenceType())
3850 return Result;
3851
3852 // C++11 [over.ics.list]p6:
3853 // Otherwise, if the parameter type is not a class:
3854 if (!ToType->isRecordType()) {
3855 // - if the initializer list has one element, the implicit conversion
3856 // sequence is the one required to convert the element to the
3857 // parameter type.
3858 // FIXME: Catch narrowing here?
3859 unsigned NumInits = From->getNumInits();
3860 if (NumInits == 1)
3861 Result = TryCopyInitialization(S, From->getInit(0), ToType,
3862 SuppressUserConversions,
3863 InOverloadResolution,
3864 AllowObjCWritebackConversion);
3865 // - if the initializer list has no elements, the implicit conversion
3866 // sequence is the identity conversion.
3867 else if (NumInits == 0) {
3868 Result.setStandard();
3869 Result.Standard.setAsIdentityConversion();
3870 }
3871 return Result;
3872 }
3873
3874 // C++11 [over.ics.list]p7:
3875 // In all cases other than those enumerated above, no conversion is possible
3876 return Result;
3877}
3878
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003879/// TryCopyInitialization - Try to copy-initialize a value of type
3880/// ToType from the expression From. Return the implicit conversion
3881/// sequence required to pass this argument, which may be a bad
3882/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003883/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003884/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003885static ImplicitConversionSequence
3886TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003887 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00003888 bool InOverloadResolution,
3889 bool AllowObjCWritebackConversion) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003890 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
3891 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
3892 InOverloadResolution,AllowObjCWritebackConversion);
3893
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003894 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003895 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003896 /*FIXME:*/From->getLocStart(),
3897 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003898 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003899
John McCall5c32be02010-08-24 20:38:10 +00003900 return TryImplicitConversion(S, From, ToType,
3901 SuppressUserConversions,
3902 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003903 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00003904 /*CStyle=*/false,
3905 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003906}
3907
Anna Zaks1b068122011-07-28 19:46:48 +00003908static bool TryCopyInitialization(const CanQualType FromQTy,
3909 const CanQualType ToQTy,
3910 Sema &S,
3911 SourceLocation Loc,
3912 ExprValueKind FromVK) {
3913 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
3914 ImplicitConversionSequence ICS =
3915 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
3916
3917 return !ICS.isBad();
3918}
3919
Douglas Gregor436424c2008-11-18 23:14:02 +00003920/// TryObjectArgumentInitialization - Try to initialize the object
3921/// parameter of the given member function (@c Method) from the
3922/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003923static ImplicitConversionSequence
3924TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003925 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003926 CXXMethodDecl *Method,
3927 CXXRecordDecl *ActingContext) {
3928 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003929 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3930 // const volatile object.
3931 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3932 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003933 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003934
3935 // Set up the conversion sequence as a "bad" conversion, to allow us
3936 // to exit early.
3937 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003938
3939 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003940 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003941 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003942 FromType = PT->getPointeeType();
3943
Douglas Gregor02824322011-01-26 19:30:28 +00003944 // When we had a pointer, it's implicitly dereferenced, so we
3945 // better have an lvalue.
3946 assert(FromClassification.isLValue());
3947 }
3948
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003949 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003950
Douglas Gregor02824322011-01-26 19:30:28 +00003951 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003952 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003953 // parameter is
3954 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003955 // - "lvalue reference to cv X" for functions declared without a
3956 // ref-qualifier or with the & ref-qualifier
3957 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003958 // ref-qualifier
3959 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003960 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003961 // cv-qualification on the member function declaration.
3962 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003963 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003964 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003965 // (C++ [over.match.funcs]p5). We perform a simplified version of
3966 // reference binding here, that allows class rvalues to bind to
3967 // non-constant references.
3968
Douglas Gregor02824322011-01-26 19:30:28 +00003969 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003970 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003971 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003972 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003973 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003974 ICS.setBad(BadConversionSequence::bad_qualifiers,
3975 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003976 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003977 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003978
3979 // Check that we have either the same type or a derived type. It
3980 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003981 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003982 ImplicitConversionKind SecondKind;
3983 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3984 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003985 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003986 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003987 else {
John McCall65eb8792010-02-25 01:37:24 +00003988 ICS.setBad(BadConversionSequence::unrelated_class,
3989 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003990 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003991 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003992
Douglas Gregor02824322011-01-26 19:30:28 +00003993 // Check the ref-qualifier.
3994 switch (Method->getRefQualifier()) {
3995 case RQ_None:
3996 // Do nothing; we don't care about lvalueness or rvalueness.
3997 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003998
Douglas Gregor02824322011-01-26 19:30:28 +00003999 case RQ_LValue:
4000 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4001 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004002 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004003 ImplicitParamType);
4004 return ICS;
4005 }
4006 break;
4007
4008 case RQ_RValue:
4009 if (!FromClassification.isRValue()) {
4010 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004011 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00004012 ImplicitParamType);
4013 return ICS;
4014 }
4015 break;
4016 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004017
Douglas Gregor436424c2008-11-18 23:14:02 +00004018 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00004019 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00004020 ICS.Standard.setAsIdentityConversion();
4021 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00004022 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004023 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00004024 ICS.Standard.ReferenceBinding = true;
4025 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004026 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004027 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004028 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4029 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4030 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004031 return ICS;
4032}
4033
4034/// PerformObjectArgumentInitialization - Perform initialization of
4035/// the implicit object parameter for the given Method with the given
4036/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004037ExprResult
4038Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004039 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004040 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004041 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004042 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004043 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004044 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004045
Douglas Gregor02824322011-01-26 19:30:28 +00004046 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004047 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004048 FromRecordType = PT->getPointeeType();
4049 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004050 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004051 } else {
4052 FromRecordType = From->getType();
4053 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004054 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004055 }
4056
John McCall6e9f8f62009-12-03 04:06:58 +00004057 // Note that we always use the true parent context when performing
4058 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004059 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004060 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4061 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004062 if (ICS.isBad()) {
4063 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4064 Qualifiers FromQs = FromRecordType.getQualifiers();
4065 Qualifiers ToQs = DestType.getQualifiers();
4066 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4067 if (CVR) {
4068 Diag(From->getSourceRange().getBegin(),
4069 diag::err_member_function_call_bad_cvr)
4070 << Method->getDeclName() << FromRecordType << (CVR - 1)
4071 << From->getSourceRange();
4072 Diag(Method->getLocation(), diag::note_previous_decl)
4073 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004074 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004075 }
4076 }
4077
Douglas Gregor436424c2008-11-18 23:14:02 +00004078 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004079 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004080 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004081 }
Mike Stump11289f42009-09-09 15:08:12 +00004082
John Wiegley01296292011-04-08 18:41:53 +00004083 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4084 ExprResult FromRes =
4085 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4086 if (FromRes.isInvalid())
4087 return ExprError();
4088 From = FromRes.take();
4089 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004090
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004091 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004092 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smith4a905b62011-11-10 23:32:36 +00004093 From->getValueKind()).take();
John Wiegley01296292011-04-08 18:41:53 +00004094 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004095}
4096
Douglas Gregor5fb53972009-01-14 15:45:31 +00004097/// TryContextuallyConvertToBool - Attempt to contextually convert the
4098/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004099static ImplicitConversionSequence
4100TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004101 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004102 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004103 // FIXME: Are these flags correct?
4104 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004105 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004106 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004107 /*CStyle=*/false,
4108 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004109}
4110
4111/// PerformContextuallyConvertToBool - Perform a contextual conversion
4112/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004113ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004114 if (checkPlaceholderForOverload(*this, From))
4115 return ExprError();
4116
John McCall5c32be02010-08-24 20:38:10 +00004117 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004118 if (!ICS.isBad())
4119 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004120
Fariborz Jahanian76197412009-11-18 18:26:29 +00004121 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00004122 return Diag(From->getSourceRange().getBegin(),
4123 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004124 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004125 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004126}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004127
John McCallfec112d2011-09-09 06:11:02 +00004128/// dropPointerConversions - If the given standard conversion sequence
4129/// involves any pointer conversions, remove them. This may change
4130/// the result type of the conversion sequence.
4131static void dropPointerConversion(StandardConversionSequence &SCS) {
4132 if (SCS.Second == ICK_Pointer_Conversion) {
4133 SCS.Second = ICK_Identity;
4134 SCS.Third = ICK_Identity;
4135 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4136 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004137}
John McCall5c32be02010-08-24 20:38:10 +00004138
John McCallfec112d2011-09-09 06:11:02 +00004139/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4140/// convert the expression From to an Objective-C pointer type.
4141static ImplicitConversionSequence
4142TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4143 // Do an implicit conversion to 'id'.
4144 QualType Ty = S.Context.getObjCIdType();
4145 ImplicitConversionSequence ICS
4146 = TryImplicitConversion(S, From, Ty,
4147 // FIXME: Are these flags correct?
4148 /*SuppressUserConversions=*/false,
4149 /*AllowExplicit=*/true,
4150 /*InOverloadResolution=*/false,
4151 /*CStyle=*/false,
4152 /*AllowObjCWritebackConversion=*/false);
4153
4154 // Strip off any final conversions to 'id'.
4155 switch (ICS.getKind()) {
4156 case ImplicitConversionSequence::BadConversion:
4157 case ImplicitConversionSequence::AmbiguousConversion:
4158 case ImplicitConversionSequence::EllipsisConversion:
4159 break;
4160
4161 case ImplicitConversionSequence::UserDefinedConversion:
4162 dropPointerConversion(ICS.UserDefined.After);
4163 break;
4164
4165 case ImplicitConversionSequence::StandardConversion:
4166 dropPointerConversion(ICS.Standard);
4167 break;
4168 }
4169
4170 return ICS;
4171}
4172
4173/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4174/// conversion of the expression From to an Objective-C pointer type.
4175ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall526ab472011-10-25 17:37:35 +00004176 if (checkPlaceholderForOverload(*this, From))
4177 return ExprError();
4178
John McCall8b07ec22010-05-15 11:32:37 +00004179 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004180 ImplicitConversionSequence ICS =
4181 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004182 if (!ICS.isBad())
4183 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004184 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004185}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004186
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004187/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004188/// enumeration type.
4189///
4190/// This routine will attempt to convert an expression of class type to an
4191/// integral or enumeration type, if that class type only has a single
4192/// conversion to an integral or enumeration type.
4193///
Douglas Gregor4799d032010-06-30 00:20:43 +00004194/// \param Loc The source location of the construct that requires the
4195/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004196///
Douglas Gregor4799d032010-06-30 00:20:43 +00004197/// \param FromE The expression we're converting from.
4198///
4199/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4200/// have integral or enumeration type.
4201///
4202/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4203/// incomplete class type.
4204///
4205/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4206/// explicit conversion function (because no implicit conversion functions
4207/// were available). This is a recovery mode.
4208///
4209/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4210/// showing which conversion was picked.
4211///
4212/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4213/// conversion function that could convert to integral or enumeration type.
4214///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004215/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004216/// usable conversion function.
4217///
4218/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4219/// function, which may be an extension in this case.
4220///
4221/// \returns The expression, converted to an integral or enumeration type if
4222/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004223ExprResult
John McCallb268a282010-08-23 23:25:46 +00004224Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004225 const PartialDiagnostic &NotIntDiag,
4226 const PartialDiagnostic &IncompleteDiag,
4227 const PartialDiagnostic &ExplicitConvDiag,
4228 const PartialDiagnostic &ExplicitConvNote,
4229 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004230 const PartialDiagnostic &AmbigNote,
4231 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004232 // We can't perform any more checking for type-dependent expressions.
4233 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004234 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004235
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004236 // If the expression already has integral or enumeration type, we're golden.
4237 QualType T = From->getType();
4238 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00004239 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004240
4241 // FIXME: Check for missing '()' if T is a function type?
4242
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004243 // 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 +00004244 // expression of integral or enumeration type.
4245 const RecordType *RecordTy = T->getAs<RecordType>();
4246 if (!RecordTy || !getLangOptions().CPlusPlus) {
4247 Diag(Loc, NotIntDiag)
4248 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004249 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004250 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004251
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004252 // We must have a complete class type.
4253 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004254 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004255
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004256 // Look for a conversion to an integral or enumeration type.
4257 UnresolvedSet<4> ViableConversions;
4258 UnresolvedSet<4> ExplicitConversions;
4259 const UnresolvedSetImpl *Conversions
4260 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004261
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004262 bool HadMultipleCandidates = (Conversions->size() > 1);
4263
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004264 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004265 E = Conversions->end();
4266 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004267 ++I) {
4268 if (CXXConversionDecl *Conversion
4269 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4270 if (Conversion->getConversionType().getNonReferenceType()
4271 ->isIntegralOrEnumerationType()) {
4272 if (Conversion->isExplicit())
4273 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4274 else
4275 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4276 }
4277 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004278
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004279 switch (ViableConversions.size()) {
4280 case 0:
4281 if (ExplicitConversions.size() == 1) {
4282 DeclAccessPair Found = ExplicitConversions[0];
4283 CXXConversionDecl *Conversion
4284 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004285
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004286 // The user probably meant to invoke the given explicit
4287 // conversion; use it.
4288 QualType ConvTy
4289 = Conversion->getConversionType().getNonReferenceType();
4290 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00004291 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004292
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004293 Diag(Loc, ExplicitConvDiag)
4294 << T << ConvTy
4295 << FixItHint::CreateInsertion(From->getLocStart(),
4296 "static_cast<" + TypeStr + ">(")
4297 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4298 ")");
4299 Diag(Conversion->getLocation(), ExplicitConvNote)
4300 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004301
4302 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004303 // explicit conversion function.
4304 if (isSFINAEContext())
4305 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004306
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004307 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004308 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4309 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004310 if (Result.isInvalid())
4311 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004312 // Record usage of conversion in an implicit cast.
4313 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4314 CK_UserDefinedConversion,
4315 Result.get(), 0,
4316 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004317 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004318
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004319 // We'll complain below about a non-integral condition type.
4320 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004321
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004322 case 1: {
4323 // Apply this conversion.
4324 DeclAccessPair Found = ViableConversions[0];
4325 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004326
Douglas Gregor4799d032010-06-30 00:20:43 +00004327 CXXConversionDecl *Conversion
4328 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4329 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004330 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004331 if (ConvDiag.getDiagID()) {
4332 if (isSFINAEContext())
4333 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004334
Douglas Gregor4799d032010-06-30 00:20:43 +00004335 Diag(Loc, ConvDiag)
4336 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4337 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004338
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004339 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4340 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004341 if (Result.isInvalid())
4342 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00004343 // Record usage of conversion in an implicit cast.
4344 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4345 CK_UserDefinedConversion,
4346 Result.get(), 0,
4347 Result.get()->getValueKind());
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004348 break;
4349 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004350
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004351 default:
4352 Diag(Loc, AmbigDiag)
4353 << T << From->getSourceRange();
4354 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4355 CXXConversionDecl *Conv
4356 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4357 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4358 Diag(Conv->getLocation(), AmbigNote)
4359 << ConvTy->isEnumeralType() << ConvTy;
4360 }
John McCallb268a282010-08-23 23:25:46 +00004361 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004362 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004363
Douglas Gregor5823da32010-06-29 23:25:20 +00004364 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004365 Diag(Loc, NotIntDiag)
4366 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004367
John McCallb268a282010-08-23 23:25:46 +00004368 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004369}
4370
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004371/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004372/// candidate functions, using the given function call arguments. If
4373/// @p SuppressUserConversions, then don't allow user-defined
4374/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004375///
4376/// \para PartialOverloading true if we are performing "partial" overloading
4377/// based on an incomplete set of function arguments. This feature is used by
4378/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004379void
4380Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004381 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004382 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004383 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004384 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004385 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004386 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004387 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004388 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004389 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004390 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004391
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004392 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004393 if (!isa<CXXConstructorDecl>(Method)) {
4394 // If we get here, it's because we're calling a member function
4395 // that is named without a member access expression (e.g.,
4396 // "this->f") that was either written explicitly or created
4397 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004398 // function, e.g., X::f(). We use an empty type for the implied
4399 // object argument (C++ [over.call.func]p3), and the acting context
4400 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004401 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004402 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004403 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004404 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004405 return;
4406 }
4407 // We treat a constructor like a non-member function, since its object
4408 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004409 }
4410
Douglas Gregorff7028a2009-11-13 23:59:09 +00004411 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004412 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004413
Douglas Gregor27381f32009-11-23 12:27:39 +00004414 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004415 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004416
Douglas Gregorffe14e32009-11-14 01:20:54 +00004417 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4418 // C++ [class.copy]p3:
4419 // A member function template is never instantiated to perform the copy
4420 // of a class object to an object of its class type.
4421 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004422 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004423 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004424 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4425 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004426 return;
4427 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004428
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004429 // Add this candidate
4430 CandidateSet.push_back(OverloadCandidate());
4431 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004432 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004433 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004434 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004435 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004436 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004437 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004438
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004439 unsigned NumArgsInProto = Proto->getNumArgs();
4440
4441 // (C++ 13.3.2p2): A candidate function having fewer than m
4442 // parameters is viable only if it has an ellipsis in its parameter
4443 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004444 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004445 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004446 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004447 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004448 return;
4449 }
4450
4451 // (C++ 13.3.2p2): A candidate function having more than m parameters
4452 // is viable only if the (m+1)st parameter has a default argument
4453 // (8.3.6). For the purposes of overload resolution, the
4454 // parameter list is truncated on the right, so that there are
4455 // exactly m parameters.
4456 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004457 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004458 // Not enough arguments.
4459 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004460 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004461 return;
4462 }
4463
Peter Collingbourne7277fe82011-10-02 23:49:40 +00004464 // (CUDA B.1): Check for invalid calls between targets.
4465 if (getLangOptions().CUDA)
4466 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4467 if (CheckCUDATarget(Caller, Function)) {
4468 Candidate.Viable = false;
4469 Candidate.FailureKind = ovl_fail_bad_target;
4470 return;
4471 }
4472
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004473 // Determine the implicit conversion sequences for each of the
4474 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004475 Candidate.Conversions.resize(NumArgs);
4476 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4477 if (ArgIdx < NumArgsInProto) {
4478 // (C++ 13.3.2p3): for F to be a viable function, there shall
4479 // exist for each argument an implicit conversion sequence
4480 // (13.3.3.1) that converts that argument to the corresponding
4481 // parameter of F.
4482 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004483 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004484 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004485 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004486 /*InOverloadResolution=*/true,
4487 /*AllowObjCWritebackConversion=*/
4488 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004489 if (Candidate.Conversions[ArgIdx].isBad()) {
4490 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004491 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004492 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004493 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004494 } else {
4495 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4496 // argument for which there is no corresponding parameter is
4497 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004498 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004499 }
4500 }
4501}
4502
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004503/// \brief Add all of the function declarations in the given function set to
4504/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004505void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004506 Expr **Args, unsigned NumArgs,
4507 OverloadCandidateSet& CandidateSet,
4508 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004509 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004510 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4511 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004512 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004513 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004514 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004515 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004516 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004517 CandidateSet, SuppressUserConversions);
4518 else
John McCalla0296f72010-03-19 07:35:19 +00004519 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004520 SuppressUserConversions);
4521 } else {
John McCalla0296f72010-03-19 07:35:19 +00004522 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004523 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4524 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004525 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004526 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004527 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004528 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004529 Args[0]->Classify(Context),
4530 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004531 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004532 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004533 else
John McCalla0296f72010-03-19 07:35:19 +00004534 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004535 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004536 Args, NumArgs, CandidateSet,
4537 SuppressUserConversions);
4538 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004539 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004540}
4541
John McCallf0f1cf02009-11-17 07:50:12 +00004542/// AddMethodCandidate - Adds a named decl (which is some kind of
4543/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004544void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004545 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004546 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004547 Expr **Args, unsigned NumArgs,
4548 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004549 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004550 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004551 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004552
4553 if (isa<UsingShadowDecl>(Decl))
4554 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004555
John McCallf0f1cf02009-11-17 07:50:12 +00004556 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4557 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4558 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004559 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4560 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004561 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004562 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004563 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004564 } else {
John McCalla0296f72010-03-19 07:35:19 +00004565 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004566 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004567 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004568 }
4569}
4570
Douglas Gregor436424c2008-11-18 23:14:02 +00004571/// AddMethodCandidate - Adds the given C++ member function to the set
4572/// of candidate functions, using the given function call arguments
4573/// and the object argument (@c Object). For example, in a call
4574/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4575/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4576/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004577/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004578void
John McCalla0296f72010-03-19 07:35:19 +00004579Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004580 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004581 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004582 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004583 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004584 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004585 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004586 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004587 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004588 assert(!isa<CXXConstructorDecl>(Method) &&
4589 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004590
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004591 if (!CandidateSet.isNewCandidate(Method))
4592 return;
4593
Douglas Gregor27381f32009-11-23 12:27:39 +00004594 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004595 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004596
Douglas Gregor436424c2008-11-18 23:14:02 +00004597 // Add this candidate
4598 CandidateSet.push_back(OverloadCandidate());
4599 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004600 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004601 Candidate.Function = Method;
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;
Douglas Gregor436424c2008-11-18 23:14:02 +00004605
4606 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).
4611 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4612 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004613 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004614 return;
4615 }
4616
4617 // (C++ 13.3.2p2): A candidate function having more than m parameters
4618 // is viable only if the (m+1)st parameter has a default argument
4619 // (8.3.6). For the purposes of overload resolution, the
4620 // parameter list is truncated on the right, so that there are
4621 // exactly m parameters.
4622 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4623 if (NumArgs < MinRequiredArgs) {
4624 // Not enough arguments.
4625 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004626 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004627 return;
4628 }
4629
4630 Candidate.Viable = true;
4631 Candidate.Conversions.resize(NumArgs + 1);
4632
John McCall6e9f8f62009-12-03 04:06:58 +00004633 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004634 // The implicit object argument is ignored.
4635 Candidate.IgnoreObjectArgument = true;
4636 else {
4637 // Determine the implicit conversion sequence for the object
4638 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004639 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004640 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4641 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004642 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004643 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004644 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004645 return;
4646 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004647 }
4648
4649 // Determine the implicit conversion sequences for each of the
4650 // arguments.
4651 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4652 if (ArgIdx < NumArgsInProto) {
4653 // (C++ 13.3.2p3): for F to be a viable function, there shall
4654 // exist for each argument an implicit conversion sequence
4655 // (13.3.3.1) that converts that argument to the corresponding
4656 // parameter of F.
4657 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004658 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004659 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004660 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004661 /*InOverloadResolution=*/true,
4662 /*AllowObjCWritebackConversion=*/
4663 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004664 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004665 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004666 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004667 break;
4668 }
4669 } else {
4670 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4671 // argument for which there is no corresponding parameter is
4672 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004673 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004674 }
4675 }
4676}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004677
Douglas Gregor97628d62009-08-21 00:16:32 +00004678/// \brief Add a C++ member function template as a candidate to the candidate
4679/// set, using template argument deduction to produce an appropriate member
4680/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004681void
Douglas Gregor97628d62009-08-21 00:16:32 +00004682Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004683 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004684 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004685 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004686 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004687 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004688 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004689 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004690 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004691 if (!CandidateSet.isNewCandidate(MethodTmpl))
4692 return;
4693
Douglas Gregor97628d62009-08-21 00:16:32 +00004694 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004695 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004696 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004697 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004698 // candidate functions in the usual way.113) A given name can refer to one
4699 // or more function templates and also to a set of overloaded non-template
4700 // functions. In such a case, the candidate functions generated from each
4701 // function template are combined with the set of non-template candidate
4702 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004703 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004704 FunctionDecl *Specialization = 0;
4705 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004706 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004707 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004708 CandidateSet.push_back(OverloadCandidate());
4709 OverloadCandidate &Candidate = CandidateSet.back();
4710 Candidate.FoundDecl = FoundDecl;
4711 Candidate.Function = MethodTmpl->getTemplatedDecl();
4712 Candidate.Viable = false;
4713 Candidate.FailureKind = ovl_fail_bad_deduction;
4714 Candidate.IsSurrogate = false;
4715 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004716 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004717 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004718 Info);
4719 return;
4720 }
Mike Stump11289f42009-09-09 15:08:12 +00004721
Douglas Gregor97628d62009-08-21 00:16:32 +00004722 // Add the function template specialization produced by template argument
4723 // deduction as a candidate.
4724 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004725 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004726 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004727 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004728 ActingContext, ObjectType, ObjectClassification,
4729 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004730}
4731
Douglas Gregor05155d82009-08-21 23:19:43 +00004732/// \brief Add a C++ function template specialization as a candidate
4733/// in the candidate set, using template argument deduction to produce
4734/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004735void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004736Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004737 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004738 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004739 Expr **Args, unsigned NumArgs,
4740 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004741 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004742 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4743 return;
4744
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004745 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004746 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004747 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004748 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004749 // candidate functions in the usual way.113) A given name can refer to one
4750 // or more function templates and also to a set of overloaded non-template
4751 // functions. In such a case, the candidate functions generated from each
4752 // function template are combined with the set of non-template candidate
4753 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004754 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004755 FunctionDecl *Specialization = 0;
4756 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004757 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004758 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004759 CandidateSet.push_back(OverloadCandidate());
4760 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004761 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004762 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4763 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004764 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004765 Candidate.IsSurrogate = false;
4766 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004767 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004768 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004769 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004770 return;
4771 }
Mike Stump11289f42009-09-09 15:08:12 +00004772
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004773 // Add the function template specialization produced by template argument
4774 // deduction as a candidate.
4775 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004776 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004777 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004778}
Mike Stump11289f42009-09-09 15:08:12 +00004779
Douglas Gregora1f013e2008-11-07 22:36:19 +00004780/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004781/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004782/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004783/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004784/// (which may or may not be the same type as the type that the
4785/// conversion function produces).
4786void
4787Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004788 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004789 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004790 Expr *From, QualType ToType,
4791 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004792 assert(!Conversion->getDescribedFunctionTemplate() &&
4793 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004794 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004795 if (!CandidateSet.isNewCandidate(Conversion))
4796 return;
4797
Douglas Gregor27381f32009-11-23 12:27:39 +00004798 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004799 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004800
Douglas Gregora1f013e2008-11-07 22:36:19 +00004801 // Add this candidate
4802 CandidateSet.push_back(OverloadCandidate());
4803 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004804 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004805 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004806 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004807 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004808 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004809 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004810 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004811 Candidate.Viable = true;
4812 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004813 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004814
Douglas Gregor6affc782010-08-19 15:37:02 +00004815 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004816 // For conversion functions, the function is considered to be a member of
4817 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004818 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004819 //
4820 // Determine the implicit conversion sequence for the implicit
4821 // object parameter.
4822 QualType ImplicitParamType = From->getType();
4823 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4824 ImplicitParamType = FromPtrType->getPointeeType();
4825 CXXRecordDecl *ConversionContext
4826 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004827
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004828 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004829 = TryObjectArgumentInitialization(*this, From->getType(),
4830 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004831 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004832
John McCall0d1da222010-01-12 00:44:57 +00004833 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004834 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004835 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004836 return;
4837 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004838
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004839 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004840 // derived to base as such conversions are given Conversion Rank. They only
4841 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4842 QualType FromCanon
4843 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4844 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4845 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4846 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004847 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004848 return;
4849 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004850
Douglas Gregora1f013e2008-11-07 22:36:19 +00004851 // To determine what the conversion from the result of calling the
4852 // conversion function to the type we're eventually trying to
4853 // convert to (ToType), we need to synthesize a call to the
4854 // conversion function and attempt copy initialization from it. This
4855 // makes sure that we get the right semantics with respect to
4856 // lvalues/rvalues and the type. Fortunately, we can allocate this
4857 // call on the stack and we don't need its arguments to be
4858 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004859 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004860 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004861 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4862 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004863 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004864 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004865
Richard Smith48d24642011-07-13 22:53:21 +00004866 QualType ConversionType = Conversion->getConversionType();
4867 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004868 Candidate.Viable = false;
4869 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4870 return;
4871 }
4872
Richard Smith48d24642011-07-13 22:53:21 +00004873 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00004874
Mike Stump11289f42009-09-09 15:08:12 +00004875 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004876 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4877 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00004878 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004879 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004880 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004881 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004882 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004883 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00004884 /*InOverloadResolution=*/false,
4885 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004886
John McCall0d1da222010-01-12 00:44:57 +00004887 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004888 case ImplicitConversionSequence::StandardConversion:
4889 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004890
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004891 // C++ [over.ics.user]p3:
4892 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004893 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004894 // shall have exact match rank.
4895 if (Conversion->getPrimaryTemplate() &&
4896 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4897 Candidate.Viable = false;
4898 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4899 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004900
Douglas Gregorcba72b12011-01-21 05:18:22 +00004901 // C++0x [dcl.init.ref]p5:
4902 // In the second case, if the reference is an rvalue reference and
4903 // the second standard conversion sequence of the user-defined
4904 // conversion sequence includes an lvalue-to-rvalue conversion, the
4905 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004906 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004907 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4908 Candidate.Viable = false;
4909 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4910 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004911 break;
4912
4913 case ImplicitConversionSequence::BadConversion:
4914 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004915 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004916 break;
4917
4918 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004919 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00004920 "Can only end up with a standard conversion sequence or failure");
4921 }
4922}
4923
Douglas Gregor05155d82009-08-21 23:19:43 +00004924/// \brief Adds a conversion function template specialization
4925/// candidate to the overload set, using template argument deduction
4926/// to deduce the template arguments of the conversion function
4927/// template from the type that we are converting to (C++
4928/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004929void
Douglas Gregor05155d82009-08-21 23:19:43 +00004930Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004931 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004932 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004933 Expr *From, QualType ToType,
4934 OverloadCandidateSet &CandidateSet) {
4935 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4936 "Only conversion function templates permitted here");
4937
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004938 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4939 return;
4940
John McCallbc077cf2010-02-08 23:07:23 +00004941 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004942 CXXConversionDecl *Specialization = 0;
4943 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004944 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004945 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004946 CandidateSet.push_back(OverloadCandidate());
4947 OverloadCandidate &Candidate = CandidateSet.back();
4948 Candidate.FoundDecl = FoundDecl;
4949 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4950 Candidate.Viable = false;
4951 Candidate.FailureKind = ovl_fail_bad_deduction;
4952 Candidate.IsSurrogate = false;
4953 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004954 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004955 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004956 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004957 return;
4958 }
Mike Stump11289f42009-09-09 15:08:12 +00004959
Douglas Gregor05155d82009-08-21 23:19:43 +00004960 // Add the conversion function template specialization produced by
4961 // template argument deduction as a candidate.
4962 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004963 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004964 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004965}
4966
Douglas Gregorab7897a2008-11-19 22:57:39 +00004967/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4968/// converts the given @c Object to a function pointer via the
4969/// conversion function @c Conversion, and then attempts to call it
4970/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4971/// the type of function that we'll eventually be calling.
4972void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004973 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004974 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004975 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004976 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004977 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004978 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004979 if (!CandidateSet.isNewCandidate(Conversion))
4980 return;
4981
Douglas Gregor27381f32009-11-23 12:27:39 +00004982 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004983 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004984
Douglas Gregorab7897a2008-11-19 22:57:39 +00004985 CandidateSet.push_back(OverloadCandidate());
4986 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004987 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004988 Candidate.Function = 0;
4989 Candidate.Surrogate = Conversion;
4990 Candidate.Viable = true;
4991 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004992 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004993 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004994 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004995
4996 // Determine the implicit conversion sequence for the implicit
4997 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004998 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004999 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00005000 Object->Classify(Context),
5001 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00005002 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005003 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005004 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00005005 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005006 return;
5007 }
5008
5009 // The first conversion is actually a user-defined conversion whose
5010 // first conversion is ObjectInit's standard conversion (which is
5011 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00005012 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005013 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00005014 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00005015 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005016 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00005017 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00005018 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00005019 = Candidate.Conversions[0].UserDefined.Before;
5020 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5021
Mike Stump11289f42009-09-09 15:08:12 +00005022 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00005023 unsigned NumArgsInProto = Proto->getNumArgs();
5024
5025 // (C++ 13.3.2p2): A candidate function having fewer than m
5026 // parameters is viable only if it has an ellipsis in its parameter
5027 // list (8.3.5).
5028 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5029 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005030 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005031 return;
5032 }
5033
5034 // Function types don't have any default arguments, so just check if
5035 // we have enough arguments.
5036 if (NumArgs < NumArgsInProto) {
5037 // Not enough arguments.
5038 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005039 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005040 return;
5041 }
5042
5043 // Determine the implicit conversion sequences for each of the
5044 // arguments.
5045 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5046 if (ArgIdx < NumArgsInProto) {
5047 // (C++ 13.3.2p3): for F to be a viable function, there shall
5048 // exist for each argument an implicit conversion sequence
5049 // (13.3.3.1) that converts that argument to the corresponding
5050 // parameter of F.
5051 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005052 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005053 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005054 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005055 /*InOverloadResolution=*/false,
5056 /*AllowObjCWritebackConversion=*/
5057 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005058 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005059 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005060 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005061 break;
5062 }
5063 } else {
5064 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5065 // argument for which there is no corresponding parameter is
5066 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005067 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005068 }
5069 }
5070}
5071
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005072/// \brief Add overload candidates for overloaded operators that are
5073/// member functions.
5074///
5075/// Add the overloaded operator candidates that are member functions
5076/// for the operator Op that was used in an operator expression such
5077/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5078/// CandidateSet will store the added overload candidates. (C++
5079/// [over.match.oper]).
5080void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5081 SourceLocation OpLoc,
5082 Expr **Args, unsigned NumArgs,
5083 OverloadCandidateSet& CandidateSet,
5084 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005085 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5086
5087 // C++ [over.match.oper]p3:
5088 // For a unary operator @ with an operand of a type whose
5089 // cv-unqualified version is T1, and for a binary operator @ with
5090 // a left operand of a type whose cv-unqualified version is T1 and
5091 // a right operand of a type whose cv-unqualified version is T2,
5092 // three sets of candidate functions, designated member
5093 // candidates, non-member candidates and built-in candidates, are
5094 // constructed as follows:
5095 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005096
5097 // -- If T1 is a class type, the set of member candidates is the
5098 // result of the qualified lookup of T1::operator@
5099 // (13.3.1.1.1); otherwise, the set of member candidates is
5100 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005101 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005102 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005103 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005104 return;
Mike Stump11289f42009-09-09 15:08:12 +00005105
John McCall27b18f82009-11-17 02:14:36 +00005106 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5107 LookupQualifiedName(Operators, T1Rec->getDecl());
5108 Operators.suppressDiagnostics();
5109
Mike Stump11289f42009-09-09 15:08:12 +00005110 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005111 OperEnd = Operators.end();
5112 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005113 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005114 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005115 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005116 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005117 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005118 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005119}
5120
Douglas Gregora11693b2008-11-12 17:17:38 +00005121/// AddBuiltinCandidate - Add a candidate for a built-in
5122/// operator. ResultTy and ParamTys are the result and parameter types
5123/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005124/// arguments being passed to the candidate. IsAssignmentOperator
5125/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005126/// operator. NumContextualBoolArguments is the number of arguments
5127/// (at the beginning of the argument list) that will be contextually
5128/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005129void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005130 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005131 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005132 bool IsAssignmentOperator,
5133 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005134 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005135 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005136
Douglas Gregora11693b2008-11-12 17:17:38 +00005137 // Add this candidate
5138 CandidateSet.push_back(OverloadCandidate());
5139 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00005140 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005141 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005142 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005143 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005144 Candidate.BuiltinTypes.ResultTy = ResultTy;
5145 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5146 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5147
5148 // Determine the implicit conversion sequences for each of the
5149 // arguments.
5150 Candidate.Viable = true;
5151 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00005152 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005153 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005154 // C++ [over.match.oper]p4:
5155 // For the built-in assignment operators, conversions of the
5156 // left operand are restricted as follows:
5157 // -- no temporaries are introduced to hold the left operand, and
5158 // -- no user-defined conversions are applied to the left
5159 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005160 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005161 //
5162 // We block these conversions by turning off user-defined
5163 // conversions, since that is the only way that initialization of
5164 // a reference to a non-class type can occur from something that
5165 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005166 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005167 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005168 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005169 Candidate.Conversions[ArgIdx]
5170 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005171 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005172 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005173 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005174 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005175 /*InOverloadResolution=*/false,
5176 /*AllowObjCWritebackConversion=*/
5177 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005178 }
John McCall0d1da222010-01-12 00:44:57 +00005179 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005180 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005181 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005182 break;
5183 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005184 }
5185}
5186
5187/// BuiltinCandidateTypeSet - A set of types that will be used for the
5188/// candidate operator functions for built-in operators (C++
5189/// [over.built]). The types are separated into pointer types and
5190/// enumeration types.
5191class BuiltinCandidateTypeSet {
5192 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005193 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005194
5195 /// PointerTypes - The set of pointer types that will be used in the
5196 /// built-in candidates.
5197 TypeSet PointerTypes;
5198
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005199 /// MemberPointerTypes - The set of member pointer types that will be
5200 /// used in the built-in candidates.
5201 TypeSet MemberPointerTypes;
5202
Douglas Gregora11693b2008-11-12 17:17:38 +00005203 /// EnumerationTypes - The set of enumeration types that will be
5204 /// used in the built-in candidates.
5205 TypeSet EnumerationTypes;
5206
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005207 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005208 /// candidates.
5209 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005210
5211 /// \brief A flag indicating non-record types are viable candidates
5212 bool HasNonRecordTypes;
5213
5214 /// \brief A flag indicating whether either arithmetic or enumeration types
5215 /// were present in the candidate set.
5216 bool HasArithmeticOrEnumeralTypes;
5217
Douglas Gregor80af3132011-05-21 23:15:46 +00005218 /// \brief A flag indicating whether the nullptr type was present in the
5219 /// candidate set.
5220 bool HasNullPtrType;
5221
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005222 /// Sema - The semantic analysis instance where we are building the
5223 /// candidate type set.
5224 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005225
Douglas Gregora11693b2008-11-12 17:17:38 +00005226 /// Context - The AST context in which we will build the type sets.
5227 ASTContext &Context;
5228
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005229 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5230 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005231 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005232
5233public:
5234 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005235 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005236
Mike Stump11289f42009-09-09 15:08:12 +00005237 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005238 : HasNonRecordTypes(false),
5239 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005240 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005241 SemaRef(SemaRef),
5242 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005243
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005244 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005245 SourceLocation Loc,
5246 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005247 bool AllowExplicitConversions,
5248 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005249
5250 /// pointer_begin - First pointer type found;
5251 iterator pointer_begin() { return PointerTypes.begin(); }
5252
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005253 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005254 iterator pointer_end() { return PointerTypes.end(); }
5255
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005256 /// member_pointer_begin - First member pointer type found;
5257 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5258
5259 /// member_pointer_end - Past the last member pointer type found;
5260 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5261
Douglas Gregora11693b2008-11-12 17:17:38 +00005262 /// enumeration_begin - First enumeration type found;
5263 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5264
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005265 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005266 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005267
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005268 iterator vector_begin() { return VectorTypes.begin(); }
5269 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005270
5271 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5272 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005273 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005274};
5275
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005276/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005277/// the set of pointer types along with any more-qualified variants of
5278/// that type. For example, if @p Ty is "int const *", this routine
5279/// will add "int const *", "int const volatile *", "int const
5280/// restrict *", and "int const volatile restrict *" to the set of
5281/// pointer types. Returns true if the add of @p Ty itself succeeded,
5282/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005283///
5284/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005285bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005286BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5287 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00005288
Douglas Gregora11693b2008-11-12 17:17:38 +00005289 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005290 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00005291 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005292
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005293 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00005294 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005295 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005296 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005297 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005298 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005299 buildObjCPtr = true;
5300 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005301 else
David Blaikie83d382b2011-09-23 05:06:16 +00005302 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005303 }
5304 else
5305 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005306
Sebastian Redl4990a632009-11-18 20:39:26 +00005307 // Don't add qualified variants of arrays. For one, they're not allowed
5308 // (the qualifier would sink to the element type), and for another, the
5309 // only overload situation where it matters is subscript or pointer +- int,
5310 // and those shouldn't have qualifier variants anyway.
5311 if (PointeeTy->isArrayType())
5312 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005313 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005314 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005315 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005316 bool hasVolatile = VisibleQuals.hasVolatile();
5317 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005318
John McCall8ccfcb52009-09-24 19:53:00 +00005319 // Iterate through all strict supersets of BaseCVR.
5320 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5321 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005322 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5323 // in the types.
5324 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5325 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005326 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005327 if (!buildObjCPtr)
5328 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5329 else
5330 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005331 }
5332
5333 return true;
5334}
5335
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005336/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5337/// to the set of pointer types along with any more-qualified variants of
5338/// that type. For example, if @p Ty is "int const *", this routine
5339/// will add "int const *", "int const volatile *", "int const
5340/// restrict *", and "int const volatile restrict *" to the set of
5341/// pointer types. Returns true if the add of @p Ty itself succeeded,
5342/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005343///
5344/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005345bool
5346BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5347 QualType Ty) {
5348 // Insert this type.
5349 if (!MemberPointerTypes.insert(Ty))
5350 return false;
5351
John McCall8ccfcb52009-09-24 19:53:00 +00005352 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5353 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005354
John McCall8ccfcb52009-09-24 19:53:00 +00005355 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005356 // Don't add qualified variants of arrays. For one, they're not allowed
5357 // (the qualifier would sink to the element type), and for another, the
5358 // only overload situation where it matters is subscript or pointer +- int,
5359 // and those shouldn't have qualifier variants anyway.
5360 if (PointeeTy->isArrayType())
5361 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005362 const Type *ClassTy = PointerTy->getClass();
5363
5364 // Iterate through all strict supersets of the pointee type's CVR
5365 // qualifiers.
5366 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5367 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5368 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005369
John McCall8ccfcb52009-09-24 19:53:00 +00005370 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005371 MemberPointerTypes.insert(
5372 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005373 }
5374
5375 return true;
5376}
5377
Douglas Gregora11693b2008-11-12 17:17:38 +00005378/// AddTypesConvertedFrom - Add each of the types to which the type @p
5379/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005380/// primarily interested in pointer types and enumeration types. We also
5381/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005382/// AllowUserConversions is true if we should look at the conversion
5383/// functions of a class type, and AllowExplicitConversions if we
5384/// should also include the explicit conversion functions of a class
5385/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005386void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005387BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005388 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005389 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005390 bool AllowExplicitConversions,
5391 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005392 // Only deal with canonical types.
5393 Ty = Context.getCanonicalType(Ty);
5394
5395 // Look through reference types; they aren't part of the type of an
5396 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005397 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005398 Ty = RefTy->getPointeeType();
5399
John McCall33ddac02011-01-19 10:06:00 +00005400 // If we're dealing with an array type, decay to the pointer.
5401 if (Ty->isArrayType())
5402 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5403
5404 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005405 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005406
Chandler Carruth00a38332010-12-13 01:44:01 +00005407 // Flag if we ever add a non-record type.
5408 const RecordType *TyRec = Ty->getAs<RecordType>();
5409 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5410
Chandler Carruth00a38332010-12-13 01:44:01 +00005411 // Flag if we encounter an arithmetic type.
5412 HasArithmeticOrEnumeralTypes =
5413 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5414
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005415 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5416 PointerTypes.insert(Ty);
5417 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005418 // Insert our type, and its more-qualified variants, into the set
5419 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005420 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005421 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005422 } else if (Ty->isMemberPointerType()) {
5423 // Member pointers are far easier, since the pointee can't be converted.
5424 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5425 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005426 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005427 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005428 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005429 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005430 // We treat vector types as arithmetic types in many contexts as an
5431 // extension.
5432 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005433 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005434 } else if (Ty->isNullPtrType()) {
5435 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005436 } else if (AllowUserConversions && TyRec) {
5437 // No conversion functions in incomplete types.
5438 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5439 return;
Mike Stump11289f42009-09-09 15:08:12 +00005440
Chandler Carruth00a38332010-12-13 01:44:01 +00005441 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5442 const UnresolvedSetImpl *Conversions
5443 = ClassDecl->getVisibleConversionFunctions();
5444 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5445 E = Conversions->end(); I != E; ++I) {
5446 NamedDecl *D = I.getDecl();
5447 if (isa<UsingShadowDecl>(D))
5448 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005449
Chandler Carruth00a38332010-12-13 01:44:01 +00005450 // Skip conversion function templates; they don't tell us anything
5451 // about which builtin types we can convert to.
5452 if (isa<FunctionTemplateDecl>(D))
5453 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005454
Chandler Carruth00a38332010-12-13 01:44:01 +00005455 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5456 if (AllowExplicitConversions || !Conv->isExplicit()) {
5457 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5458 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005459 }
5460 }
5461 }
5462}
5463
Douglas Gregor84605ae2009-08-24 13:43:27 +00005464/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5465/// the volatile- and non-volatile-qualified assignment operators for the
5466/// given type to the candidate set.
5467static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5468 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005469 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005470 unsigned NumArgs,
5471 OverloadCandidateSet &CandidateSet) {
5472 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005473
Douglas Gregor84605ae2009-08-24 13:43:27 +00005474 // T& operator=(T&, T)
5475 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5476 ParamTypes[1] = T;
5477 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5478 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005479
Douglas Gregor84605ae2009-08-24 13:43:27 +00005480 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5481 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005482 ParamTypes[0]
5483 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005484 ParamTypes[1] = T;
5485 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005486 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005487 }
5488}
Mike Stump11289f42009-09-09 15:08:12 +00005489
Sebastian Redl1054fae2009-10-25 17:03:50 +00005490/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5491/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005492static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5493 Qualifiers VRQuals;
5494 const RecordType *TyRec;
5495 if (const MemberPointerType *RHSMPType =
5496 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005497 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005498 else
5499 TyRec = ArgExpr->getType()->getAs<RecordType>();
5500 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005501 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005502 VRQuals.addVolatile();
5503 VRQuals.addRestrict();
5504 return VRQuals;
5505 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005506
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005507 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005508 if (!ClassDecl->hasDefinition())
5509 return VRQuals;
5510
John McCallad371252010-01-20 00:46:10 +00005511 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005512 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005513
John McCallad371252010-01-20 00:46:10 +00005514 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005515 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005516 NamedDecl *D = I.getDecl();
5517 if (isa<UsingShadowDecl>(D))
5518 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5519 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005520 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5521 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5522 CanTy = ResTypeRef->getPointeeType();
5523 // Need to go down the pointer/mempointer chain and add qualifiers
5524 // as see them.
5525 bool done = false;
5526 while (!done) {
5527 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5528 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005529 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005530 CanTy->getAs<MemberPointerType>())
5531 CanTy = ResTypeMPtr->getPointeeType();
5532 else
5533 done = true;
5534 if (CanTy.isVolatileQualified())
5535 VRQuals.addVolatile();
5536 if (CanTy.isRestrictQualified())
5537 VRQuals.addRestrict();
5538 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5539 return VRQuals;
5540 }
5541 }
5542 }
5543 return VRQuals;
5544}
John McCall52872982010-11-13 05:51:15 +00005545
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005546namespace {
John McCall52872982010-11-13 05:51:15 +00005547
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005548/// \brief Helper class to manage the addition of builtin operator overload
5549/// candidates. It provides shared state and utility methods used throughout
5550/// the process, as well as a helper method to add each group of builtin
5551/// operator overloads from the standard to a candidate set.
5552class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005553 // Common instance state available to all overload candidate addition methods.
5554 Sema &S;
5555 Expr **Args;
5556 unsigned NumArgs;
5557 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005558 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005559 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005560 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005561
Chandler Carruthc6586e52010-12-12 10:35:00 +00005562 // Define some constants used to index and iterate over the arithemetic types
5563 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005564 // The "promoted arithmetic types" are the arithmetic
5565 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005566 static const unsigned FirstIntegralType = 3;
5567 static const unsigned LastIntegralType = 18;
5568 static const unsigned FirstPromotedIntegralType = 3,
5569 LastPromotedIntegralType = 9;
5570 static const unsigned FirstPromotedArithmeticType = 0,
5571 LastPromotedArithmeticType = 9;
5572 static const unsigned NumArithmeticTypes = 18;
5573
Chandler Carruthc6586e52010-12-12 10:35:00 +00005574 /// \brief Get the canonical type for a given arithmetic type index.
5575 CanQualType getArithmeticType(unsigned index) {
5576 assert(index < NumArithmeticTypes);
5577 static CanQualType ASTContext::* const
5578 ArithmeticTypes[NumArithmeticTypes] = {
5579 // Start of promoted types.
5580 &ASTContext::FloatTy,
5581 &ASTContext::DoubleTy,
5582 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005583
Chandler Carruthc6586e52010-12-12 10:35:00 +00005584 // Start of integral types.
5585 &ASTContext::IntTy,
5586 &ASTContext::LongTy,
5587 &ASTContext::LongLongTy,
5588 &ASTContext::UnsignedIntTy,
5589 &ASTContext::UnsignedLongTy,
5590 &ASTContext::UnsignedLongLongTy,
5591 // End of promoted types.
5592
5593 &ASTContext::BoolTy,
5594 &ASTContext::CharTy,
5595 &ASTContext::WCharTy,
5596 &ASTContext::Char16Ty,
5597 &ASTContext::Char32Ty,
5598 &ASTContext::SignedCharTy,
5599 &ASTContext::ShortTy,
5600 &ASTContext::UnsignedCharTy,
5601 &ASTContext::UnsignedShortTy,
5602 // End of integral types.
5603 // FIXME: What about complex?
5604 };
5605 return S.Context.*ArithmeticTypes[index];
5606 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005607
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005608 /// \brief Gets the canonical type resulting from the usual arithemetic
5609 /// converions for the given arithmetic types.
5610 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5611 // Accelerator table for performing the usual arithmetic conversions.
5612 // The rules are basically:
5613 // - if either is floating-point, use the wider floating-point
5614 // - if same signedness, use the higher rank
5615 // - if same size, use unsigned of the higher rank
5616 // - use the larger type
5617 // These rules, together with the axiom that higher ranks are
5618 // never smaller, are sufficient to precompute all of these results
5619 // *except* when dealing with signed types of higher rank.
5620 // (we could precompute SLL x UI for all known platforms, but it's
5621 // better not to make any assumptions).
5622 enum PromotedType {
5623 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5624 };
5625 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5626 [LastPromotedArithmeticType] = {
5627 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5628 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5629 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5630 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5631 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5632 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5633 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5634 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5635 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5636 };
5637
5638 assert(L < LastPromotedArithmeticType);
5639 assert(R < LastPromotedArithmeticType);
5640 int Idx = ConversionsTable[L][R];
5641
5642 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005643 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005644
5645 // Slow path: we need to compare widths.
5646 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005647 CanQualType LT = getArithmeticType(L),
5648 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005649 unsigned LW = S.Context.getIntWidth(LT),
5650 RW = S.Context.getIntWidth(RT);
5651
5652 // If they're different widths, use the signed type.
5653 if (LW > RW) return LT;
5654 else if (LW < RW) return RT;
5655
5656 // Otherwise, use the unsigned type of the signed type's rank.
5657 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5658 assert(L == SLL || R == SLL);
5659 return S.Context.UnsignedLongLongTy;
5660 }
5661
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005662 /// \brief Helper method to factor out the common pattern of adding overloads
5663 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005664 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5665 bool HasVolatile) {
5666 QualType ParamTypes[2] = {
5667 S.Context.getLValueReferenceType(CandidateTy),
5668 S.Context.IntTy
5669 };
5670
5671 // Non-volatile version.
5672 if (NumArgs == 1)
5673 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5674 else
5675 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5676
5677 // Use a heuristic to reduce number of builtin candidates in the set:
5678 // add volatile version only if there are conversions to a volatile type.
5679 if (HasVolatile) {
5680 ParamTypes[0] =
5681 S.Context.getLValueReferenceType(
5682 S.Context.getVolatileType(CandidateTy));
5683 if (NumArgs == 1)
5684 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5685 else
5686 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5687 }
5688 }
5689
5690public:
5691 BuiltinOperatorOverloadBuilder(
5692 Sema &S, Expr **Args, unsigned NumArgs,
5693 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005694 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005695 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005696 OverloadCandidateSet &CandidateSet)
5697 : S(S), Args(Args), NumArgs(NumArgs),
5698 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005699 HasArithmeticOrEnumeralCandidateType(
5700 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005701 CandidateTypes(CandidateTypes),
5702 CandidateSet(CandidateSet) {
5703 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005704 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005705 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005706 assert(getArithmeticType(LastPromotedIntegralType - 1)
5707 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005708 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005709 assert(getArithmeticType(FirstPromotedArithmeticType)
5710 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005711 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005712 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5713 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005714 "Invalid last promoted arithmetic type");
5715 }
5716
5717 // C++ [over.built]p3:
5718 //
5719 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5720 // is either volatile or empty, there exist candidate operator
5721 // functions of the form
5722 //
5723 // VQ T& operator++(VQ T&);
5724 // T operator++(VQ T&, int);
5725 //
5726 // C++ [over.built]p4:
5727 //
5728 // For every pair (T, VQ), where T is an arithmetic type other
5729 // than bool, and VQ is either volatile or empty, there exist
5730 // candidate operator functions of the form
5731 //
5732 // VQ T& operator--(VQ T&);
5733 // T operator--(VQ T&, int);
5734 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005735 if (!HasArithmeticOrEnumeralCandidateType)
5736 return;
5737
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005738 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5739 Arith < NumArithmeticTypes; ++Arith) {
5740 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005741 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005742 VisibleTypeConversionsQuals.hasVolatile());
5743 }
5744 }
5745
5746 // C++ [over.built]p5:
5747 //
5748 // For every pair (T, VQ), where T is a cv-qualified or
5749 // cv-unqualified object type, and VQ is either volatile or
5750 // empty, there exist candidate operator functions of the form
5751 //
5752 // T*VQ& operator++(T*VQ&);
5753 // T*VQ& operator--(T*VQ&);
5754 // T* operator++(T*VQ&, int);
5755 // T* operator--(T*VQ&, int);
5756 void addPlusPlusMinusMinusPointerOverloads() {
5757 for (BuiltinCandidateTypeSet::iterator
5758 Ptr = CandidateTypes[0].pointer_begin(),
5759 PtrEnd = CandidateTypes[0].pointer_end();
5760 Ptr != PtrEnd; ++Ptr) {
5761 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005762 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005763 continue;
5764
5765 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5766 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5767 VisibleTypeConversionsQuals.hasVolatile()));
5768 }
5769 }
5770
5771 // C++ [over.built]p6:
5772 // For every cv-qualified or cv-unqualified object type T, there
5773 // exist candidate operator functions of the form
5774 //
5775 // T& operator*(T*);
5776 //
5777 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005778 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005779 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005780 // T& operator*(T*);
5781 void addUnaryStarPointerOverloads() {
5782 for (BuiltinCandidateTypeSet::iterator
5783 Ptr = CandidateTypes[0].pointer_begin(),
5784 PtrEnd = CandidateTypes[0].pointer_end();
5785 Ptr != PtrEnd; ++Ptr) {
5786 QualType ParamTy = *Ptr;
5787 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005788 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5789 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005790
Douglas Gregor02824322011-01-26 19:30:28 +00005791 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5792 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5793 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005794
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005795 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5796 &ParamTy, Args, 1, CandidateSet);
5797 }
5798 }
5799
5800 // C++ [over.built]p9:
5801 // For every promoted arithmetic type T, there exist candidate
5802 // operator functions of the form
5803 //
5804 // T operator+(T);
5805 // T operator-(T);
5806 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005807 if (!HasArithmeticOrEnumeralCandidateType)
5808 return;
5809
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005810 for (unsigned Arith = FirstPromotedArithmeticType;
5811 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005812 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005813 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5814 }
5815
5816 // Extension: We also add these operators for vector types.
5817 for (BuiltinCandidateTypeSet::iterator
5818 Vec = CandidateTypes[0].vector_begin(),
5819 VecEnd = CandidateTypes[0].vector_end();
5820 Vec != VecEnd; ++Vec) {
5821 QualType VecTy = *Vec;
5822 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5823 }
5824 }
5825
5826 // C++ [over.built]p8:
5827 // For every type T, there exist candidate operator functions of
5828 // the form
5829 //
5830 // T* operator+(T*);
5831 void addUnaryPlusPointerOverloads() {
5832 for (BuiltinCandidateTypeSet::iterator
5833 Ptr = CandidateTypes[0].pointer_begin(),
5834 PtrEnd = CandidateTypes[0].pointer_end();
5835 Ptr != PtrEnd; ++Ptr) {
5836 QualType ParamTy = *Ptr;
5837 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5838 }
5839 }
5840
5841 // C++ [over.built]p10:
5842 // For every promoted integral type T, there exist candidate
5843 // operator functions of the form
5844 //
5845 // T operator~(T);
5846 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005847 if (!HasArithmeticOrEnumeralCandidateType)
5848 return;
5849
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005850 for (unsigned Int = FirstPromotedIntegralType;
5851 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005852 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005853 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5854 }
5855
5856 // Extension: We also add this operator for vector types.
5857 for (BuiltinCandidateTypeSet::iterator
5858 Vec = CandidateTypes[0].vector_begin(),
5859 VecEnd = CandidateTypes[0].vector_end();
5860 Vec != VecEnd; ++Vec) {
5861 QualType VecTy = *Vec;
5862 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5863 }
5864 }
5865
5866 // C++ [over.match.oper]p16:
5867 // For every pointer to member type T, there exist candidate operator
5868 // functions of the form
5869 //
5870 // bool operator==(T,T);
5871 // bool operator!=(T,T);
5872 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5873 /// Set of (canonical) types that we've already handled.
5874 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5875
5876 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5877 for (BuiltinCandidateTypeSet::iterator
5878 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5879 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5880 MemPtr != MemPtrEnd;
5881 ++MemPtr) {
5882 // Don't add the same builtin candidate twice.
5883 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5884 continue;
5885
5886 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5887 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5888 CandidateSet);
5889 }
5890 }
5891 }
5892
5893 // C++ [over.built]p15:
5894 //
Douglas Gregor80af3132011-05-21 23:15:46 +00005895 // For every T, where T is an enumeration type, a pointer type, or
5896 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005897 //
5898 // bool operator<(T, T);
5899 // bool operator>(T, T);
5900 // bool operator<=(T, T);
5901 // bool operator>=(T, T);
5902 // bool operator==(T, T);
5903 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005904 void addRelationalPointerOrEnumeralOverloads() {
5905 // C++ [over.built]p1:
5906 // If there is a user-written candidate with the same name and parameter
5907 // types as a built-in candidate operator function, the built-in operator
5908 // function is hidden and is not included in the set of candidate
5909 // functions.
5910 //
5911 // The text is actually in a note, but if we don't implement it then we end
5912 // up with ambiguities when the user provides an overloaded operator for
5913 // an enumeration type. Note that only enumeration types have this problem,
5914 // so we track which enumeration types we've seen operators for. Also, the
5915 // only other overloaded operator with enumeration argumenst, operator=,
5916 // cannot be overloaded for enumeration types, so this is the only place
5917 // where we must suppress candidates like this.
5918 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5919 UserDefinedBinaryOperators;
5920
5921 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5922 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5923 CandidateTypes[ArgIdx].enumeration_end()) {
5924 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5925 CEnd = CandidateSet.end();
5926 C != CEnd; ++C) {
5927 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5928 continue;
5929
5930 QualType FirstParamType =
5931 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5932 QualType SecondParamType =
5933 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5934
5935 // Skip if either parameter isn't of enumeral type.
5936 if (!FirstParamType->isEnumeralType() ||
5937 !SecondParamType->isEnumeralType())
5938 continue;
5939
5940 // Add this operator to the set of known user-defined operators.
5941 UserDefinedBinaryOperators.insert(
5942 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5943 S.Context.getCanonicalType(SecondParamType)));
5944 }
5945 }
5946 }
5947
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005948 /// Set of (canonical) types that we've already handled.
5949 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5950
5951 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5952 for (BuiltinCandidateTypeSet::iterator
5953 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5954 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5955 Ptr != PtrEnd; ++Ptr) {
5956 // Don't add the same builtin candidate twice.
5957 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5958 continue;
5959
5960 QualType ParamTypes[2] = { *Ptr, *Ptr };
5961 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5962 CandidateSet);
5963 }
5964 for (BuiltinCandidateTypeSet::iterator
5965 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5966 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5967 Enum != EnumEnd; ++Enum) {
5968 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5969
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005970 // Don't add the same builtin candidate twice, or if a user defined
5971 // candidate exists.
5972 if (!AddedTypes.insert(CanonType) ||
5973 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5974 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005975 continue;
5976
5977 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005978 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5979 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005980 }
Douglas Gregor80af3132011-05-21 23:15:46 +00005981
5982 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5983 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5984 if (AddedTypes.insert(NullPtrTy) &&
5985 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5986 NullPtrTy))) {
5987 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5988 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5989 CandidateSet);
5990 }
5991 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005992 }
5993 }
5994
5995 // C++ [over.built]p13:
5996 //
5997 // For every cv-qualified or cv-unqualified object type T
5998 // there exist candidate operator functions of the form
5999 //
6000 // T* operator+(T*, ptrdiff_t);
6001 // T& operator[](T*, ptrdiff_t); [BELOW]
6002 // T* operator-(T*, ptrdiff_t);
6003 // T* operator+(ptrdiff_t, T*);
6004 // T& operator[](ptrdiff_t, T*); [BELOW]
6005 //
6006 // C++ [over.built]p14:
6007 //
6008 // For every T, where T is a pointer to object type, there
6009 // exist candidate operator functions of the form
6010 //
6011 // ptrdiff_t operator-(T, T);
6012 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6013 /// Set of (canonical) types that we've already handled.
6014 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6015
6016 for (int Arg = 0; Arg < 2; ++Arg) {
6017 QualType AsymetricParamTypes[2] = {
6018 S.Context.getPointerDiffType(),
6019 S.Context.getPointerDiffType(),
6020 };
6021 for (BuiltinCandidateTypeSet::iterator
6022 Ptr = CandidateTypes[Arg].pointer_begin(),
6023 PtrEnd = CandidateTypes[Arg].pointer_end();
6024 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00006025 QualType PointeeTy = (*Ptr)->getPointeeType();
6026 if (!PointeeTy->isObjectType())
6027 continue;
6028
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006029 AsymetricParamTypes[Arg] = *Ptr;
6030 if (Arg == 0 || Op == OO_Plus) {
6031 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6032 // T* operator+(ptrdiff_t, T*);
6033 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6034 CandidateSet);
6035 }
6036 if (Op == OO_Minus) {
6037 // ptrdiff_t operator-(T, T);
6038 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6039 continue;
6040
6041 QualType ParamTypes[2] = { *Ptr, *Ptr };
6042 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6043 Args, 2, CandidateSet);
6044 }
6045 }
6046 }
6047 }
6048
6049 // C++ [over.built]p12:
6050 //
6051 // For every pair of promoted arithmetic types L and R, there
6052 // exist candidate operator functions of the form
6053 //
6054 // LR operator*(L, R);
6055 // LR operator/(L, R);
6056 // LR operator+(L, R);
6057 // LR operator-(L, R);
6058 // bool operator<(L, R);
6059 // bool operator>(L, R);
6060 // bool operator<=(L, R);
6061 // bool operator>=(L, R);
6062 // bool operator==(L, R);
6063 // bool operator!=(L, R);
6064 //
6065 // where LR is the result of the usual arithmetic conversions
6066 // between types L and R.
6067 //
6068 // C++ [over.built]p24:
6069 //
6070 // For every pair of promoted arithmetic types L and R, there exist
6071 // candidate operator functions of the form
6072 //
6073 // LR operator?(bool, L, R);
6074 //
6075 // where LR is the result of the usual arithmetic conversions
6076 // between types L and R.
6077 // Our candidates ignore the first parameter.
6078 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006079 if (!HasArithmeticOrEnumeralCandidateType)
6080 return;
6081
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006082 for (unsigned Left = FirstPromotedArithmeticType;
6083 Left < LastPromotedArithmeticType; ++Left) {
6084 for (unsigned Right = FirstPromotedArithmeticType;
6085 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006086 QualType LandR[2] = { getArithmeticType(Left),
6087 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006088 QualType Result =
6089 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006090 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006091 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6092 }
6093 }
6094
6095 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6096 // conditional operator for vector types.
6097 for (BuiltinCandidateTypeSet::iterator
6098 Vec1 = CandidateTypes[0].vector_begin(),
6099 Vec1End = CandidateTypes[0].vector_end();
6100 Vec1 != Vec1End; ++Vec1) {
6101 for (BuiltinCandidateTypeSet::iterator
6102 Vec2 = CandidateTypes[1].vector_begin(),
6103 Vec2End = CandidateTypes[1].vector_end();
6104 Vec2 != Vec2End; ++Vec2) {
6105 QualType LandR[2] = { *Vec1, *Vec2 };
6106 QualType Result = S.Context.BoolTy;
6107 if (!isComparison) {
6108 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6109 Result = *Vec1;
6110 else
6111 Result = *Vec2;
6112 }
6113
6114 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6115 }
6116 }
6117 }
6118
6119 // C++ [over.built]p17:
6120 //
6121 // For every pair of promoted integral types L and R, there
6122 // exist candidate operator functions of the form
6123 //
6124 // LR operator%(L, R);
6125 // LR operator&(L, R);
6126 // LR operator^(L, R);
6127 // LR operator|(L, R);
6128 // L operator<<(L, R);
6129 // L operator>>(L, R);
6130 //
6131 // where LR is the result of the usual arithmetic conversions
6132 // between types L and R.
6133 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006134 if (!HasArithmeticOrEnumeralCandidateType)
6135 return;
6136
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006137 for (unsigned Left = FirstPromotedIntegralType;
6138 Left < LastPromotedIntegralType; ++Left) {
6139 for (unsigned Right = FirstPromotedIntegralType;
6140 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006141 QualType LandR[2] = { getArithmeticType(Left),
6142 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006143 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6144 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006145 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006146 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6147 }
6148 }
6149 }
6150
6151 // C++ [over.built]p20:
6152 //
6153 // For every pair (T, VQ), where T is an enumeration or
6154 // pointer to member type and VQ is either volatile or
6155 // empty, there exist candidate operator functions of the form
6156 //
6157 // VQ T& operator=(VQ T&, T);
6158 void addAssignmentMemberPointerOrEnumeralOverloads() {
6159 /// Set of (canonical) types that we've already handled.
6160 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6161
6162 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6163 for (BuiltinCandidateTypeSet::iterator
6164 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6165 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6166 Enum != EnumEnd; ++Enum) {
6167 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6168 continue;
6169
6170 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6171 CandidateSet);
6172 }
6173
6174 for (BuiltinCandidateTypeSet::iterator
6175 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6176 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6177 MemPtr != MemPtrEnd; ++MemPtr) {
6178 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6179 continue;
6180
6181 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6182 CandidateSet);
6183 }
6184 }
6185 }
6186
6187 // C++ [over.built]p19:
6188 //
6189 // For every pair (T, VQ), where T is any type and VQ is either
6190 // volatile or empty, there exist candidate operator functions
6191 // of the form
6192 //
6193 // T*VQ& operator=(T*VQ&, T*);
6194 //
6195 // C++ [over.built]p21:
6196 //
6197 // For every pair (T, VQ), where T is a cv-qualified or
6198 // cv-unqualified object type and VQ is either volatile or
6199 // empty, there exist candidate operator functions of the form
6200 //
6201 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6202 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6203 void addAssignmentPointerOverloads(bool isEqualOp) {
6204 /// Set of (canonical) types that we've already handled.
6205 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6206
6207 for (BuiltinCandidateTypeSet::iterator
6208 Ptr = CandidateTypes[0].pointer_begin(),
6209 PtrEnd = CandidateTypes[0].pointer_end();
6210 Ptr != PtrEnd; ++Ptr) {
6211 // If this is operator=, keep track of the builtin candidates we added.
6212 if (isEqualOp)
6213 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006214 else if (!(*Ptr)->getPointeeType()->isObjectType())
6215 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006216
6217 // non-volatile version
6218 QualType ParamTypes[2] = {
6219 S.Context.getLValueReferenceType(*Ptr),
6220 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6221 };
6222 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6223 /*IsAssigmentOperator=*/ isEqualOp);
6224
6225 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6226 VisibleTypeConversionsQuals.hasVolatile()) {
6227 // volatile version
6228 ParamTypes[0] =
6229 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6230 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6231 /*IsAssigmentOperator=*/isEqualOp);
6232 }
6233 }
6234
6235 if (isEqualOp) {
6236 for (BuiltinCandidateTypeSet::iterator
6237 Ptr = CandidateTypes[1].pointer_begin(),
6238 PtrEnd = CandidateTypes[1].pointer_end();
6239 Ptr != PtrEnd; ++Ptr) {
6240 // Make sure we don't add the same candidate twice.
6241 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6242 continue;
6243
Chandler Carruth8e543b32010-12-12 08:17:55 +00006244 QualType ParamTypes[2] = {
6245 S.Context.getLValueReferenceType(*Ptr),
6246 *Ptr,
6247 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006248
6249 // non-volatile version
6250 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6251 /*IsAssigmentOperator=*/true);
6252
6253 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6254 VisibleTypeConversionsQuals.hasVolatile()) {
6255 // volatile version
6256 ParamTypes[0] =
6257 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006258 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6259 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006260 }
6261 }
6262 }
6263 }
6264
6265 // C++ [over.built]p18:
6266 //
6267 // For every triple (L, VQ, R), where L is an arithmetic type,
6268 // VQ is either volatile or empty, and R is a promoted
6269 // arithmetic type, there exist candidate operator functions of
6270 // the form
6271 //
6272 // VQ L& operator=(VQ L&, R);
6273 // VQ L& operator*=(VQ L&, R);
6274 // VQ L& operator/=(VQ L&, R);
6275 // VQ L& operator+=(VQ L&, R);
6276 // VQ L& operator-=(VQ L&, R);
6277 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006278 if (!HasArithmeticOrEnumeralCandidateType)
6279 return;
6280
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006281 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6282 for (unsigned Right = FirstPromotedArithmeticType;
6283 Right < LastPromotedArithmeticType; ++Right) {
6284 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006285 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006286
6287 // Add this built-in operator as a candidate (VQ is empty).
6288 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006289 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006290 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6291 /*IsAssigmentOperator=*/isEqualOp);
6292
6293 // Add this built-in operator as a candidate (VQ is 'volatile').
6294 if (VisibleTypeConversionsQuals.hasVolatile()) {
6295 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006296 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006297 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006298 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6299 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006300 /*IsAssigmentOperator=*/isEqualOp);
6301 }
6302 }
6303 }
6304
6305 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6306 for (BuiltinCandidateTypeSet::iterator
6307 Vec1 = CandidateTypes[0].vector_begin(),
6308 Vec1End = CandidateTypes[0].vector_end();
6309 Vec1 != Vec1End; ++Vec1) {
6310 for (BuiltinCandidateTypeSet::iterator
6311 Vec2 = CandidateTypes[1].vector_begin(),
6312 Vec2End = CandidateTypes[1].vector_end();
6313 Vec2 != Vec2End; ++Vec2) {
6314 QualType ParamTypes[2];
6315 ParamTypes[1] = *Vec2;
6316 // Add this built-in operator as a candidate (VQ is empty).
6317 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6318 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6319 /*IsAssigmentOperator=*/isEqualOp);
6320
6321 // Add this built-in operator as a candidate (VQ is 'volatile').
6322 if (VisibleTypeConversionsQuals.hasVolatile()) {
6323 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6324 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006325 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6326 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006327 /*IsAssigmentOperator=*/isEqualOp);
6328 }
6329 }
6330 }
6331 }
6332
6333 // C++ [over.built]p22:
6334 //
6335 // For every triple (L, VQ, R), where L is an integral type, VQ
6336 // is either volatile or empty, and R is a promoted integral
6337 // type, there exist candidate operator functions of the form
6338 //
6339 // VQ L& operator%=(VQ L&, R);
6340 // VQ L& operator<<=(VQ L&, R);
6341 // VQ L& operator>>=(VQ L&, R);
6342 // VQ L& operator&=(VQ L&, R);
6343 // VQ L& operator^=(VQ L&, R);
6344 // VQ L& operator|=(VQ L&, R);
6345 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006346 if (!HasArithmeticOrEnumeralCandidateType)
6347 return;
6348
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006349 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6350 for (unsigned Right = FirstPromotedIntegralType;
6351 Right < LastPromotedIntegralType; ++Right) {
6352 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006353 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006354
6355 // Add this built-in operator as a candidate (VQ is empty).
6356 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006357 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006358 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6359 if (VisibleTypeConversionsQuals.hasVolatile()) {
6360 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006361 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006362 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6363 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6364 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6365 CandidateSet);
6366 }
6367 }
6368 }
6369 }
6370
6371 // C++ [over.operator]p23:
6372 //
6373 // There also exist candidate operator functions of the form
6374 //
6375 // bool operator!(bool);
6376 // bool operator&&(bool, bool);
6377 // bool operator||(bool, bool);
6378 void addExclaimOverload() {
6379 QualType ParamTy = S.Context.BoolTy;
6380 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6381 /*IsAssignmentOperator=*/false,
6382 /*NumContextualBoolArguments=*/1);
6383 }
6384 void addAmpAmpOrPipePipeOverload() {
6385 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6386 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6387 /*IsAssignmentOperator=*/false,
6388 /*NumContextualBoolArguments=*/2);
6389 }
6390
6391 // C++ [over.built]p13:
6392 //
6393 // For every cv-qualified or cv-unqualified object type T there
6394 // exist candidate operator functions of the form
6395 //
6396 // T* operator+(T*, ptrdiff_t); [ABOVE]
6397 // T& operator[](T*, ptrdiff_t);
6398 // T* operator-(T*, ptrdiff_t); [ABOVE]
6399 // T* operator+(ptrdiff_t, T*); [ABOVE]
6400 // T& operator[](ptrdiff_t, T*);
6401 void addSubscriptOverloads() {
6402 for (BuiltinCandidateTypeSet::iterator
6403 Ptr = CandidateTypes[0].pointer_begin(),
6404 PtrEnd = CandidateTypes[0].pointer_end();
6405 Ptr != PtrEnd; ++Ptr) {
6406 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6407 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006408 if (!PointeeType->isObjectType())
6409 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006410
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006411 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6412
6413 // T& operator[](T*, ptrdiff_t)
6414 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6415 }
6416
6417 for (BuiltinCandidateTypeSet::iterator
6418 Ptr = CandidateTypes[1].pointer_begin(),
6419 PtrEnd = CandidateTypes[1].pointer_end();
6420 Ptr != PtrEnd; ++Ptr) {
6421 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6422 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006423 if (!PointeeType->isObjectType())
6424 continue;
6425
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006426 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6427
6428 // T& operator[](ptrdiff_t, T*)
6429 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6430 }
6431 }
6432
6433 // C++ [over.built]p11:
6434 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6435 // C1 is the same type as C2 or is a derived class of C2, T is an object
6436 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6437 // there exist candidate operator functions of the form
6438 //
6439 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6440 //
6441 // where CV12 is the union of CV1 and CV2.
6442 void addArrowStarOverloads() {
6443 for (BuiltinCandidateTypeSet::iterator
6444 Ptr = CandidateTypes[0].pointer_begin(),
6445 PtrEnd = CandidateTypes[0].pointer_end();
6446 Ptr != PtrEnd; ++Ptr) {
6447 QualType C1Ty = (*Ptr);
6448 QualType C1;
6449 QualifierCollector Q1;
6450 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6451 if (!isa<RecordType>(C1))
6452 continue;
6453 // heuristic to reduce number of builtin candidates in the set.
6454 // Add volatile/restrict version only if there are conversions to a
6455 // volatile/restrict type.
6456 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6457 continue;
6458 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6459 continue;
6460 for (BuiltinCandidateTypeSet::iterator
6461 MemPtr = CandidateTypes[1].member_pointer_begin(),
6462 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6463 MemPtr != MemPtrEnd; ++MemPtr) {
6464 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6465 QualType C2 = QualType(mptr->getClass(), 0);
6466 C2 = C2.getUnqualifiedType();
6467 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6468 break;
6469 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6470 // build CV12 T&
6471 QualType T = mptr->getPointeeType();
6472 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6473 T.isVolatileQualified())
6474 continue;
6475 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6476 T.isRestrictQualified())
6477 continue;
6478 T = Q1.apply(S.Context, T);
6479 QualType ResultTy = S.Context.getLValueReferenceType(T);
6480 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6481 }
6482 }
6483 }
6484
6485 // Note that we don't consider the first argument, since it has been
6486 // contextually converted to bool long ago. The candidates below are
6487 // therefore added as binary.
6488 //
6489 // C++ [over.built]p25:
6490 // For every type T, where T is a pointer, pointer-to-member, or scoped
6491 // enumeration type, there exist candidate operator functions of the form
6492 //
6493 // T operator?(bool, T, T);
6494 //
6495 void addConditionalOperatorOverloads() {
6496 /// Set of (canonical) types that we've already handled.
6497 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6498
6499 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6500 for (BuiltinCandidateTypeSet::iterator
6501 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6502 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6503 Ptr != PtrEnd; ++Ptr) {
6504 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6505 continue;
6506
6507 QualType ParamTypes[2] = { *Ptr, *Ptr };
6508 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6509 }
6510
6511 for (BuiltinCandidateTypeSet::iterator
6512 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6513 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6514 MemPtr != MemPtrEnd; ++MemPtr) {
6515 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6516 continue;
6517
6518 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6519 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6520 }
6521
6522 if (S.getLangOptions().CPlusPlus0x) {
6523 for (BuiltinCandidateTypeSet::iterator
6524 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6525 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6526 Enum != EnumEnd; ++Enum) {
6527 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6528 continue;
6529
6530 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6531 continue;
6532
6533 QualType ParamTypes[2] = { *Enum, *Enum };
6534 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6535 }
6536 }
6537 }
6538 }
6539};
6540
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006541} // end anonymous namespace
6542
6543/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6544/// operator overloads to the candidate set (C++ [over.built]), based
6545/// on the operator @p Op and the arguments given. For example, if the
6546/// operator is a binary '+', this routine might add "int
6547/// operator+(int, int)" to cover integer addition.
6548void
6549Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6550 SourceLocation OpLoc,
6551 Expr **Args, unsigned NumArgs,
6552 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006553 // Find all of the types that the arguments can convert to, but only
6554 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006555 // that make use of these types. Also record whether we encounter non-record
6556 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006557 Qualifiers VisibleTypeConversionsQuals;
6558 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006559 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6560 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006561
6562 bool HasNonRecordCandidateType = false;
6563 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006564 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006565 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6566 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6567 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6568 OpLoc,
6569 true,
6570 (Op == OO_Exclaim ||
6571 Op == OO_AmpAmp ||
6572 Op == OO_PipePipe),
6573 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006574 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6575 CandidateTypes[ArgIdx].hasNonRecordTypes();
6576 HasArithmeticOrEnumeralCandidateType =
6577 HasArithmeticOrEnumeralCandidateType ||
6578 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006579 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006580
Chandler Carruth00a38332010-12-13 01:44:01 +00006581 // Exit early when no non-record types have been added to the candidate set
6582 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00006583 //
6584 // We can't exit early for !, ||, or &&, since there we have always have
6585 // 'bool' overloads.
6586 if (!HasNonRecordCandidateType &&
6587 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00006588 return;
6589
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006590 // Setup an object to manage the common state for building overloads.
6591 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6592 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006593 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006594 CandidateTypes, CandidateSet);
6595
6596 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006597 switch (Op) {
6598 case OO_None:
6599 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00006600 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00006601
Chandler Carruth5184de02010-12-12 08:51:33 +00006602 case OO_New:
6603 case OO_Delete:
6604 case OO_Array_New:
6605 case OO_Array_Delete:
6606 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00006607 llvm_unreachable(
6608 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00006609
6610 case OO_Comma:
6611 case OO_Arrow:
6612 // C++ [over.match.oper]p3:
6613 // -- For the operator ',', the unary operator '&', or the
6614 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006615 break;
6616
6617 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006618 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006619 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006620 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006621
6622 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006623 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006624 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006625 } else {
6626 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6627 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6628 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006629 break;
6630
Chandler Carruth5184de02010-12-12 08:51:33 +00006631 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006632 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006633 OpBuilder.addUnaryStarPointerOverloads();
6634 else
6635 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6636 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006637
Chandler Carruth5184de02010-12-12 08:51:33 +00006638 case OO_Slash:
6639 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006640 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006641
6642 case OO_PlusPlus:
6643 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006644 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6645 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006646 break;
6647
Douglas Gregor84605ae2009-08-24 13:43:27 +00006648 case OO_EqualEqual:
6649 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006650 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006651 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006652
Douglas Gregora11693b2008-11-12 17:17:38 +00006653 case OO_Less:
6654 case OO_Greater:
6655 case OO_LessEqual:
6656 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006657 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006658 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6659 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006660
Douglas Gregora11693b2008-11-12 17:17:38 +00006661 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006662 case OO_Caret:
6663 case OO_Pipe:
6664 case OO_LessLess:
6665 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006666 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006667 break;
6668
Chandler Carruth5184de02010-12-12 08:51:33 +00006669 case OO_Amp: // '&' is either unary or binary
6670 if (NumArgs == 1)
6671 // C++ [over.match.oper]p3:
6672 // -- For the operator ',', the unary operator '&', or the
6673 // operator '->', the built-in candidates set is empty.
6674 break;
6675
6676 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6677 break;
6678
6679 case OO_Tilde:
6680 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6681 break;
6682
Douglas Gregora11693b2008-11-12 17:17:38 +00006683 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006684 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006685 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006686
6687 case OO_PlusEqual:
6688 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006689 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006690 // Fall through.
6691
6692 case OO_StarEqual:
6693 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006694 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006695 break;
6696
6697 case OO_PercentEqual:
6698 case OO_LessLessEqual:
6699 case OO_GreaterGreaterEqual:
6700 case OO_AmpEqual:
6701 case OO_CaretEqual:
6702 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006703 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006704 break;
6705
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006706 case OO_Exclaim:
6707 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006708 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006709
Douglas Gregora11693b2008-11-12 17:17:38 +00006710 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006711 case OO_PipePipe:
6712 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006713 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006714
6715 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006716 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006717 break;
6718
6719 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006720 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006721 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006722
6723 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006724 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006725 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6726 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006727 }
6728}
6729
Douglas Gregore254f902009-02-04 00:32:51 +00006730/// \brief Add function candidates found via argument-dependent lookup
6731/// to the set of overloading candidates.
6732///
6733/// This routine performs argument-dependent name lookup based on the
6734/// given function name (which may also be an operator name) and adds
6735/// all of the overload candidates found by ADL to the overload
6736/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006737void
Douglas Gregore254f902009-02-04 00:32:51 +00006738Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006739 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006740 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006741 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006742 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006743 bool PartialOverloading,
6744 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006745 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006746
John McCall91f61fc2010-01-26 06:04:06 +00006747 // FIXME: This approach for uniquing ADL results (and removing
6748 // redundant candidates from the set) relies on pointer-equality,
6749 // which means we need to key off the canonical decl. However,
6750 // always going back to the canonical decl might not get us the
6751 // right set of default arguments. What default arguments are
6752 // we supposed to consider on ADL candidates, anyway?
6753
Douglas Gregorcabea402009-09-22 15:41:20 +00006754 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006755 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6756 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006757
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006758 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006759 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6760 CandEnd = CandidateSet.end();
6761 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006762 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006763 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006764 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006765 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006766 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006767
6768 // For each of the ADL candidates we found, add it to the overload
6769 // set.
John McCall8fe68082010-01-26 07:16:45 +00006770 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006771 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006772 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006773 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006774 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006775
John McCalla0296f72010-03-19 07:35:19 +00006776 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006777 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006778 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006779 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006780 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006781 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006782 }
Douglas Gregore254f902009-02-04 00:32:51 +00006783}
6784
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006785/// isBetterOverloadCandidate - Determines whether the first overload
6786/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006787bool
John McCall5c32be02010-08-24 20:38:10 +00006788isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006789 const OverloadCandidate &Cand1,
6790 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006791 SourceLocation Loc,
6792 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006793 // Define viable functions to be better candidates than non-viable
6794 // functions.
6795 if (!Cand2.Viable)
6796 return Cand1.Viable;
6797 else if (!Cand1.Viable)
6798 return false;
6799
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006800 // C++ [over.match.best]p1:
6801 //
6802 // -- if F is a static member function, ICS1(F) is defined such
6803 // that ICS1(F) is neither better nor worse than ICS1(G) for
6804 // any function G, and, symmetrically, ICS1(G) is neither
6805 // better nor worse than ICS1(F).
6806 unsigned StartArg = 0;
6807 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6808 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006809
Douglas Gregord3cb3562009-07-07 23:38:56 +00006810 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006811 // A viable function F1 is defined to be a better function than another
6812 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006813 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006814 unsigned NumArgs = Cand1.Conversions.size();
6815 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6816 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006817 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006818 switch (CompareImplicitConversionSequences(S,
6819 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006820 Cand2.Conversions[ArgIdx])) {
6821 case ImplicitConversionSequence::Better:
6822 // Cand1 has a better conversion sequence.
6823 HasBetterConversion = true;
6824 break;
6825
6826 case ImplicitConversionSequence::Worse:
6827 // Cand1 can't be better than Cand2.
6828 return false;
6829
6830 case ImplicitConversionSequence::Indistinguishable:
6831 // Do nothing.
6832 break;
6833 }
6834 }
6835
Mike Stump11289f42009-09-09 15:08:12 +00006836 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006837 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006838 if (HasBetterConversion)
6839 return true;
6840
Mike Stump11289f42009-09-09 15:08:12 +00006841 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006842 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006843 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006844 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6845 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006846
6847 // -- F1 and F2 are function template specializations, and the function
6848 // template for F1 is more specialized than the template for F2
6849 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006850 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006851 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006852 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006853 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006854 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6855 Cand2.Function->getPrimaryTemplate(),
6856 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006857 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006858 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006859 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006860 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006861 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006862
Douglas Gregora1f013e2008-11-07 22:36:19 +00006863 // -- the context is an initialization by user-defined conversion
6864 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6865 // from the return type of F1 to the destination type (i.e.,
6866 // the type of the entity being initialized) is a better
6867 // conversion sequence than the standard conversion sequence
6868 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006869 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006870 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006871 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006872 switch (CompareStandardConversionSequences(S,
6873 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006874 Cand2.FinalConversion)) {
6875 case ImplicitConversionSequence::Better:
6876 // Cand1 has a better conversion sequence.
6877 return true;
6878
6879 case ImplicitConversionSequence::Worse:
6880 // Cand1 can't be better than Cand2.
6881 return false;
6882
6883 case ImplicitConversionSequence::Indistinguishable:
6884 // Do nothing
6885 break;
6886 }
6887 }
6888
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006889 return false;
6890}
6891
Mike Stump11289f42009-09-09 15:08:12 +00006892/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006893/// within an overload candidate set.
6894///
6895/// \param CandidateSet the set of candidate functions.
6896///
6897/// \param Loc the location of the function name (or operator symbol) for
6898/// which overload resolution occurs.
6899///
Mike Stump11289f42009-09-09 15:08:12 +00006900/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006901/// function, Best points to the candidate function found.
6902///
6903/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006904OverloadingResult
6905OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006906 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00006907 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006908 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006909 Best = end();
6910 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6911 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006912 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006913 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006914 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006915 }
6916
6917 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006918 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006919 return OR_No_Viable_Function;
6920
6921 // Make sure that this function is better than every other viable
6922 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006923 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006924 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006925 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006926 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006927 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006928 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006929 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006930 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006931 }
Mike Stump11289f42009-09-09 15:08:12 +00006932
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006933 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006934 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00006935 (Best->Function->isDeleted() ||
6936 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006937 return OR_Deleted;
6938
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006939 return OR_Success;
6940}
6941
John McCall53262c92010-01-12 02:15:36 +00006942namespace {
6943
6944enum OverloadCandidateKind {
6945 oc_function,
6946 oc_method,
6947 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006948 oc_function_template,
6949 oc_method_template,
6950 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006951 oc_implicit_default_constructor,
6952 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006953 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006954 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006955 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00006956 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006957};
6958
John McCalle1ac8d12010-01-13 00:25:19 +00006959OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6960 FunctionDecl *Fn,
6961 std::string &Description) {
6962 bool isTemplate = false;
6963
6964 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6965 isTemplate = true;
6966 Description = S.getTemplateArgumentBindingsText(
6967 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6968 }
John McCallfd0b2f82010-01-06 09:43:14 +00006969
6970 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006971 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006972 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006973
Sebastian Redl08905022011-02-05 19:23:19 +00006974 if (Ctor->getInheritedConstructor())
6975 return oc_implicit_inherited_constructor;
6976
Alexis Hunt119c10e2011-05-25 23:16:36 +00006977 if (Ctor->isDefaultConstructor())
6978 return oc_implicit_default_constructor;
6979
6980 if (Ctor->isMoveConstructor())
6981 return oc_implicit_move_constructor;
6982
6983 assert(Ctor->isCopyConstructor() &&
6984 "unexpected sort of implicit constructor");
6985 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006986 }
6987
6988 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6989 // This actually gets spelled 'candidate function' for now, but
6990 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006991 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006992 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006993
Alexis Hunt119c10e2011-05-25 23:16:36 +00006994 if (Meth->isMoveAssignmentOperator())
6995 return oc_implicit_move_assignment;
6996
Douglas Gregorec3bec02010-09-27 22:37:28 +00006997 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006998 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006999 return oc_implicit_copy_assignment;
7000 }
7001
John McCalle1ac8d12010-01-13 00:25:19 +00007002 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00007003}
7004
Sebastian Redl08905022011-02-05 19:23:19 +00007005void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7006 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7007 if (!Ctor) return;
7008
7009 Ctor = Ctor->getInheritedConstructor();
7010 if (!Ctor) return;
7011
7012 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7013}
7014
John McCall53262c92010-01-12 02:15:36 +00007015} // end anonymous namespace
7016
7017// Notes the location of an overload candidate.
7018void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00007019 std::string FnDesc;
7020 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
7021 Diag(Fn->getLocation(), diag::note_ovl_candidate)
7022 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00007023 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00007024}
7025
Douglas Gregorb491ed32011-02-19 21:32:49 +00007026//Notes the location of all overload candidates designated through
7027// OverloadedExpr
7028void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
7029 assert(OverloadedExpr->getType() == Context.OverloadTy);
7030
7031 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7032 OverloadExpr *OvlExpr = Ovl.Expression;
7033
7034 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7035 IEnd = OvlExpr->decls_end();
7036 I != IEnd; ++I) {
7037 if (FunctionTemplateDecl *FunTmpl =
7038 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
7039 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
7040 } else if (FunctionDecl *Fun
7041 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
7042 NoteOverloadCandidate(Fun);
7043 }
7044 }
7045}
7046
John McCall0d1da222010-01-12 00:44:57 +00007047/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7048/// "lead" diagnostic; it will be given two arguments, the source and
7049/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007050void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7051 Sema &S,
7052 SourceLocation CaretLoc,
7053 const PartialDiagnostic &PDiag) const {
7054 S.Diag(CaretLoc, PDiag)
7055 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007056 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007057 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7058 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007059 }
John McCall12f97bc2010-01-08 04:41:39 +00007060}
7061
John McCall0d1da222010-01-12 00:44:57 +00007062namespace {
7063
John McCall6a61b522010-01-13 09:16:55 +00007064void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7065 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7066 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007067 assert(Cand->Function && "for now, candidate must be a function");
7068 FunctionDecl *Fn = Cand->Function;
7069
7070 // There's a conversion slot for the object argument if this is a
7071 // non-constructor method. Note that 'I' corresponds the
7072 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007073 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007074 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007075 if (I == 0)
7076 isObjectArgument = true;
7077 else
7078 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007079 }
7080
John McCalle1ac8d12010-01-13 00:25:19 +00007081 std::string FnDesc;
7082 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7083
John McCall6a61b522010-01-13 09:16:55 +00007084 Expr *FromExpr = Conv.Bad.FromExpr;
7085 QualType FromTy = Conv.Bad.getFromType();
7086 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007087
John McCallfb7ad0f2010-02-02 02:42:52 +00007088 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007089 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007090 Expr *E = FromExpr->IgnoreParens();
7091 if (isa<UnaryOperator>(E))
7092 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007093 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007094
7095 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7096 << (unsigned) FnKind << FnDesc
7097 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7098 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007099 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007100 return;
7101 }
7102
John McCall6d174642010-01-23 08:10:49 +00007103 // Do some hand-waving analysis to see if the non-viability is due
7104 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007105 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7106 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7107 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7108 CToTy = RT->getPointeeType();
7109 else {
7110 // TODO: detect and diagnose the full richness of const mismatches.
7111 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7112 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7113 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7114 }
7115
7116 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7117 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7118 // It is dumb that we have to do this here.
7119 while (isa<ArrayType>(CFromTy))
7120 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7121 while (isa<ArrayType>(CToTy))
7122 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7123
7124 Qualifiers FromQs = CFromTy.getQualifiers();
7125 Qualifiers ToQs = CToTy.getQualifiers();
7126
7127 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7128 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7129 << (unsigned) FnKind << FnDesc
7130 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7131 << FromTy
7132 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7133 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007134 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007135 return;
7136 }
7137
John McCall31168b02011-06-15 23:02:42 +00007138 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007139 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007140 << (unsigned) FnKind << FnDesc
7141 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7142 << FromTy
7143 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7144 << (unsigned) isObjectArgument << I+1;
7145 MaybeEmitInheritedConstructorNote(S, Fn);
7146 return;
7147 }
7148
Douglas Gregoraec25842011-04-26 23:16:46 +00007149 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7150 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7151 << (unsigned) FnKind << FnDesc
7152 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7153 << FromTy
7154 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7155 << (unsigned) isObjectArgument << I+1;
7156 MaybeEmitInheritedConstructorNote(S, Fn);
7157 return;
7158 }
7159
John McCall47000992010-01-14 03:28:57 +00007160 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7161 assert(CVR && "unexpected qualifiers mismatch");
7162
7163 if (isObjectArgument) {
7164 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7165 << (unsigned) FnKind << FnDesc
7166 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7167 << FromTy << (CVR - 1);
7168 } else {
7169 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7170 << (unsigned) FnKind << FnDesc
7171 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7172 << FromTy << (CVR - 1) << I+1;
7173 }
Sebastian Redl08905022011-02-05 19:23:19 +00007174 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007175 return;
7176 }
7177
Sebastian Redla72462c2011-09-24 17:48:32 +00007178 // Special diagnostic for failure to convert an initializer list, since
7179 // telling the user that it has type void is not useful.
7180 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7181 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7182 << (unsigned) FnKind << FnDesc
7183 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7184 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7185 MaybeEmitInheritedConstructorNote(S, Fn);
7186 return;
7187 }
7188
John McCall6d174642010-01-23 08:10:49 +00007189 // Diagnose references or pointers to incomplete types differently,
7190 // since it's far from impossible that the incompleteness triggered
7191 // the failure.
7192 QualType TempFromTy = FromTy.getNonReferenceType();
7193 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7194 TempFromTy = PTy->getPointeeType();
7195 if (TempFromTy->isIncompleteType()) {
7196 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7197 << (unsigned) FnKind << FnDesc
7198 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7199 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007200 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007201 return;
7202 }
7203
Douglas Gregor56f2e342010-06-30 23:01:39 +00007204 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007205 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007206 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7207 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7208 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7209 FromPtrTy->getPointeeType()) &&
7210 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7211 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007212 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007213 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007214 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007215 }
7216 } else if (const ObjCObjectPointerType *FromPtrTy
7217 = FromTy->getAs<ObjCObjectPointerType>()) {
7218 if (const ObjCObjectPointerType *ToPtrTy
7219 = ToTy->getAs<ObjCObjectPointerType>())
7220 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7221 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7222 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7223 FromPtrTy->getPointeeType()) &&
7224 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007225 BaseToDerivedConversion = 2;
7226 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7227 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7228 !FromTy->isIncompleteType() &&
7229 !ToRefTy->getPointeeType()->isIncompleteType() &&
7230 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7231 BaseToDerivedConversion = 3;
7232 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007233
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007234 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007235 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007236 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007237 << (unsigned) FnKind << FnDesc
7238 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007239 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007240 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007241 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007242 return;
7243 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007244
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007245 if (isa<ObjCObjectPointerType>(CFromTy) &&
7246 isa<PointerType>(CToTy)) {
7247 Qualifiers FromQs = CFromTy.getQualifiers();
7248 Qualifiers ToQs = CToTy.getQualifiers();
7249 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7250 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7251 << (unsigned) FnKind << FnDesc
7252 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7253 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7254 MaybeEmitInheritedConstructorNote(S, Fn);
7255 return;
7256 }
7257 }
7258
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007259 // Emit the generic diagnostic and, optionally, add the hints to it.
7260 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7261 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007262 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007263 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7264 << (unsigned) (Cand->Fix.Kind);
7265
7266 // If we can fix the conversion, suggest the FixIts.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007267 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007268 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7269 HI != HE; ++HI)
7270 FDiag << *HI;
7271 S.Diag(Fn->getLocation(), FDiag);
7272
Sebastian Redl08905022011-02-05 19:23:19 +00007273 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007274}
7275
7276void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7277 unsigned NumFormalArgs) {
7278 // TODO: treat calls to a missing default constructor as a special case
7279
7280 FunctionDecl *Fn = Cand->Function;
7281 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7282
7283 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007284
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00007285 // With invalid overloaded operators, it's possible that we think we
7286 // have an arity mismatch when it fact it looks like we have the
7287 // right number of arguments, because only overloaded operators have
7288 // the weird behavior of overloading member and non-member functions.
7289 // Just don't report anything.
7290 if (Fn->isInvalidDecl() &&
7291 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7292 return;
7293
John McCall6a61b522010-01-13 09:16:55 +00007294 // at least / at most / exactly
7295 unsigned mode, modeCount;
7296 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007297 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7298 (Cand->FailureKind == ovl_fail_bad_deduction &&
7299 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007300 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00007301 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00007302 mode = 0; // "at least"
7303 else
7304 mode = 2; // "exactly"
7305 modeCount = MinParams;
7306 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007307 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7308 (Cand->FailureKind == ovl_fail_bad_deduction &&
7309 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00007310 if (MinParams != FnTy->getNumArgs())
7311 mode = 1; // "at most"
7312 else
7313 mode = 2; // "exactly"
7314 modeCount = FnTy->getNumArgs();
7315 }
7316
7317 std::string Description;
7318 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7319
7320 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007321 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00007322 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00007323 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007324}
7325
John McCall8b9ed552010-02-01 18:53:26 +00007326/// Diagnose a failed template-argument deduction.
7327void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7328 Expr **Args, unsigned NumArgs) {
7329 FunctionDecl *Fn = Cand->Function; // pattern
7330
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007331 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007332 NamedDecl *ParamD;
7333 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7334 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7335 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007336 switch (Cand->DeductionFailure.Result) {
7337 case Sema::TDK_Success:
7338 llvm_unreachable("TDK_success while diagnosing bad deduction");
7339
7340 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007341 assert(ParamD && "no parameter found for incomplete deduction result");
7342 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7343 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007344 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007345 return;
7346 }
7347
John McCall42d7d192010-08-05 09:05:08 +00007348 case Sema::TDK_Underqualified: {
7349 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7350 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7351
7352 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7353
7354 // Param will have been canonicalized, but it should just be a
7355 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007356 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007357 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007358 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007359 assert(S.Context.hasSameType(Param, NonCanonParam));
7360
7361 // Arg has also been canonicalized, but there's nothing we can do
7362 // about that. It also doesn't matter as much, because it won't
7363 // have any template parameters in it (because deduction isn't
7364 // done on dependent types).
7365 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7366
7367 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7368 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007369 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007370 return;
7371 }
7372
7373 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007374 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007375 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007376 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007377 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007378 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007379 which = 1;
7380 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007381 which = 2;
7382 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007383
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007384 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007385 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007386 << *Cand->DeductionFailure.getFirstArg()
7387 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007388 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007389 return;
7390 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007391
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007392 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007393 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007394 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007395 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007396 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7397 << ParamD->getDeclName();
7398 else {
7399 int index = 0;
7400 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7401 index = TTP->getIndex();
7402 else if (NonTypeTemplateParmDecl *NTTP
7403 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7404 index = NTTP->getIndex();
7405 else
7406 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007407 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007408 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7409 << (index + 1);
7410 }
Sebastian Redl08905022011-02-05 19:23:19 +00007411 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007412 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007413
Douglas Gregor02eb4832010-05-08 18:13:28 +00007414 case Sema::TDK_TooManyArguments:
7415 case Sema::TDK_TooFewArguments:
7416 DiagnoseArityMismatch(S, Cand, NumArgs);
7417 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007418
7419 case Sema::TDK_InstantiationDepth:
7420 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007421 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007422 return;
7423
7424 case Sema::TDK_SubstitutionFailure: {
7425 std::string ArgString;
7426 if (TemplateArgumentList *Args
7427 = Cand->DeductionFailure.getTemplateArgumentList())
7428 ArgString = S.getTemplateArgumentBindingsText(
7429 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7430 *Args);
7431 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7432 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007433 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007434 return;
7435 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007436
John McCall8b9ed552010-02-01 18:53:26 +00007437 // TODO: diagnose these individually, then kill off
7438 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007439 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007440 case Sema::TDK_FailedOverloadResolution:
7441 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007442 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007443 return;
7444 }
7445}
7446
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007447/// CUDA: diagnose an invalid call across targets.
7448void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7449 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7450 FunctionDecl *Callee = Cand->Function;
7451
7452 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7453 CalleeTarget = S.IdentifyCUDATarget(Callee);
7454
7455 std::string FnDesc;
7456 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7457
7458 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7459 << (unsigned) FnKind << CalleeTarget << CallerTarget;
7460}
7461
John McCall8b9ed552010-02-01 18:53:26 +00007462/// Generates a 'note' diagnostic for an overload candidate. We've
7463/// already generated a primary error at the call site.
7464///
7465/// It really does need to be a single diagnostic with its caret
7466/// pointed at the candidate declaration. Yes, this creates some
7467/// major challenges of technical writing. Yes, this makes pointing
7468/// out problems with specific arguments quite awkward. It's still
7469/// better than generating twenty screens of text for every failed
7470/// overload.
7471///
7472/// It would be great to be able to express per-candidate problems
7473/// more richly for those diagnostic clients that cared, but we'd
7474/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007475void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7476 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007477 FunctionDecl *Fn = Cand->Function;
7478
John McCall12f97bc2010-01-08 04:41:39 +00007479 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007480 if (Cand->Viable && (Fn->isDeleted() ||
7481 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007482 std::string FnDesc;
7483 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007484
7485 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007486 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007487 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007488 return;
John McCall12f97bc2010-01-08 04:41:39 +00007489 }
7490
John McCalle1ac8d12010-01-13 00:25:19 +00007491 // We don't really have anything else to say about viable candidates.
7492 if (Cand->Viable) {
7493 S.NoteOverloadCandidate(Fn);
7494 return;
7495 }
John McCall0d1da222010-01-12 00:44:57 +00007496
John McCall6a61b522010-01-13 09:16:55 +00007497 switch (Cand->FailureKind) {
7498 case ovl_fail_too_many_arguments:
7499 case ovl_fail_too_few_arguments:
7500 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007501
John McCall6a61b522010-01-13 09:16:55 +00007502 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007503 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7504
John McCallfe796dd2010-01-23 05:17:32 +00007505 case ovl_fail_trivial_conversion:
7506 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007507 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007508 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007509
John McCall65eb8792010-02-25 01:37:24 +00007510 case ovl_fail_bad_conversion: {
7511 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7512 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007513 if (Cand->Conversions[I].isBad())
7514 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007515
John McCall6a61b522010-01-13 09:16:55 +00007516 // FIXME: this currently happens when we're called from SemaInit
7517 // when user-conversion overload fails. Figure out how to handle
7518 // those conditions and diagnose them well.
7519 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007520 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007521
7522 case ovl_fail_bad_target:
7523 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00007524 }
John McCalld3224162010-01-08 00:58:21 +00007525}
7526
7527void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7528 // Desugar the type of the surrogate down to a function type,
7529 // retaining as many typedefs as possible while still showing
7530 // the function type (and, therefore, its parameter types).
7531 QualType FnType = Cand->Surrogate->getConversionType();
7532 bool isLValueReference = false;
7533 bool isRValueReference = false;
7534 bool isPointer = false;
7535 if (const LValueReferenceType *FnTypeRef =
7536 FnType->getAs<LValueReferenceType>()) {
7537 FnType = FnTypeRef->getPointeeType();
7538 isLValueReference = true;
7539 } else if (const RValueReferenceType *FnTypeRef =
7540 FnType->getAs<RValueReferenceType>()) {
7541 FnType = FnTypeRef->getPointeeType();
7542 isRValueReference = true;
7543 }
7544 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7545 FnType = FnTypePtr->getPointeeType();
7546 isPointer = true;
7547 }
7548 // Desugar down to a function type.
7549 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7550 // Reconstruct the pointer/reference as appropriate.
7551 if (isPointer) FnType = S.Context.getPointerType(FnType);
7552 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7553 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7554
7555 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7556 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007557 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007558}
7559
7560void NoteBuiltinOperatorCandidate(Sema &S,
7561 const char *Opc,
7562 SourceLocation OpLoc,
7563 OverloadCandidate *Cand) {
7564 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7565 std::string TypeStr("operator");
7566 TypeStr += Opc;
7567 TypeStr += "(";
7568 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7569 if (Cand->Conversions.size() == 1) {
7570 TypeStr += ")";
7571 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7572 } else {
7573 TypeStr += ", ";
7574 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7575 TypeStr += ")";
7576 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7577 }
7578}
7579
7580void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7581 OverloadCandidate *Cand) {
7582 unsigned NoOperands = Cand->Conversions.size();
7583 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7584 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007585 if (ICS.isBad()) break; // all meaningless after first invalid
7586 if (!ICS.isAmbiguous()) continue;
7587
John McCall5c32be02010-08-24 20:38:10 +00007588 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007589 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007590 }
7591}
7592
John McCall3712d9e2010-01-15 23:32:50 +00007593SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7594 if (Cand->Function)
7595 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007596 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007597 return Cand->Surrogate->getLocation();
7598 return SourceLocation();
7599}
7600
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007601static unsigned
7602RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00007603 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007604 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00007605 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007606
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007607 case Sema::TDK_Incomplete:
7608 return 1;
7609
7610 case Sema::TDK_Underqualified:
7611 case Sema::TDK_Inconsistent:
7612 return 2;
7613
7614 case Sema::TDK_SubstitutionFailure:
7615 case Sema::TDK_NonDeducedMismatch:
7616 return 3;
7617
7618 case Sema::TDK_InstantiationDepth:
7619 case Sema::TDK_FailedOverloadResolution:
7620 return 4;
7621
7622 case Sema::TDK_InvalidExplicitArguments:
7623 return 5;
7624
7625 case Sema::TDK_TooManyArguments:
7626 case Sema::TDK_TooFewArguments:
7627 return 6;
7628 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007629 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007630}
7631
John McCallad2587a2010-01-12 00:48:53 +00007632struct CompareOverloadCandidatesForDisplay {
7633 Sema &S;
7634 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007635
7636 bool operator()(const OverloadCandidate *L,
7637 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007638 // Fast-path this check.
7639 if (L == R) return false;
7640
John McCall12f97bc2010-01-08 04:41:39 +00007641 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007642 if (L->Viable) {
7643 if (!R->Viable) return true;
7644
7645 // TODO: introduce a tri-valued comparison for overload
7646 // candidates. Would be more worthwhile if we had a sort
7647 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007648 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7649 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007650 } else if (R->Viable)
7651 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007652
John McCall3712d9e2010-01-15 23:32:50 +00007653 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007654
John McCall3712d9e2010-01-15 23:32:50 +00007655 // Criteria by which we can sort non-viable candidates:
7656 if (!L->Viable) {
7657 // 1. Arity mismatches come after other candidates.
7658 if (L->FailureKind == ovl_fail_too_many_arguments ||
7659 L->FailureKind == ovl_fail_too_few_arguments)
7660 return false;
7661 if (R->FailureKind == ovl_fail_too_many_arguments ||
7662 R->FailureKind == ovl_fail_too_few_arguments)
7663 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007664
John McCallfe796dd2010-01-23 05:17:32 +00007665 // 2. Bad conversions come first and are ordered by the number
7666 // of bad conversions and quality of good conversions.
7667 if (L->FailureKind == ovl_fail_bad_conversion) {
7668 if (R->FailureKind != ovl_fail_bad_conversion)
7669 return true;
7670
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007671 // The conversion that can be fixed with a smaller number of changes,
7672 // comes first.
7673 unsigned numLFixes = L->Fix.NumConversionsFixed;
7674 unsigned numRFixes = R->Fix.NumConversionsFixed;
7675 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7676 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007677 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007678 if (numLFixes < numRFixes)
7679 return true;
7680 else
7681 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007682 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007683
John McCallfe796dd2010-01-23 05:17:32 +00007684 // If there's any ordering between the defined conversions...
7685 // FIXME: this might not be transitive.
7686 assert(L->Conversions.size() == R->Conversions.size());
7687
7688 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007689 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7690 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007691 switch (CompareImplicitConversionSequences(S,
7692 L->Conversions[I],
7693 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007694 case ImplicitConversionSequence::Better:
7695 leftBetter++;
7696 break;
7697
7698 case ImplicitConversionSequence::Worse:
7699 leftBetter--;
7700 break;
7701
7702 case ImplicitConversionSequence::Indistinguishable:
7703 break;
7704 }
7705 }
7706 if (leftBetter > 0) return true;
7707 if (leftBetter < 0) return false;
7708
7709 } else if (R->FailureKind == ovl_fail_bad_conversion)
7710 return false;
7711
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007712 if (L->FailureKind == ovl_fail_bad_deduction) {
7713 if (R->FailureKind != ovl_fail_bad_deduction)
7714 return true;
7715
7716 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7717 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00007718 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00007719 } else if (R->FailureKind == ovl_fail_bad_deduction)
7720 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007721
John McCall3712d9e2010-01-15 23:32:50 +00007722 // TODO: others?
7723 }
7724
7725 // Sort everything else by location.
7726 SourceLocation LLoc = GetLocationForCandidate(L);
7727 SourceLocation RLoc = GetLocationForCandidate(R);
7728
7729 // Put candidates without locations (e.g. builtins) at the end.
7730 if (LLoc.isInvalid()) return false;
7731 if (RLoc.isInvalid()) return true;
7732
7733 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007734 }
7735};
7736
John McCallfe796dd2010-01-23 05:17:32 +00007737/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007738/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00007739void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7740 Expr **Args, unsigned NumArgs) {
7741 assert(!Cand->Viable);
7742
7743 // Don't do anything on failures other than bad conversion.
7744 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7745
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007746 // We only want the FixIts if all the arguments can be corrected.
7747 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00007748 // Use a implicit copy initialization to check conversion fixes.
7749 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007750
John McCallfe796dd2010-01-23 05:17:32 +00007751 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007752 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007753 unsigned ConvCount = Cand->Conversions.size();
7754 while (true) {
7755 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7756 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007757 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00007758 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00007759 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007760 }
John McCallfe796dd2010-01-23 05:17:32 +00007761 }
7762
7763 if (ConvIdx == ConvCount)
7764 return;
7765
John McCall65eb8792010-02-25 01:37:24 +00007766 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7767 "remaining conversion is initialized?");
7768
Douglas Gregoradc7a702010-04-16 17:45:54 +00007769 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007770 // operation somehow.
7771 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007772
7773 const FunctionProtoType* Proto;
7774 unsigned ArgIdx = ConvIdx;
7775
7776 if (Cand->IsSurrogate) {
7777 QualType ConvType
7778 = Cand->Surrogate->getConversionType().getNonReferenceType();
7779 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7780 ConvType = ConvPtrType->getPointeeType();
7781 Proto = ConvType->getAs<FunctionProtoType>();
7782 ArgIdx--;
7783 } else if (Cand->Function) {
7784 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7785 if (isa<CXXMethodDecl>(Cand->Function) &&
7786 !isa<CXXConstructorDecl>(Cand->Function))
7787 ArgIdx--;
7788 } else {
7789 // Builtin binary operator with a bad first conversion.
7790 assert(ConvCount <= 3);
7791 for (; ConvIdx != ConvCount; ++ConvIdx)
7792 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007793 = TryCopyInitialization(S, Args[ConvIdx],
7794 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007795 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007796 /*InOverloadResolution*/ true,
7797 /*AllowObjCWritebackConversion=*/
7798 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00007799 return;
7800 }
7801
7802 // Fill in the rest of the conversions.
7803 unsigned NumArgsInProto = Proto->getNumArgs();
7804 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007805 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00007806 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007807 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007808 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007809 /*InOverloadResolution=*/true,
7810 /*AllowObjCWritebackConversion=*/
7811 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007812 // Store the FixIt in the candidate if it exists.
7813 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00007814 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007815 }
John McCallfe796dd2010-01-23 05:17:32 +00007816 else
7817 Cand->Conversions[ConvIdx].setEllipsis();
7818 }
7819}
7820
John McCalld3224162010-01-08 00:58:21 +00007821} // end anonymous namespace
7822
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007823/// PrintOverloadCandidates - When overload resolution fails, prints
7824/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007825/// set.
John McCall5c32be02010-08-24 20:38:10 +00007826void OverloadCandidateSet::NoteCandidates(Sema &S,
7827 OverloadCandidateDisplayKind OCD,
7828 Expr **Args, unsigned NumArgs,
7829 const char *Opc,
7830 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007831 // Sort the candidates by viability and position. Sorting directly would
7832 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007833 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007834 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7835 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007836 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007837 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007838 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007839 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007840 if (Cand->Function || Cand->IsSurrogate)
7841 Cands.push_back(Cand);
7842 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7843 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007844 }
7845 }
7846
John McCallad2587a2010-01-12 00:48:53 +00007847 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007848 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007849
John McCall0d1da222010-01-12 00:44:57 +00007850 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007851
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007852 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00007853 const DiagnosticsEngine::OverloadsShown ShowOverloads =
7854 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007855 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007856 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7857 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007858
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007859 // Set an arbitrary limit on the number of candidate functions we'll spam
7860 // the user with. FIXME: This limit should depend on details of the
7861 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00007862 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007863 break;
7864 }
7865 ++CandsShown;
7866
John McCalld3224162010-01-08 00:58:21 +00007867 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007868 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007869 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007870 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007871 else {
7872 assert(Cand->Viable &&
7873 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007874 // Generally we only see ambiguities including viable builtin
7875 // operators if overload resolution got screwed up by an
7876 // ambiguous user-defined conversion.
7877 //
7878 // FIXME: It's quite possible for different conversions to see
7879 // different ambiguities, though.
7880 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007881 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007882 ReportedAmbiguousConversions = true;
7883 }
John McCalld3224162010-01-08 00:58:21 +00007884
John McCall0d1da222010-01-12 00:44:57 +00007885 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007886 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007887 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007888 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007889
7890 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007891 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007892}
7893
Douglas Gregorb491ed32011-02-19 21:32:49 +00007894// [PossiblyAFunctionType] --> [Return]
7895// NonFunctionType --> NonFunctionType
7896// R (A) --> R(A)
7897// R (*)(A) --> R (A)
7898// R (&)(A) --> R (A)
7899// R (S::*)(A) --> R (A)
7900QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7901 QualType Ret = PossiblyAFunctionType;
7902 if (const PointerType *ToTypePtr =
7903 PossiblyAFunctionType->getAs<PointerType>())
7904 Ret = ToTypePtr->getPointeeType();
7905 else if (const ReferenceType *ToTypeRef =
7906 PossiblyAFunctionType->getAs<ReferenceType>())
7907 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007908 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007909 PossiblyAFunctionType->getAs<MemberPointerType>())
7910 Ret = MemTypePtr->getPointeeType();
7911 Ret =
7912 Context.getCanonicalType(Ret).getUnqualifiedType();
7913 return Ret;
7914}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007915
Douglas Gregorb491ed32011-02-19 21:32:49 +00007916// A helper class to help with address of function resolution
7917// - allows us to avoid passing around all those ugly parameters
7918class AddressOfFunctionResolver
7919{
7920 Sema& S;
7921 Expr* SourceExpr;
7922 const QualType& TargetType;
7923 QualType TargetFunctionType; // Extracted function type from target type
7924
7925 bool Complain;
7926 //DeclAccessPair& ResultFunctionAccessPair;
7927 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007928
Douglas Gregorb491ed32011-02-19 21:32:49 +00007929 bool TargetTypeIsNonStaticMemberFunction;
7930 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007931
Douglas Gregorb491ed32011-02-19 21:32:49 +00007932 OverloadExpr::FindResult OvlExprInfo;
7933 OverloadExpr *OvlExpr;
7934 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007935 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007936
Douglas Gregorb491ed32011-02-19 21:32:49 +00007937public:
7938 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7939 const QualType& TargetType, bool Complain)
7940 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7941 Complain(Complain), Context(S.getASTContext()),
7942 TargetTypeIsNonStaticMemberFunction(
7943 !!TargetType->getAs<MemberPointerType>()),
7944 FoundNonTemplateFunction(false),
7945 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7946 OvlExpr(OvlExprInfo.Expression)
7947 {
7948 ExtractUnqualifiedFunctionTypeFromTargetType();
7949
7950 if (!TargetFunctionType->isFunctionType()) {
7951 if (OvlExpr->hasExplicitTemplateArgs()) {
7952 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00007953 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00007954 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00007955
7956 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7957 if (!Method->isStatic()) {
7958 // If the target type is a non-function type and the function
7959 // found is a non-static member function, pretend as if that was
7960 // the target, it's the only possible type to end up with.
7961 TargetTypeIsNonStaticMemberFunction = true;
7962
7963 // And skip adding the function if its not in the proper form.
7964 // We'll diagnose this due to an empty set of functions.
7965 if (!OvlExprInfo.HasFormOfMemberPointer)
7966 return;
7967 }
7968 }
7969
Douglas Gregorb491ed32011-02-19 21:32:49 +00007970 Matches.push_back(std::make_pair(dap,Fn));
7971 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007972 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007973 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007974 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007975
7976 if (OvlExpr->hasExplicitTemplateArgs())
7977 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007978
Douglas Gregorb491ed32011-02-19 21:32:49 +00007979 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7980 // C++ [over.over]p4:
7981 // If more than one function is selected, [...]
7982 if (Matches.size() > 1) {
7983 if (FoundNonTemplateFunction)
7984 EliminateAllTemplateMatches();
7985 else
7986 EliminateAllExceptMostSpecializedTemplate();
7987 }
7988 }
7989 }
7990
7991private:
7992 bool isTargetTypeAFunction() const {
7993 return TargetFunctionType->isFunctionType();
7994 }
7995
7996 // [ToType] [Return]
7997
7998 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7999 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8000 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8001 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8002 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8003 }
8004
8005 // return true if any matching specializations were found
8006 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8007 const DeclAccessPair& CurAccessFunPair) {
8008 if (CXXMethodDecl *Method
8009 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8010 // Skip non-static function templates when converting to pointer, and
8011 // static when converting to member pointer.
8012 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8013 return false;
8014 }
8015 else if (TargetTypeIsNonStaticMemberFunction)
8016 return false;
8017
8018 // C++ [over.over]p2:
8019 // If the name is a function template, template argument deduction is
8020 // done (14.8.2.2), and if the argument deduction succeeds, the
8021 // resulting template argument list is used to generate a single
8022 // function template specialization, which is added to the set of
8023 // overloaded functions considered.
8024 FunctionDecl *Specialization = 0;
8025 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8026 if (Sema::TemplateDeductionResult Result
8027 = S.DeduceTemplateArguments(FunctionTemplate,
8028 &OvlExplicitTemplateArgs,
8029 TargetFunctionType, Specialization,
8030 Info)) {
8031 // FIXME: make a note of the failed deduction for diagnostics.
8032 (void)Result;
8033 return false;
8034 }
8035
8036 // Template argument deduction ensures that we have an exact match.
8037 // This function template specicalization works.
8038 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8039 assert(TargetFunctionType
8040 == Context.getCanonicalType(Specialization->getType()));
8041 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8042 return true;
8043 }
8044
8045 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8046 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008047 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008048 // Skip non-static functions when converting to pointer, and static
8049 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008050 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8051 return false;
8052 }
8053 else if (TargetTypeIsNonStaticMemberFunction)
8054 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008055
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008056 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008057 if (S.getLangOptions().CUDA)
8058 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8059 if (S.CheckCUDATarget(Caller, FunDecl))
8060 return false;
8061
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008062 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008063 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8064 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008065 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8066 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008067 Matches.push_back(std::make_pair(CurAccessFunPair,
8068 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008069 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008070 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008071 }
Mike Stump11289f42009-09-09 15:08:12 +00008072 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008073
8074 return false;
8075 }
8076
8077 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8078 bool Ret = false;
8079
8080 // If the overload expression doesn't have the form of a pointer to
8081 // member, don't try to convert it to a pointer-to-member type.
8082 if (IsInvalidFormOfPointerToMemberFunction())
8083 return false;
8084
8085 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8086 E = OvlExpr->decls_end();
8087 I != E; ++I) {
8088 // Look through any using declarations to find the underlying function.
8089 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8090
8091 // C++ [over.over]p3:
8092 // Non-member functions and static member functions match
8093 // targets of type "pointer-to-function" or "reference-to-function."
8094 // Nonstatic member functions match targets of
8095 // type "pointer-to-member-function."
8096 // Note that according to DR 247, the containing class does not matter.
8097 if (FunctionTemplateDecl *FunctionTemplate
8098 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8099 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8100 Ret = true;
8101 }
8102 // If we have explicit template arguments supplied, skip non-templates.
8103 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8104 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8105 Ret = true;
8106 }
8107 assert(Ret || Matches.empty());
8108 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008109 }
8110
Douglas Gregorb491ed32011-02-19 21:32:49 +00008111 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008112 // [...] and any given function template specialization F1 is
8113 // eliminated if the set contains a second function template
8114 // specialization whose function template is more specialized
8115 // than the function template of F1 according to the partial
8116 // ordering rules of 14.5.5.2.
8117
8118 // The algorithm specified above is quadratic. We instead use a
8119 // two-pass algorithm (similar to the one used to identify the
8120 // best viable function in an overload set) that identifies the
8121 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008122
8123 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8124 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8125 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008126
John McCall58cc69d2010-01-27 01:50:18 +00008127 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008128 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8129 TPOC_Other, 0, SourceExpr->getLocStart(),
8130 S.PDiag(),
8131 S.PDiag(diag::err_addr_ovl_ambiguous)
8132 << Matches[0].second->getDeclName(),
8133 S.PDiag(diag::note_ovl_candidate)
8134 << (unsigned) oc_function_template,
8135 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008136
Douglas Gregorb491ed32011-02-19 21:32:49 +00008137 if (Result != MatchesCopy.end()) {
8138 // Make it the first and only element
8139 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8140 Matches[0].second = cast<FunctionDecl>(*Result);
8141 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008142 }
8143 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008144
Douglas Gregorb491ed32011-02-19 21:32:49 +00008145 void EliminateAllTemplateMatches() {
8146 // [...] any function template specializations in the set are
8147 // eliminated if the set also contains a non-template function, [...]
8148 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8149 if (Matches[I].second->getPrimaryTemplate() == 0)
8150 ++I;
8151 else {
8152 Matches[I] = Matches[--N];
8153 Matches.set_size(N);
8154 }
8155 }
8156 }
8157
8158public:
8159 void ComplainNoMatchesFound() const {
8160 assert(Matches.empty());
8161 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8162 << OvlExpr->getName() << TargetFunctionType
8163 << OvlExpr->getSourceRange();
8164 S.NoteAllOverloadCandidates(OvlExpr);
8165 }
8166
8167 bool IsInvalidFormOfPointerToMemberFunction() const {
8168 return TargetTypeIsNonStaticMemberFunction &&
8169 !OvlExprInfo.HasFormOfMemberPointer;
8170 }
8171
8172 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8173 // TODO: Should we condition this on whether any functions might
8174 // have matched, or is it more appropriate to do that in callers?
8175 // TODO: a fixit wouldn't hurt.
8176 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8177 << TargetType << OvlExpr->getSourceRange();
8178 }
8179
8180 void ComplainOfInvalidConversion() const {
8181 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8182 << OvlExpr->getName() << TargetType;
8183 }
8184
8185 void ComplainMultipleMatchesFound() const {
8186 assert(Matches.size() > 1);
8187 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8188 << OvlExpr->getName()
8189 << OvlExpr->getSourceRange();
8190 S.NoteAllOverloadCandidates(OvlExpr);
8191 }
8192
8193 int getNumMatches() const { return Matches.size(); }
8194
8195 FunctionDecl* getMatchingFunctionDecl() const {
8196 if (Matches.size() != 1) return 0;
8197 return Matches[0].second;
8198 }
8199
8200 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8201 if (Matches.size() != 1) return 0;
8202 return &Matches[0].first;
8203 }
8204};
8205
8206/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8207/// an overloaded function (C++ [over.over]), where @p From is an
8208/// expression with overloaded function type and @p ToType is the type
8209/// we're trying to resolve to. For example:
8210///
8211/// @code
8212/// int f(double);
8213/// int f(int);
8214///
8215/// int (*pfd)(double) = f; // selects f(double)
8216/// @endcode
8217///
8218/// This routine returns the resulting FunctionDecl if it could be
8219/// resolved, and NULL otherwise. When @p Complain is true, this
8220/// routine will emit diagnostics if there is an error.
8221FunctionDecl *
8222Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
8223 bool Complain,
8224 DeclAccessPair &FoundResult) {
8225
8226 assert(AddressOfExpr->getType() == Context.OverloadTy);
8227
8228 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
8229 int NumMatches = Resolver.getNumMatches();
8230 FunctionDecl* Fn = 0;
8231 if ( NumMatches == 0 && Complain) {
8232 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8233 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8234 else
8235 Resolver.ComplainNoMatchesFound();
8236 }
8237 else if (NumMatches > 1 && Complain)
8238 Resolver.ComplainMultipleMatchesFound();
8239 else if (NumMatches == 1) {
8240 Fn = Resolver.getMatchingFunctionDecl();
8241 assert(Fn);
8242 FoundResult = *Resolver.getMatchingFunctionAccessPair();
8243 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00008244 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00008245 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00008246 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008247
8248 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008249}
8250
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008251/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008252/// resolve that overloaded function expression down to a single function.
8253///
8254/// This routine can only resolve template-ids that refer to a single function
8255/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008256/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008257/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00008258FunctionDecl *
8259Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8260 bool Complain,
8261 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008262 // C++ [over.over]p1:
8263 // [...] [Note: any redundant set of parentheses surrounding the
8264 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008265 // C++ [over.over]p1:
8266 // [...] The overloaded function name can be preceded by the &
8267 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008268
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008269 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00008270 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008271 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00008272
8273 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00008274 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008275
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008276 // Look through all of the overloaded functions, searching for one
8277 // whose type matches exactly.
8278 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008279 for (UnresolvedSetIterator I = ovl->decls_begin(),
8280 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008281 // C++0x [temp.arg.explicit]p3:
8282 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008283 // where deduction is not done, if a template argument list is
8284 // specified and it, along with any default template arguments,
8285 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008286 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00008287 FunctionTemplateDecl *FunctionTemplate
8288 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008289
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008290 // C++ [over.over]p2:
8291 // If the name is a function template, template argument deduction is
8292 // done (14.8.2.2), and if the argument deduction succeeds, the
8293 // resulting template argument list is used to generate a single
8294 // function template specialization, which is added to the set of
8295 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008296 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008297 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008298 if (TemplateDeductionResult Result
8299 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8300 Specialization, Info)) {
8301 // FIXME: make a note of the failed deduction for diagnostics.
8302 (void)Result;
8303 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008304 }
8305
John McCall0009fcc2011-04-26 20:42:42 +00008306 assert(Specialization && "no specialization and no error?");
8307
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008308 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008309 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008310 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00008311 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8312 << ovl->getName();
8313 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008314 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008315 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00008316 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008317
John McCall0009fcc2011-04-26 20:42:42 +00008318 Matched = Specialization;
8319 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008320 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008321
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008322 return Matched;
8323}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008324
Douglas Gregor1beec452011-03-12 01:48:56 +00008325
8326
8327
John McCall50a2c2c2011-10-11 23:14:30 +00008328// Resolve and fix an overloaded expression that can be resolved
8329// because it identifies a single function template specialization.
8330//
Douglas Gregor1beec452011-03-12 01:48:56 +00008331// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00008332//
8333// Return true if it was logically possible to so resolve the
8334// expression, regardless of whether or not it succeeded. Always
8335// returns true if 'complain' is set.
8336bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8337 ExprResult &SrcExpr, bool doFunctionPointerConverion,
8338 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00008339 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00008340 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00008341 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00008342
John McCall50a2c2c2011-10-11 23:14:30 +00008343 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00008344
John McCall0009fcc2011-04-26 20:42:42 +00008345 DeclAccessPair found;
8346 ExprResult SingleFunctionExpression;
8347 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8348 ovl.Expression, /*complain*/ false, &found)) {
John McCall50a2c2c2011-10-11 23:14:30 +00008349 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8350 SrcExpr = ExprError();
8351 return true;
8352 }
John McCall0009fcc2011-04-26 20:42:42 +00008353
8354 // It is only correct to resolve to an instance method if we're
8355 // resolving a form that's permitted to be a pointer to member.
8356 // Otherwise we'll end up making a bound member expression, which
8357 // is illegal in all the contexts we resolve like this.
8358 if (!ovl.HasFormOfMemberPointer &&
8359 isa<CXXMethodDecl>(fn) &&
8360 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00008361 if (!complain) return false;
8362
8363 Diag(ovl.Expression->getExprLoc(),
8364 diag::err_bound_member_function)
8365 << 0 << ovl.Expression->getSourceRange();
8366
8367 // TODO: I believe we only end up here if there's a mix of
8368 // static and non-static candidates (otherwise the expression
8369 // would have 'bound member' type, not 'overload' type).
8370 // Ideally we would note which candidate was chosen and why
8371 // the static candidates were rejected.
8372 SrcExpr = ExprError();
8373 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008374 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008375
John McCall0009fcc2011-04-26 20:42:42 +00008376 // Fix the expresion to refer to 'fn'.
8377 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00008378 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00008379
8380 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00008381 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00008382 SingleFunctionExpression =
8383 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00008384 if (SingleFunctionExpression.isInvalid()) {
8385 SrcExpr = ExprError();
8386 return true;
8387 }
8388 }
John McCall0009fcc2011-04-26 20:42:42 +00008389 }
8390
8391 if (!SingleFunctionExpression.isUsable()) {
8392 if (complain) {
8393 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8394 << ovl.Expression->getName()
8395 << DestTypeForComplaining
8396 << OpRangeForComplaining
8397 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00008398 NoteAllOverloadCandidates(SrcExpr.get());
8399
8400 SrcExpr = ExprError();
8401 return true;
8402 }
8403
8404 return false;
John McCall0009fcc2011-04-26 20:42:42 +00008405 }
8406
John McCall50a2c2c2011-10-11 23:14:30 +00008407 SrcExpr = SingleFunctionExpression;
8408 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008409}
8410
Douglas Gregorcabea402009-09-22 15:41:20 +00008411/// \brief Add a single candidate to the overload set.
8412static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00008413 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008414 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008415 Expr **Args, unsigned NumArgs,
8416 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008417 bool PartialOverloading,
8418 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00008419 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00008420 if (isa<UsingShadowDecl>(Callee))
8421 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8422
Douglas Gregorcabea402009-09-22 15:41:20 +00008423 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00008424 if (ExplicitTemplateArgs) {
8425 assert(!KnownValid && "Explicit template arguments?");
8426 return;
8427 }
John McCalla0296f72010-03-19 07:35:19 +00008428 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00008429 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008430 return;
John McCalld14a8642009-11-21 08:51:07 +00008431 }
8432
8433 if (FunctionTemplateDecl *FuncTemplate
8434 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00008435 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8436 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00008437 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00008438 return;
8439 }
8440
Richard Smith95ce4f62011-06-26 22:19:54 +00008441 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00008442}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008443
Douglas Gregorcabea402009-09-22 15:41:20 +00008444/// \brief Add the overload candidates named by callee and/or found by argument
8445/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00008446void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00008447 Expr **Args, unsigned NumArgs,
8448 OverloadCandidateSet &CandidateSet,
8449 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00008450
8451#ifndef NDEBUG
8452 // Verify that ArgumentDependentLookup is consistent with the rules
8453 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00008454 //
Douglas Gregorcabea402009-09-22 15:41:20 +00008455 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8456 // and let Y be the lookup set produced by argument dependent
8457 // lookup (defined as follows). If X contains
8458 //
8459 // -- a declaration of a class member, or
8460 //
8461 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00008462 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00008463 //
8464 // -- a declaration that is neither a function or a function
8465 // template
8466 //
8467 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00008468
John McCall57500772009-12-16 12:17:52 +00008469 if (ULE->requiresADL()) {
8470 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8471 E = ULE->decls_end(); I != E; ++I) {
8472 assert(!(*I)->getDeclContext()->isRecord());
8473 assert(isa<UsingShadowDecl>(*I) ||
8474 !(*I)->getDeclContext()->isFunctionOrMethod());
8475 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008476 }
8477 }
8478#endif
8479
John McCall57500772009-12-16 12:17:52 +00008480 // It would be nice to avoid this copy.
8481 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008482 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008483 if (ULE->hasExplicitTemplateArgs()) {
8484 ULE->copyTemplateArgumentsInto(TABuffer);
8485 ExplicitTemplateArgs = &TABuffer;
8486 }
8487
8488 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8489 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008490 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008491 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008492 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008493
John McCall57500772009-12-16 12:17:52 +00008494 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008495 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8496 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008497 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008498 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008499 PartialOverloading,
8500 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008501}
John McCalld681c392009-12-16 08:11:27 +00008502
Richard Smith998a5912011-06-05 22:42:48 +00008503/// Attempt to recover from an ill-formed use of a non-dependent name in a
8504/// template, where the non-dependent name was declared after the template
8505/// was defined. This is common in code written for a compilers which do not
8506/// correctly implement two-stage name lookup.
8507///
8508/// Returns true if a viable candidate was found and a diagnostic was issued.
8509static bool
8510DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8511 const CXXScopeSpec &SS, LookupResult &R,
8512 TemplateArgumentListInfo *ExplicitTemplateArgs,
8513 Expr **Args, unsigned NumArgs) {
8514 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8515 return false;
8516
8517 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8518 SemaRef.LookupQualifiedName(R, DC);
8519
8520 if (!R.empty()) {
8521 R.suppressDiagnostics();
8522
8523 if (isa<CXXRecordDecl>(DC)) {
8524 // Don't diagnose names we find in classes; we get much better
8525 // diagnostics for these from DiagnoseEmptyLookup.
8526 R.clear();
8527 return false;
8528 }
8529
8530 OverloadCandidateSet Candidates(FnLoc);
8531 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8532 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8533 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008534 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008535
8536 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008537 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008538 // No viable functions. Don't bother the user with notes for functions
8539 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008540 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008541 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008542 }
Richard Smith998a5912011-06-05 22:42:48 +00008543
8544 // Find the namespaces where ADL would have looked, and suggest
8545 // declaring the function there instead.
8546 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8547 Sema::AssociatedClassSet AssociatedClasses;
8548 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8549 AssociatedNamespaces,
8550 AssociatedClasses);
8551 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008552 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008553 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008554 for (Sema::AssociatedNamespaceSet::iterator
8555 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008556 end = AssociatedNamespaces.end(); it != end; ++it) {
8557 if (!Std->Encloses(*it))
8558 SuggestedNamespaces.insert(*it);
8559 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008560 } else {
8561 // Lacking the 'std::' namespace, use all of the associated namespaces.
8562 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008563 }
8564
8565 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8566 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008567 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008568 SemaRef.Diag(Best->Function->getLocation(),
8569 diag::note_not_found_by_two_phase_lookup)
8570 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008571 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008572 SemaRef.Diag(Best->Function->getLocation(),
8573 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008574 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008575 } else {
8576 // FIXME: It would be useful to list the associated namespaces here,
8577 // but the diagnostics infrastructure doesn't provide a way to produce
8578 // a localized representation of a list of items.
8579 SemaRef.Diag(Best->Function->getLocation(),
8580 diag::note_not_found_by_two_phase_lookup)
8581 << R.getLookupName() << 2;
8582 }
8583
8584 // Try to recover by calling this function.
8585 return true;
8586 }
8587
8588 R.clear();
8589 }
8590
8591 return false;
8592}
8593
8594/// Attempt to recover from ill-formed use of a non-dependent operator in a
8595/// template, where the non-dependent operator was declared after the template
8596/// was defined.
8597///
8598/// Returns true if a viable candidate was found and a diagnostic was issued.
8599static bool
8600DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8601 SourceLocation OpLoc,
8602 Expr **Args, unsigned NumArgs) {
8603 DeclarationName OpName =
8604 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8605 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8606 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8607 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8608}
8609
John McCalld681c392009-12-16 08:11:27 +00008610/// Attempts to recover from a call where no functions were found.
8611///
8612/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008613static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008614BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008615 UnresolvedLookupExpr *ULE,
8616 SourceLocation LParenLoc,
8617 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008618 SourceLocation RParenLoc,
8619 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008620
8621 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008622 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008623
John McCall57500772009-12-16 12:17:52 +00008624 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008625 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008626 if (ULE->hasExplicitTemplateArgs()) {
8627 ULE->copyTemplateArgumentsInto(TABuffer);
8628 ExplicitTemplateArgs = &TABuffer;
8629 }
8630
John McCalld681c392009-12-16 08:11:27 +00008631 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8632 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008633 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8634 ExplicitTemplateArgs, Args, NumArgs) &&
8635 (!EmptyLookup ||
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00008636 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00008637 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00008638 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008639
John McCall57500772009-12-16 12:17:52 +00008640 assert(!R.empty() && "lookup results empty despite recovery");
8641
8642 // Build an implicit member call if appropriate. Just drop the
8643 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008644 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008645 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008646 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8647 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008648 else if (ExplicitTemplateArgs)
8649 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8650 else
8651 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8652
8653 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008654 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008655
8656 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008657 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008658 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008659 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008660 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008661}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008662
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008663/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008664/// (which eventually refers to the declaration Func) and the call
8665/// arguments Args/NumArgs, attempt to resolve the function call down
8666/// to a specific function. If overload resolution succeeds, returns
8667/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008668/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008669/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008670ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008671Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008672 SourceLocation LParenLoc,
8673 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008674 SourceLocation RParenLoc,
8675 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008676#ifndef NDEBUG
8677 if (ULE->requiresADL()) {
8678 // To do ADL, we must have found an unqualified name.
8679 assert(!ULE->getQualifier() && "qualified name with ADL");
8680
8681 // We don't perform ADL for implicit declarations of builtins.
8682 // Verify that this was correctly set up.
8683 FunctionDecl *F;
8684 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8685 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8686 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00008687 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008688
John McCall57500772009-12-16 12:17:52 +00008689 // We don't perform ADL in C.
8690 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008691 } else
8692 assert(!ULE->isStdAssociatedNamespace() &&
8693 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008694#endif
8695
John McCall4124c492011-10-17 18:40:02 +00008696 UnbridgedCastsSet UnbridgedCasts;
8697 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
8698 return ExprError();
8699
John McCallbc077cf2010-02-08 23:07:23 +00008700 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008701
John McCall57500772009-12-16 12:17:52 +00008702 // Add the functions denoted by the callee to the set of candidate
8703 // functions, including those from argument-dependent lookup.
8704 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008705
8706 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008707 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8708 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00008709 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008710 // In Microsoft mode, if we are inside a template class member function then
8711 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00008712 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008713 // classes.
Francois Pichetf707ae62011-11-11 00:12:11 +00008714 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008715 isa<CXXMethodDecl>(CurContext)) {
8716 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8717 Context.DependentTy, VK_RValue,
8718 RParenLoc);
8719 CE->setTypeDependent(true);
8720 return Owned(CE);
8721 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008722 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008723 RParenLoc, /*EmptyLookup=*/true);
Francois Pichetbcf64712011-09-07 00:14:57 +00008724 }
John McCalld681c392009-12-16 08:11:27 +00008725
John McCall4124c492011-10-17 18:40:02 +00008726 UnbridgedCasts.restore();
8727
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008728 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008729 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008730 case OR_Success: {
8731 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008732 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008733 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00008734 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008735 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008736 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8737 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008738 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008739
Richard Smith998a5912011-06-05 22:42:48 +00008740 case OR_No_Viable_Function: {
8741 // Try to recover by looking for viable functions which the user might
8742 // have meant to call.
8743 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8744 Args, NumArgs, RParenLoc,
8745 /*EmptyLookup=*/false);
8746 if (!Recovery.isInvalid())
8747 return Recovery;
8748
Chris Lattner45d9d602009-02-17 07:29:20 +00008749 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008750 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008751 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008752 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008753 break;
Richard Smith998a5912011-06-05 22:42:48 +00008754 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008755
8756 case OR_Ambiguous:
8757 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008758 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008759 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008760 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008761
8762 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008763 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008764 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8765 << Best->Function->isDeleted()
8766 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008767 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008768 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008769 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis3eaa22a2011-11-04 15:58:13 +00008770
8771 // We emitted an error for the unvailable/deleted function call but keep
8772 // the call in the AST.
8773 FunctionDecl *FDecl = Best->Function;
8774 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
8775 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
8776 RParenLoc, ExecConfig);
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008777 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008778 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008779 }
8780
Douglas Gregorb412e172010-07-25 18:17:45 +00008781 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00008782 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008783}
8784
John McCall4c4c1df2010-01-26 03:27:55 +00008785static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00008786 return Functions.size() > 1 ||
8787 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8788}
8789
Douglas Gregor084d8552009-03-13 23:49:33 +00008790/// \brief Create a unary operation that may resolve to an overloaded
8791/// operator.
8792///
8793/// \param OpLoc The location of the operator itself (e.g., '*').
8794///
8795/// \param OpcIn The UnaryOperator::Opcode that describes this
8796/// operator.
8797///
8798/// \param Functions The set of non-member functions that will be
8799/// considered by overload resolution. The caller needs to build this
8800/// set based on the context using, e.g.,
8801/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8802/// set should not contain any member functions; those will be added
8803/// by CreateOverloadedUnaryOp().
8804///
8805/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00008806ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00008807Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8808 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00008809 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008810 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00008811
8812 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8813 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8814 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008815 // TODO: provide better source location info.
8816 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008817
John McCall4124c492011-10-17 18:40:02 +00008818 if (checkPlaceholderForOverload(*this, Input))
8819 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00008820
Douglas Gregor084d8552009-03-13 23:49:33 +00008821 Expr *Args[2] = { Input, 0 };
8822 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00008823
Douglas Gregor084d8552009-03-13 23:49:33 +00008824 // For post-increment and post-decrement, add the implicit '0' as
8825 // the second argument, so that we know this is a post-increment or
8826 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00008827 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008828 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008829 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8830 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00008831 NumArgs = 2;
8832 }
8833
8834 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00008835 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00008836 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008837 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00008838 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008839 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00008840 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008841
John McCall58cc69d2010-01-27 01:50:18 +00008842 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00008843 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008844 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008845 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008846 /*ADL*/ true, IsOverloaded(Fns),
8847 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00008848 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008849 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00008850 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008851 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00008852 OpLoc));
8853 }
8854
8855 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008856 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008857
8858 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008859 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00008860
8861 // Add operator candidates that are member functions.
8862 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8863
John McCall4c4c1df2010-01-26 03:27:55 +00008864 // Add candidates from ADL.
8865 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00008866 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00008867 /*ExplicitTemplateArgs*/ 0,
8868 CandidateSet);
8869
Douglas Gregor084d8552009-03-13 23:49:33 +00008870 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008871 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00008872
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008873 bool HadMultipleCandidates = (CandidateSet.size() > 1);
8874
Douglas Gregor084d8552009-03-13 23:49:33 +00008875 // Perform overload resolution.
8876 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008877 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008878 case OR_Success: {
8879 // We found a built-in operator or an overloaded operator.
8880 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00008881
Douglas Gregor084d8552009-03-13 23:49:33 +00008882 if (FnDecl) {
8883 // We matched an overloaded operator. Build a call to that
8884 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00008885
Chandler Carruth30141632011-02-25 19:41:05 +00008886 MarkDeclarationReferenced(OpLoc, FnDecl);
8887
Douglas Gregor084d8552009-03-13 23:49:33 +00008888 // Convert the arguments.
8889 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00008890 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008891
John Wiegley01296292011-04-08 18:41:53 +00008892 ExprResult InputRes =
8893 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8894 Best->FoundDecl, Method);
8895 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008896 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008897 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008898 } else {
8899 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008900 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00008901 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008902 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00008903 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008904 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00008905 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00008906 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008907 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008908 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008909 }
8910
John McCall4fa0d5f2010-05-06 18:15:07 +00008911 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8912
John McCall7decc9e2010-11-18 06:31:45 +00008913 // Determine the result type.
8914 QualType ResultTy = FnDecl->getResultType();
8915 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8916 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00008917
Douglas Gregor084d8552009-03-13 23:49:33 +00008918 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008919 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
8920 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00008921 if (FnExpr.isInvalid())
8922 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00008923
Eli Friedman030eee42009-11-18 03:58:17 +00008924 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00008925 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008926 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008927 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00008928
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008929 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00008930 FnDecl))
8931 return ExprError();
8932
John McCallb268a282010-08-23 23:25:46 +00008933 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00008934 } else {
8935 // We matched a built-in operator. Convert the arguments, then
8936 // break out so that we will build the appropriate built-in
8937 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008938 ExprResult InputRes =
8939 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8940 Best->Conversions[0], AA_Passing);
8941 if (InputRes.isInvalid())
8942 return ExprError();
8943 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008944 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00008945 }
John Wiegley01296292011-04-08 18:41:53 +00008946 }
8947
8948 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00008949 // This is an erroneous use of an operator which can be overloaded by
8950 // a non-member function. Check for non-member operators which were
8951 // defined too late to be candidates.
8952 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8953 // FIXME: Recover by calling the found function.
8954 return ExprError();
8955
John Wiegley01296292011-04-08 18:41:53 +00008956 // No viable function; fall through to handling this as a
8957 // built-in operator, which will produce an error message for us.
8958 break;
8959
8960 case OR_Ambiguous:
8961 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8962 << UnaryOperator::getOpcodeStr(Opc)
8963 << Input->getType()
8964 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008965 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00008966 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8967 return ExprError();
8968
8969 case OR_Deleted:
8970 Diag(OpLoc, diag::err_ovl_deleted_oper)
8971 << Best->Function->isDeleted()
8972 << UnaryOperator::getOpcodeStr(Opc)
8973 << getDeletedOrUnavailableSuffix(Best->Function)
8974 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008975 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
8976 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00008977 return ExprError();
8978 }
Douglas Gregor084d8552009-03-13 23:49:33 +00008979
8980 // Either we found no viable overloaded operator or we matched a
8981 // built-in operator. In either case, fall through to trying to
8982 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00008983 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008984}
8985
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008986/// \brief Create a binary operation that may resolve to an overloaded
8987/// operator.
8988///
8989/// \param OpLoc The location of the operator itself (e.g., '+').
8990///
8991/// \param OpcIn The BinaryOperator::Opcode that describes this
8992/// operator.
8993///
8994/// \param Functions The set of non-member functions that will be
8995/// considered by overload resolution. The caller needs to build this
8996/// set based on the context using, e.g.,
8997/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8998/// set should not contain any member functions; those will be added
8999/// by CreateOverloadedBinOp().
9000///
9001/// \param LHS Left-hand argument.
9002/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00009003ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009004Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00009005 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00009006 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009007 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009008 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00009009 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009010
9011 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9012 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9013 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9014
9015 // If either side is type-dependent, create an appropriate dependent
9016 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00009017 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00009018 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009019 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00009020 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00009021 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00009022 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00009023 Context.DependentTy,
9024 VK_RValue, OK_Ordinary,
9025 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009026
Douglas Gregor5287f092009-11-05 00:51:44 +00009027 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9028 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009029 VK_LValue,
9030 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00009031 Context.DependentTy,
9032 Context.DependentTy,
9033 OpLoc));
9034 }
John McCall4c4c1df2010-01-26 03:27:55 +00009035
9036 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00009037 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009038 // TODO: provide better source location info in DNLoc component.
9039 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00009040 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00009041 = UnresolvedLookupExpr::Create(Context, NamingClass,
9042 NestedNameSpecifierLoc(), OpNameInfo,
9043 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009044 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009045 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009046 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009047 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009048 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009049 OpLoc));
9050 }
9051
John McCall4124c492011-10-17 18:40:02 +00009052 // Always do placeholder-like conversions on the RHS.
9053 if (checkPlaceholderForOverload(*this, Args[1]))
9054 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009055
John McCall526ab472011-10-25 17:37:35 +00009056 // Do placeholder-like conversion on the LHS; note that we should
9057 // not get here with a PseudoObject LHS.
9058 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall4124c492011-10-17 18:40:02 +00009059 if (checkPlaceholderForOverload(*this, Args[0]))
9060 return ExprError();
9061
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009062 // If this is the assignment operator, we only perform overload resolution
9063 // if the left-hand side is a class or enumeration type. This is actually
9064 // a hack. The standard requires that we do overload resolution between the
9065 // various built-in candidates, but as DR507 points out, this can lead to
9066 // problems. So we do it this way, which pretty much follows what GCC does.
9067 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009068 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009069 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009070
John McCalle26a8722010-12-04 08:14:53 +00009071 // If this is the .* operator, which is not overloadable, just
9072 // create a built-in binary operator.
9073 if (Opc == BO_PtrMemD)
9074 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9075
Douglas Gregor084d8552009-03-13 23:49:33 +00009076 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009077 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009078
9079 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009080 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009081
9082 // Add operator candidates that are member functions.
9083 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9084
John McCall4c4c1df2010-01-26 03:27:55 +00009085 // Add candidates from ADL.
9086 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9087 Args, 2,
9088 /*ExplicitTemplateArgs*/ 0,
9089 CandidateSet);
9090
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009091 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009092 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009093
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009094 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9095
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009096 // Perform overload resolution.
9097 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009098 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009099 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009100 // We found a built-in operator or an overloaded operator.
9101 FunctionDecl *FnDecl = Best->Function;
9102
9103 if (FnDecl) {
9104 // We matched an overloaded operator. Build a call to that
9105 // operator.
9106
Chandler Carruth30141632011-02-25 19:41:05 +00009107 MarkDeclarationReferenced(OpLoc, FnDecl);
9108
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009109 // Convert the arguments.
9110 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009111 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009112 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009113
Chandler Carruth8e543b32010-12-12 08:17:55 +00009114 ExprResult Arg1 =
9115 PerformCopyInitialization(
9116 InitializedEntity::InitializeParameter(Context,
9117 FnDecl->getParamDecl(0)),
9118 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009119 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009120 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009121
John Wiegley01296292011-04-08 18:41:53 +00009122 ExprResult Arg0 =
9123 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9124 Best->FoundDecl, Method);
9125 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009126 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009127 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009128 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009129 } else {
9130 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009131 ExprResult Arg0 = PerformCopyInitialization(
9132 InitializedEntity::InitializeParameter(Context,
9133 FnDecl->getParamDecl(0)),
9134 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009135 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009136 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009137
Chandler Carruth8e543b32010-12-12 08:17:55 +00009138 ExprResult Arg1 =
9139 PerformCopyInitialization(
9140 InitializedEntity::InitializeParameter(Context,
9141 FnDecl->getParamDecl(1)),
9142 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009143 if (Arg1.isInvalid())
9144 return ExprError();
9145 Args[0] = LHS = Arg0.takeAs<Expr>();
9146 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009147 }
9148
John McCall4fa0d5f2010-05-06 18:15:07 +00009149 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9150
John McCall7decc9e2010-11-18 06:31:45 +00009151 // Determine the result type.
9152 QualType ResultTy = FnDecl->getResultType();
9153 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9154 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009155
9156 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009157 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9158 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009159 if (FnExpr.isInvalid())
9160 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009161
John McCallb268a282010-08-23 23:25:46 +00009162 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009163 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009164 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009165
9166 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009167 FnDecl))
9168 return ExprError();
9169
John McCallb268a282010-08-23 23:25:46 +00009170 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009171 } else {
9172 // We matched a built-in operator. Convert the arguments, then
9173 // break out so that we will build the appropriate built-in
9174 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009175 ExprResult ArgsRes0 =
9176 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9177 Best->Conversions[0], AA_Passing);
9178 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009179 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009180 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009181
John Wiegley01296292011-04-08 18:41:53 +00009182 ExprResult ArgsRes1 =
9183 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9184 Best->Conversions[1], AA_Passing);
9185 if (ArgsRes1.isInvalid())
9186 return ExprError();
9187 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009188 break;
9189 }
9190 }
9191
Douglas Gregor66950a32009-09-30 21:46:01 +00009192 case OR_No_Viable_Function: {
9193 // C++ [over.match.oper]p9:
9194 // If the operator is the operator , [...] and there are no
9195 // viable functions, then the operator is assumed to be the
9196 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00009197 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00009198 break;
9199
Chandler Carruth8e543b32010-12-12 08:17:55 +00009200 // For class as left operand for assignment or compound assigment
9201 // operator do not fall through to handling in built-in, but report that
9202 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00009203 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009204 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00009205 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00009206 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9207 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00009208 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00009209 } else {
Richard Smith998a5912011-06-05 22:42:48 +00009210 // This is an erroneous use of an operator which can be overloaded by
9211 // a non-member function. Check for non-member operators which were
9212 // defined too late to be candidates.
9213 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9214 // FIXME: Recover by calling the found function.
9215 return ExprError();
9216
Douglas Gregor66950a32009-09-30 21:46:01 +00009217 // No viable function; try to create a built-in operation, which will
9218 // produce an error. Then, show the non-viable candidates.
9219 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00009220 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009221 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00009222 "C++ binary operator overloading is missing candidates!");
9223 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00009224 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9225 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00009226 return move(Result);
9227 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009228
9229 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009230 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009231 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00009232 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00009233 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009234 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9235 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009236 return ExprError();
9237
9238 case OR_Deleted:
9239 Diag(OpLoc, diag::err_ovl_deleted_oper)
9240 << Best->Function->isDeleted()
9241 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009242 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00009243 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009244 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9245 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009246 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00009247 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009248
Douglas Gregor66950a32009-09-30 21:46:01 +00009249 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00009250 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009251}
9252
John McCalldadc5752010-08-24 06:29:42 +00009253ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00009254Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9255 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00009256 Expr *Base, Expr *Idx) {
9257 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00009258 DeclarationName OpName =
9259 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9260
9261 // If either side is type-dependent, create an appropriate dependent
9262 // expression.
9263 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9264
John McCall58cc69d2010-01-27 01:50:18 +00009265 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009266 // CHECKME: no 'operator' keyword?
9267 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9268 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00009269 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009270 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009271 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009272 /*ADL*/ true, /*Overloaded*/ false,
9273 UnresolvedSetIterator(),
9274 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00009275 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00009276
Sebastian Redladba46e2009-10-29 20:17:01 +00009277 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9278 Args, 2,
9279 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009280 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00009281 RLoc));
9282 }
9283
John McCall4124c492011-10-17 18:40:02 +00009284 // Handle placeholders on both operands.
9285 if (checkPlaceholderForOverload(*this, Args[0]))
9286 return ExprError();
9287 if (checkPlaceholderForOverload(*this, Args[1]))
9288 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009289
Sebastian Redladba46e2009-10-29 20:17:01 +00009290 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009291 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009292
9293 // Subscript can only be overloaded as a member function.
9294
9295 // Add operator candidates that are member functions.
9296 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9297
9298 // Add builtin operator candidates.
9299 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9300
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009301 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9302
Sebastian Redladba46e2009-10-29 20:17:01 +00009303 // Perform overload resolution.
9304 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009305 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00009306 case OR_Success: {
9307 // We found a built-in operator or an overloaded operator.
9308 FunctionDecl *FnDecl = Best->Function;
9309
9310 if (FnDecl) {
9311 // We matched an overloaded operator. Build a call to that
9312 // operator.
9313
Chandler Carruth30141632011-02-25 19:41:05 +00009314 MarkDeclarationReferenced(LLoc, FnDecl);
9315
John McCalla0296f72010-03-19 07:35:19 +00009316 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009317 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00009318
Sebastian Redladba46e2009-10-29 20:17:01 +00009319 // Convert the arguments.
9320 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00009321 ExprResult Arg0 =
9322 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9323 Best->FoundDecl, Method);
9324 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009325 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009326 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009327
Anders Carlssona68e51e2010-01-29 18:37:50 +00009328 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009329 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00009330 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009331 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00009332 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009333 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00009334 Owned(Args[1]));
9335 if (InputInit.isInvalid())
9336 return ExprError();
9337
9338 Args[1] = InputInit.takeAs<Expr>();
9339
Sebastian Redladba46e2009-10-29 20:17:01 +00009340 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00009341 QualType ResultTy = FnDecl->getResultType();
9342 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9343 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00009344
9345 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00009346 DeclarationNameLoc LocInfo;
9347 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9348 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009349 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9350 HadMultipleCandidates,
9351 LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00009352 if (FnExpr.isInvalid())
9353 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009354
John McCallb268a282010-08-23 23:25:46 +00009355 CXXOperatorCallExpr *TheCall =
9356 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00009357 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00009358 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009359
John McCallb268a282010-08-23 23:25:46 +00009360 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00009361 FnDecl))
9362 return ExprError();
9363
John McCallb268a282010-08-23 23:25:46 +00009364 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00009365 } else {
9366 // We matched a built-in operator. Convert the arguments, then
9367 // break out so that we will build the appropriate built-in
9368 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009369 ExprResult ArgsRes0 =
9370 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9371 Best->Conversions[0], AA_Passing);
9372 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009373 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009374 Args[0] = ArgsRes0.take();
9375
9376 ExprResult ArgsRes1 =
9377 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9378 Best->Conversions[1], AA_Passing);
9379 if (ArgsRes1.isInvalid())
9380 return ExprError();
9381 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009382
9383 break;
9384 }
9385 }
9386
9387 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00009388 if (CandidateSet.empty())
9389 Diag(LLoc, diag::err_ovl_no_oper)
9390 << Args[0]->getType() << /*subscript*/ 0
9391 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9392 else
9393 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9394 << Args[0]->getType()
9395 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009396 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9397 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00009398 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009399 }
9400
9401 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009402 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009403 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00009404 << Args[0]->getType() << Args[1]->getType()
9405 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009406 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9407 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009408 return ExprError();
9409
9410 case OR_Deleted:
9411 Diag(LLoc, diag::err_ovl_deleted_oper)
9412 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009413 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00009414 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009415 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9416 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009417 return ExprError();
9418 }
9419
9420 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00009421 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009422}
9423
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009424/// BuildCallToMemberFunction - Build a call to a member
9425/// function. MemExpr is the expression that refers to the member
9426/// function (and includes the object parameter), Args/NumArgs are the
9427/// arguments to the function call (not including the object
9428/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00009429/// expression refers to a non-static member function or an overloaded
9430/// member function.
John McCalldadc5752010-08-24 06:29:42 +00009431ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00009432Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9433 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009434 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00009435 assert(MemExprE->getType() == Context.BoundMemberTy ||
9436 MemExprE->getType() == Context.OverloadTy);
9437
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009438 // Dig out the member expression. This holds both the object
9439 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00009440 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009441
John McCall0009fcc2011-04-26 20:42:42 +00009442 // Determine whether this is a call to a pointer-to-member function.
9443 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9444 assert(op->getType() == Context.BoundMemberTy);
9445 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9446
9447 QualType fnType =
9448 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9449
9450 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9451 QualType resultType = proto->getCallResultType(Context);
9452 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9453
9454 // Check that the object type isn't more qualified than the
9455 // member function we're calling.
9456 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9457
9458 QualType objectType = op->getLHS()->getType();
9459 if (op->getOpcode() == BO_PtrMemI)
9460 objectType = objectType->castAs<PointerType>()->getPointeeType();
9461 Qualifiers objectQuals = objectType.getQualifiers();
9462
9463 Qualifiers difference = objectQuals - funcQuals;
9464 difference.removeObjCGCAttr();
9465 difference.removeAddressSpace();
9466 if (difference) {
9467 std::string qualsString = difference.getAsString();
9468 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9469 << fnType.getUnqualifiedType()
9470 << qualsString
9471 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9472 }
9473
9474 CXXMemberCallExpr *call
9475 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9476 resultType, valueKind, RParenLoc);
9477
9478 if (CheckCallReturnType(proto->getResultType(),
9479 op->getRHS()->getSourceRange().getBegin(),
9480 call, 0))
9481 return ExprError();
9482
9483 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9484 return ExprError();
9485
9486 return MaybeBindToTemporary(call);
9487 }
9488
John McCall4124c492011-10-17 18:40:02 +00009489 UnbridgedCastsSet UnbridgedCasts;
9490 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9491 return ExprError();
9492
John McCall10eae182009-11-30 22:42:35 +00009493 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009494 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009495 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009496 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009497 if (isa<MemberExpr>(NakedMemExpr)) {
9498 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009499 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009500 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009501 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +00009502 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +00009503 } else {
9504 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009505 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009506
John McCall6e9f8f62009-12-03 04:06:58 +00009507 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009508 Expr::Classification ObjectClassification
9509 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9510 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009511
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009512 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009513 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009514
John McCall2d74de92009-12-01 22:10:20 +00009515 // FIXME: avoid copy.
9516 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9517 if (UnresExpr->hasExplicitTemplateArgs()) {
9518 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9519 TemplateArgs = &TemplateArgsBuffer;
9520 }
9521
John McCall10eae182009-11-30 22:42:35 +00009522 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9523 E = UnresExpr->decls_end(); I != E; ++I) {
9524
John McCall6e9f8f62009-12-03 04:06:58 +00009525 NamedDecl *Func = *I;
9526 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9527 if (isa<UsingShadowDecl>(Func))
9528 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9529
Douglas Gregor02824322011-01-26 19:30:28 +00009530
Francois Pichet64225792011-01-18 05:04:39 +00009531 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +00009532 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +00009533 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9534 CandidateSet);
9535 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009536 // If explicit template arguments were provided, we can't call a
9537 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009538 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009539 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009540
John McCalla0296f72010-03-19 07:35:19 +00009541 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009542 ObjectClassification,
9543 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009544 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009545 } else {
John McCall10eae182009-11-30 22:42:35 +00009546 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009547 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009548 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009549 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009550 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009551 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009552 }
Mike Stump11289f42009-09-09 15:08:12 +00009553
John McCall10eae182009-11-30 22:42:35 +00009554 DeclarationName DeclName = UnresExpr->getMemberName();
9555
John McCall4124c492011-10-17 18:40:02 +00009556 UnbridgedCasts.restore();
9557
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009558 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009559 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009560 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009561 case OR_Success:
9562 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009563 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009564 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009565 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009566 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009567 break;
9568
9569 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009570 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009571 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009572 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009573 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009574 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009575 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009576
9577 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009578 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009579 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009580 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009581 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009582 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009583
9584 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009585 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009586 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009587 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009588 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009589 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009590 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009591 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009592 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009593 }
9594
John McCall16df1e52010-03-30 21:47:33 +00009595 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009596
John McCall2d74de92009-12-01 22:10:20 +00009597 // If overload resolution picked a static member, build a
9598 // non-member call based on that function.
9599 if (Method->isStatic()) {
9600 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9601 Args, NumArgs, RParenLoc);
9602 }
9603
John McCall10eae182009-11-30 22:42:35 +00009604 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009605 }
9606
John McCall7decc9e2010-11-18 06:31:45 +00009607 QualType ResultType = Method->getResultType();
9608 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9609 ResultType = ResultType.getNonLValueExprType(Context);
9610
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009611 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009612 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009613 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009614 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009615
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009616 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009617 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009618 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009619 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009620
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009621 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009622 // We only need to do this if there was actually an overload; otherwise
9623 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009624 if (!Method->isStatic()) {
9625 ExprResult ObjectArg =
9626 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9627 FoundDecl, Method);
9628 if (ObjectArg.isInvalid())
9629 return ExprError();
9630 MemExpr->setBase(ObjectArg.take());
9631 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009632
9633 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009634 const FunctionProtoType *Proto =
9635 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009636 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009637 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009638 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009639
John McCallb268a282010-08-23 23:25:46 +00009640 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009641 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009642
Anders Carlsson47061ee2011-05-06 14:25:31 +00009643 if ((isa<CXXConstructorDecl>(CurContext) ||
9644 isa<CXXDestructorDecl>(CurContext)) &&
9645 TheCall->getMethodDecl()->isPure()) {
9646 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9647
Chandler Carruth59259262011-06-27 08:31:58 +00009648 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009649 Diag(MemExpr->getLocStart(),
9650 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9651 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9652 << MD->getParent()->getDeclName();
9653
9654 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009655 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009656 }
John McCallb268a282010-08-23 23:25:46 +00009657 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009658}
9659
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009660/// BuildCallToObjectOfClassType - Build a call to an object of class
9661/// type (C++ [over.call.object]), which can end up invoking an
9662/// overloaded function call operator (@c operator()) or performing a
9663/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009664ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009665Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009666 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009667 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009668 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +00009669 if (checkPlaceholderForOverload(*this, Obj))
9670 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009671 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +00009672
9673 UnbridgedCastsSet UnbridgedCasts;
9674 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9675 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009676
John Wiegley01296292011-04-08 18:41:53 +00009677 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9678 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009679
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009680 // C++ [over.call.object]p1:
9681 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009682 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009683 // candidate functions includes at least the function call
9684 // operators of T. The function call operators of T are obtained by
9685 // ordinary lookup of the name operator() in the context of
9686 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009687 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009688 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009689
John Wiegley01296292011-04-08 18:41:53 +00009690 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009691 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009692 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009693 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009694
John McCall27b18f82009-11-17 02:14:36 +00009695 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9696 LookupQualifiedName(R, Record->getDecl());
9697 R.suppressDiagnostics();
9698
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009699 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009700 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009701 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9702 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009703 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009704 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009705
Douglas Gregorab7897a2008-11-19 22:57:39 +00009706 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009707 // In addition, for each (non-explicit in C++0x) conversion function
9708 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +00009709 //
9710 // operator conversion-type-id () cv-qualifier;
9711 //
9712 // where cv-qualifier is the same cv-qualification as, or a
9713 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009714 // denotes the type "pointer to function of (P1,...,Pn) returning
9715 // R", or the type "reference to pointer to function of
9716 // (P1,...,Pn) returning R", or the type "reference to function
9717 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009718 // is also considered as a candidate function. Similarly,
9719 // surrogate call functions are added to the set of candidate
9720 // functions for each conversion function declared in an
9721 // accessible base class provided the function is not hidden
9722 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009723 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009724 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009725 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009726 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009727 NamedDecl *D = *I;
9728 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9729 if (isa<UsingShadowDecl>(D))
9730 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009731
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009732 // Skip over templated conversion functions; they aren't
9733 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009734 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009735 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009736
John McCall6e9f8f62009-12-03 04:06:58 +00009737 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009738 if (!Conv->isExplicit()) {
9739 // Strip the reference type (if any) and then the pointer type (if
9740 // any) to get down to what might be a function type.
9741 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9742 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9743 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +00009744
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009745 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9746 {
9747 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9748 Object.get(), Args, NumArgs, CandidateSet);
9749 }
9750 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00009751 }
Mike Stump11289f42009-09-09 15:08:12 +00009752
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009753 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9754
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009755 // Perform overload resolution.
9756 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009757 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009758 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009759 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009760 // Overload resolution succeeded; we'll build the appropriate call
9761 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009762 break;
9763
9764 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009765 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009766 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9767 << Object.get()->getType() << /*call*/ 1
9768 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009769 else
John Wiegley01296292011-04-08 18:41:53 +00009770 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009771 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009772 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009773 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009774 break;
9775
9776 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009777 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009778 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009779 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009780 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009781 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009782
9783 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00009784 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00009785 diag::err_ovl_deleted_object_call)
9786 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +00009787 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009788 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +00009789 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009790 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009791 break;
Mike Stump11289f42009-09-09 15:08:12 +00009792 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009793
Douglas Gregorb412e172010-07-25 18:17:45 +00009794 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009795 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009796
John McCall4124c492011-10-17 18:40:02 +00009797 UnbridgedCasts.restore();
9798
Douglas Gregorab7897a2008-11-19 22:57:39 +00009799 if (Best->Function == 0) {
9800 // Since there is no function declaration, this is one of the
9801 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00009802 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00009803 = cast<CXXConversionDecl>(
9804 Best->Conversions[0].UserDefined.ConversionFunction);
9805
John Wiegley01296292011-04-08 18:41:53 +00009806 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009807 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009808
Douglas Gregorab7897a2008-11-19 22:57:39 +00009809 // We selected one of the surrogate functions that converts the
9810 // object parameter to a function pointer. Perform the conversion
9811 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009812
Fariborz Jahanian774cf792009-09-28 18:35:46 +00009813 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00009814 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009815 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
9816 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00009817 if (Call.isInvalid())
9818 return ExprError();
Abramo Bagnarab0cf2972011-11-16 22:46:05 +00009819 // Record usage of conversion in an implicit cast.
9820 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
9821 CK_UserDefinedConversion,
9822 Call.get(), 0, VK_RValue));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009823
Douglas Gregor668443e2011-01-20 00:18:04 +00009824 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00009825 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00009826 }
9827
Chandler Carruth30141632011-02-25 19:41:05 +00009828 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009829 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009830 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009831
Douglas Gregorab7897a2008-11-19 22:57:39 +00009832 // We found an overloaded operator(). Build a CXXOperatorCallExpr
9833 // that calls this method, using Object for the implicit object
9834 // parameter and passing along the remaining arguments.
9835 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00009836 const FunctionProtoType *Proto =
9837 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009838
9839 unsigned NumArgsInProto = Proto->getNumArgs();
9840 unsigned NumArgsToCheck = NumArgs;
9841
9842 // Build the full argument list for the method call (the
9843 // implicit object parameter is placed at the beginning of the
9844 // list).
9845 Expr **MethodArgs;
9846 if (NumArgs < NumArgsInProto) {
9847 NumArgsToCheck = NumArgsInProto;
9848 MethodArgs = new Expr*[NumArgsInProto + 1];
9849 } else {
9850 MethodArgs = new Expr*[NumArgs + 1];
9851 }
John Wiegley01296292011-04-08 18:41:53 +00009852 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009853 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9854 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00009855
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009856 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
9857 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00009858 if (NewFn.isInvalid())
9859 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009860
9861 // Once we've built TheCall, all of the expressions are properly
9862 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00009863 QualType ResultTy = Method->getResultType();
9864 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9865 ResultTy = ResultTy.getNonLValueExprType(Context);
9866
John McCallb268a282010-08-23 23:25:46 +00009867 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009868 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +00009869 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00009870 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009871 delete [] MethodArgs;
9872
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009873 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00009874 Method))
9875 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009876
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009877 // We may have default arguments. If so, we need to allocate more
9878 // slots in the call for them.
9879 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00009880 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009881 else if (NumArgs > NumArgsInProto)
9882 NumArgsToCheck = NumArgsInProto;
9883
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009884 bool IsError = false;
9885
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009886 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +00009887 ExprResult ObjRes =
9888 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9889 Best->FoundDecl, Method);
9890 if (ObjRes.isInvalid())
9891 IsError = true;
9892 else
9893 Object = move(ObjRes);
9894 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009895
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009896 // Check the argument types.
9897 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009898 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009899 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009900 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00009901
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009902 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009903
John McCalldadc5752010-08-24 06:29:42 +00009904 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009905 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009906 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009907 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00009908 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009909
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009910 IsError |= InputInit.isInvalid();
9911 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009912 } else {
John McCalldadc5752010-08-24 06:29:42 +00009913 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009914 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9915 if (DefArg.isInvalid()) {
9916 IsError = true;
9917 break;
9918 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009919
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009920 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009921 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009922
9923 TheCall->setArg(i + 1, Arg);
9924 }
9925
9926 // If this is a variadic call, handle args passed through "...".
9927 if (Proto->isVariadic()) {
9928 // Promote the arguments (C99 6.5.2.2p7).
9929 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +00009930 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9931 IsError |= Arg.isInvalid();
9932 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009933 }
9934 }
9935
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009936 if (IsError) return true;
9937
John McCallb268a282010-08-23 23:25:46 +00009938 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00009939 return true;
9940
John McCalle172be52010-08-24 06:09:16 +00009941 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009942}
9943
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009944/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00009945/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009946/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00009947ExprResult
John McCallb268a282010-08-23 23:25:46 +00009948Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009949 assert(Base->getType()->isRecordType() &&
9950 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00009951
John McCall4124c492011-10-17 18:40:02 +00009952 if (checkPlaceholderForOverload(*this, Base))
9953 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009954
John McCallbc077cf2010-02-08 23:07:23 +00009955 SourceLocation Loc = Base->getExprLoc();
9956
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009957 // C++ [over.ref]p1:
9958 //
9959 // [...] An expression x->m is interpreted as (x.operator->())->m
9960 // for a class object x of type T if T::operator->() exists and if
9961 // the operator is selected as the best match function by the
9962 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00009963 DeclarationName OpName =
9964 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00009965 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009966 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00009967
John McCallbc077cf2010-02-08 23:07:23 +00009968 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00009969 PDiag(diag::err_typecheck_incomplete_tag)
9970 << Base->getSourceRange()))
9971 return ExprError();
9972
John McCall27b18f82009-11-17 02:14:36 +00009973 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9974 LookupQualifiedName(R, BaseRecord->getDecl());
9975 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00009976
9977 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00009978 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00009979 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9980 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00009981 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009982
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009983 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9984
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009985 // Perform overload resolution.
9986 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009987 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009988 case OR_Success:
9989 // Overload resolution succeeded; we'll build the call below.
9990 break;
9991
9992 case OR_No_Viable_Function:
9993 if (CandidateSet.empty())
9994 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00009995 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009996 else
9997 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00009998 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009999 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010000 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010001
10002 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +000010003 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10004 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010005 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010006 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +000010007
10008 case OR_Deleted:
10009 Diag(OpLoc, diag::err_ovl_deleted_oper)
10010 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010011 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +000010012 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +000010013 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +000010014 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +000010015 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010016 }
10017
Chandler Carruth30141632011-02-25 19:41:05 +000010018 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010019 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010020 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010021
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010022 // Convert the object parameter.
10023 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010024 ExprResult BaseResult =
10025 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10026 Best->FoundDecl, Method);
10027 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010028 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010029 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010030
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010031 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010032 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
10033 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010034 if (FnExpr.isInvalid())
10035 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010036
John McCall7decc9e2010-11-18 06:31:45 +000010037 QualType ResultTy = Method->getResultType();
10038 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10039 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010040 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010041 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010042 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010043
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010044 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010045 Method))
10046 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010047
10048 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010049}
10050
Douglas Gregorcd695e52008-11-10 20:40:00 +000010051/// FixOverloadedFunctionReference - E is an expression that refers to
10052/// a C++ overloaded function (possibly with some parentheses and
10053/// perhaps a '&' around it). We have resolved the overloaded function
10054/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000010055/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000010056Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000010057 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000010058 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010059 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10060 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010061 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010062 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010063
Douglas Gregor51c538b2009-11-20 19:42:02 +000010064 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010065 }
10066
Douglas Gregor51c538b2009-11-20 19:42:02 +000010067 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010068 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10069 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010070 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000010071 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000010072 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000010073 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000010074 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010075 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010076
10077 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000010078 ICE->getCastKind(),
10079 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000010080 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010081 }
10082
Douglas Gregor51c538b2009-11-20 19:42:02 +000010083 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000010084 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000010085 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010086 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10087 if (Method->isStatic()) {
10088 // Do nothing: static member functions aren't any different
10089 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000010090 } else {
John McCalle66edc12009-11-24 19:00:30 +000010091 // Fix the sub expression, which really has to be an
10092 // UnresolvedLookupExpr holding an overloaded member function
10093 // or template.
John McCall16df1e52010-03-30 21:47:33 +000010094 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10095 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000010096 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010097 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010098
John McCalld14a8642009-11-21 08:51:07 +000010099 assert(isa<DeclRefExpr>(SubExpr)
10100 && "fixed to something other than a decl ref");
10101 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10102 && "fixed to a member ref with no nested name qualifier");
10103
10104 // We have taken the address of a pointer to member
10105 // function. Perform the computation here so that we get the
10106 // appropriate pointer to member type.
10107 QualType ClassType
10108 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10109 QualType MemPtrType
10110 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10111
John McCall7decc9e2010-11-18 06:31:45 +000010112 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10113 VK_RValue, OK_Ordinary,
10114 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010115 }
10116 }
John McCall16df1e52010-03-30 21:47:33 +000010117 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10118 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010119 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010120 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010121
John McCalle3027922010-08-25 11:45:40 +000010122 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010123 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000010124 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010125 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010126 }
John McCalld14a8642009-11-21 08:51:07 +000010127
10128 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000010129 // FIXME: avoid copy.
10130 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000010131 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000010132 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10133 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000010134 }
10135
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010136 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10137 ULE->getQualifierLoc(),
10138 Fn,
10139 ULE->getNameLoc(),
10140 Fn->getType(),
10141 VK_LValue,
10142 Found.getDecl(),
10143 TemplateArgs);
10144 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10145 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000010146 }
10147
John McCall10eae182009-11-30 22:42:35 +000010148 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000010149 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000010150 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10151 if (MemExpr->hasExplicitTemplateArgs()) {
10152 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10153 TemplateArgs = &TemplateArgsBuffer;
10154 }
John McCall6b51f282009-11-23 01:53:49 +000010155
John McCall2d74de92009-12-01 22:10:20 +000010156 Expr *Base;
10157
John McCall7decc9e2010-11-18 06:31:45 +000010158 // If we're filling in a static method where we used to have an
10159 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000010160 if (MemExpr->isImplicitAccess()) {
10161 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010162 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10163 MemExpr->getQualifierLoc(),
10164 Fn,
10165 MemExpr->getMemberLoc(),
10166 Fn->getType(),
10167 VK_LValue,
10168 Found.getDecl(),
10169 TemplateArgs);
10170 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10171 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000010172 } else {
10173 SourceLocation Loc = MemExpr->getMemberLoc();
10174 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000010175 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +000010176 Base = new (Context) CXXThisExpr(Loc,
10177 MemExpr->getBaseType(),
10178 /*isImplicit=*/true);
10179 }
John McCall2d74de92009-12-01 22:10:20 +000010180 } else
John McCallc3007a22010-10-26 07:05:15 +000010181 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000010182
John McCall4adb38c2011-04-27 00:36:17 +000010183 ExprValueKind valueKind;
10184 QualType type;
10185 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10186 valueKind = VK_LValue;
10187 type = Fn->getType();
10188 } else {
10189 valueKind = VK_RValue;
10190 type = Context.BoundMemberTy;
10191 }
10192
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010193 MemberExpr *ME = MemberExpr::Create(Context, Base,
10194 MemExpr->isArrow(),
10195 MemExpr->getQualifierLoc(),
10196 Fn,
10197 Found,
10198 MemExpr->getMemberNameInfo(),
10199 TemplateArgs,
10200 type, valueKind, OK_Ordinary);
10201 ME->setHadMultipleCandidates(true);
10202 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010203 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010204
John McCallc3007a22010-10-26 07:05:15 +000010205 llvm_unreachable("Invalid reference to overloaded function");
10206 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010207}
10208
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010209ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000010210 DeclAccessPair Found,
10211 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000010212 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000010213}
10214
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010215} // end namespace clang