blob: 44395c59df14f030c09613d862d7c7d03bf2b14d [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 }
Benjamin Kramerb89514a2011-10-14 18:45:37 +0000308 OS << '\'' << *ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000309 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000310 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000311 After.DebugPrint();
312 }
313}
314
315/// DebugPrint - Print this implicit conversion sequence to standard
316/// error. Useful for debugging overloading issues.
317void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000318 raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000319 switch (ConversionKind) {
320 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000321 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000322 Standard.DebugPrint();
323 break;
324 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000325 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000326 UserDefined.DebugPrint();
327 break;
328 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000329 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000330 break;
John McCall0d1da222010-01-12 00:44:57 +0000331 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000332 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000333 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000334 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000335 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000336 break;
337 }
338
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000339 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000340}
341
John McCall0d1da222010-01-12 00:44:57 +0000342void AmbiguousConversionSequence::construct() {
343 new (&conversions()) ConversionSet();
344}
345
346void AmbiguousConversionSequence::destruct() {
347 conversions().~ConversionSet();
348}
349
350void
351AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
352 FromTypePtr = O.FromTypePtr;
353 ToTypePtr = O.ToTypePtr;
354 new (&conversions()) ConversionSet(O.conversions());
355}
356
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000357namespace {
358 // Structure used by OverloadCandidate::DeductionFailureInfo to store
359 // template parameter and template argument information.
360 struct DFIParamWithArguments {
361 TemplateParameter Param;
362 TemplateArgument FirstArg;
363 TemplateArgument SecondArg;
364 };
365}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000366
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000367/// \brief Convert from Sema's representation of template deduction information
368/// to the form used in overload-candidate information.
369OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000370static MakeDeductionFailureInfo(ASTContext &Context,
371 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000372 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000373 OverloadCandidate::DeductionFailureInfo Result;
374 Result.Result = static_cast<unsigned>(TDK);
375 Result.Data = 0;
376 switch (TDK) {
377 case Sema::TDK_Success:
378 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000379 case Sema::TDK_TooManyArguments:
380 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000381 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000382
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000383 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000384 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000385 Result.Data = Info.Param.getOpaqueValue();
386 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000387
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000388 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000389 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000390 // FIXME: Should allocate from normal heap so that we can free this later.
391 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000392 Saved->Param = Info.Param;
393 Saved->FirstArg = Info.FirstArg;
394 Saved->SecondArg = Info.SecondArg;
395 Result.Data = Saved;
396 break;
397 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000398
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000399 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000400 Result.Data = Info.take();
401 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000402
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000403 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000404 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000405 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000406 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000407
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000408 return Result;
409}
John McCall0d1da222010-01-12 00:44:57 +0000410
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000411void OverloadCandidate::DeductionFailureInfo::Destroy() {
412 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
413 case Sema::TDK_Success:
414 case Sema::TDK_InstantiationDepth:
415 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000416 case Sema::TDK_TooManyArguments:
417 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000418 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000419 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000420
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000421 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000422 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000423 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000424 Data = 0;
425 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000426
427 case Sema::TDK_SubstitutionFailure:
428 // FIXME: Destroy the template arugment list?
429 Data = 0;
430 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000431
Douglas Gregor461761d2010-05-08 18:20:53 +0000432 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000433 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000434 case Sema::TDK_FailedOverloadResolution:
435 break;
436 }
437}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000438
439TemplateParameter
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000440OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
441 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
442 case Sema::TDK_Success:
443 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000444 case Sema::TDK_TooManyArguments:
445 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000446 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000447 return TemplateParameter();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000448
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000449 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000450 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000451 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000452
453 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000454 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000455 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000456
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000457 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000458 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000459 case Sema::TDK_FailedOverloadResolution:
460 break;
461 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000462
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000463 return TemplateParameter();
464}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000465
Douglas Gregord09efd42010-05-08 20:07:26 +0000466TemplateArgumentList *
467OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
468 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
469 case Sema::TDK_Success:
470 case Sema::TDK_InstantiationDepth:
471 case Sema::TDK_TooManyArguments:
472 case Sema::TDK_TooFewArguments:
473 case Sema::TDK_Incomplete:
474 case Sema::TDK_InvalidExplicitArguments:
475 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000476 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000477 return 0;
478
479 case Sema::TDK_SubstitutionFailure:
480 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000481
Douglas Gregord09efd42010-05-08 20:07:26 +0000482 // Unhandled
483 case Sema::TDK_NonDeducedMismatch:
484 case Sema::TDK_FailedOverloadResolution:
485 break;
486 }
487
488 return 0;
489}
490
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000491const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
492 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
493 case Sema::TDK_Success:
494 case Sema::TDK_InstantiationDepth:
495 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000496 case Sema::TDK_TooManyArguments:
497 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000498 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000499 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000500 return 0;
501
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000502 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000503 case Sema::TDK_Underqualified:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000504 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000505
Douglas Gregor461761d2010-05-08 18:20:53 +0000506 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000507 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000508 case Sema::TDK_FailedOverloadResolution:
509 break;
510 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000511
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000512 return 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000513}
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000514
515const TemplateArgument *
516OverloadCandidate::DeductionFailureInfo::getSecondArg() {
517 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
518 case Sema::TDK_Success:
519 case Sema::TDK_InstantiationDepth:
520 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000521 case Sema::TDK_TooManyArguments:
522 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000523 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000524 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000525 return 0;
526
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000527 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000528 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000529 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
530
Douglas Gregor461761d2010-05-08 18:20:53 +0000531 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000532 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000533 case Sema::TDK_FailedOverloadResolution:
534 break;
535 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000536
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000537 return 0;
538}
539
540void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000541 inherited::clear();
542 Functions.clear();
543}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000544
John McCall4124c492011-10-17 18:40:02 +0000545namespace {
546 class UnbridgedCastsSet {
547 struct Entry {
548 Expr **Addr;
549 Expr *Saved;
550 };
551 SmallVector<Entry, 2> Entries;
552
553 public:
554 void save(Sema &S, Expr *&E) {
555 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
556 Entry entry = { &E, E };
557 Entries.push_back(entry);
558 E = S.stripARCUnbridgedCast(E);
559 }
560
561 void restore() {
562 for (SmallVectorImpl<Entry>::iterator
563 i = Entries.begin(), e = Entries.end(); i != e; ++i)
564 *i->Addr = i->Saved;
565 }
566 };
567}
568
569/// checkPlaceholderForOverload - Do any interesting placeholder-like
570/// preprocessing on the given expression.
571///
572/// \param unbridgedCasts a collection to which to add unbridged casts;
573/// without this, they will be immediately diagnosed as errors
574///
575/// Return true on unrecoverable error.
576static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
577 UnbridgedCastsSet *unbridgedCasts = 0) {
578 // ObjCProperty l-values are placeholder-like.
579 if (E->getObjectKind() == OK_ObjCProperty) {
580 ExprResult result = S.ConvertPropertyForRValue(E);
581 if (result.isInvalid())
582 return true;
583
584 E = result.take();
585 return false;
586 }
587
588 // Handle true placeholders.
589 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
590 // We can't handle overloaded expressions here because overload
591 // resolution might reasonably tweak them.
592 if (placeholder->getKind() == BuiltinType::Overload) return false;
593
594 // If the context potentially accepts unbridged ARC casts, strip
595 // the unbridged cast and add it to the collection for later restoration.
596 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
597 unbridgedCasts) {
598 unbridgedCasts->save(S, E);
599 return false;
600 }
601
602 // Go ahead and check everything else.
603 ExprResult result = S.CheckPlaceholderExpr(E);
604 if (result.isInvalid())
605 return true;
606
607 E = result.take();
608 return false;
609 }
610
611 // Nothing to do.
612 return false;
613}
614
615/// checkArgPlaceholdersForOverload - Check a set of call operands for
616/// placeholders.
617static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
618 unsigned numArgs,
619 UnbridgedCastsSet &unbridged) {
620 for (unsigned i = 0; i != numArgs; ++i)
621 if (checkPlaceholderForOverload(S, args[i], &unbridged))
622 return true;
623
624 return false;
625}
626
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000627// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000628// overload of the declarations in Old. This routine returns false if
629// New and Old cannot be overloaded, e.g., if New has the same
630// signature as some function in Old (C++ 1.3.10) or if the Old
631// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000632// it does return false, MatchedDecl will point to the decl that New
633// cannot be overloaded with. This decl may be a UsingShadowDecl on
634// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000635//
636// Example: Given the following input:
637//
638// void f(int, float); // #1
639// void f(int, int); // #2
640// int f(int, int); // #3
641//
642// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000643// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000644//
John McCall3d988d92009-12-02 08:47:38 +0000645// When we process #2, Old contains only the FunctionDecl for #1. By
646// comparing the parameter types, we see that #1 and #2 are overloaded
647// (since they have different signatures), so this routine returns
648// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000649//
John McCall3d988d92009-12-02 08:47:38 +0000650// When we process #3, Old is an overload set containing #1 and #2. We
651// compare the signatures of #3 to #1 (they're overloaded, so we do
652// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
653// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000654// signature), IsOverload returns false and MatchedDecl will be set to
655// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000656//
657// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
658// into a class by a using declaration. The rules for whether to hide
659// shadow declarations ignore some properties which otherwise figure
660// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000661Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000662Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
663 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000664 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000665 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000666 NamedDecl *OldD = *I;
667
668 bool OldIsUsingDecl = false;
669 if (isa<UsingShadowDecl>(OldD)) {
670 OldIsUsingDecl = true;
671
672 // We can always introduce two using declarations into the same
673 // context, even if they have identical signatures.
674 if (NewIsUsingDecl) continue;
675
676 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
677 }
678
679 // If either declaration was introduced by a using declaration,
680 // we'll need to use slightly different rules for matching.
681 // Essentially, these rules are the normal rules, except that
682 // function templates hide function templates with different
683 // return types or template parameter lists.
684 bool UseMemberUsingDeclRules =
685 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
686
John McCall3d988d92009-12-02 08:47:38 +0000687 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000688 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
689 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
690 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
691 continue;
692 }
693
John McCalldaa3d6b2009-12-09 03:35:25 +0000694 Match = *I;
695 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000696 }
John McCall3d988d92009-12-02 08:47:38 +0000697 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000698 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
699 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
700 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
701 continue;
702 }
703
John McCalldaa3d6b2009-12-09 03:35:25 +0000704 Match = *I;
705 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000706 }
John McCalla8987a2942010-11-10 03:01:53 +0000707 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000708 // We can overload with these, which can show up when doing
709 // redeclaration checks for UsingDecls.
710 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000711 } else if (isa<TagDecl>(OldD)) {
712 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000713 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
714 // Optimistically assume that an unresolved using decl will
715 // overload; if it doesn't, we'll have to diagnose during
716 // template instantiation.
717 } else {
John McCall1f82f242009-11-18 22:49:29 +0000718 // (C++ 13p1):
719 // Only function declarations can be overloaded; object and type
720 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000721 Match = *I;
722 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000723 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000724 }
John McCall1f82f242009-11-18 22:49:29 +0000725
John McCalldaa3d6b2009-12-09 03:35:25 +0000726 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000727}
728
John McCalle9cccd82010-06-16 08:42:20 +0000729bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
730 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000731 // If both of the functions are extern "C", then they are not
732 // overloads.
733 if (Old->isExternC() && New->isExternC())
734 return false;
735
John McCall1f82f242009-11-18 22:49:29 +0000736 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
737 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
738
739 // C++ [temp.fct]p2:
740 // A function template can be overloaded with other function templates
741 // and with normal (non-template) functions.
742 if ((OldTemplate == 0) != (NewTemplate == 0))
743 return true;
744
745 // Is the function New an overload of the function Old?
746 QualType OldQType = Context.getCanonicalType(Old->getType());
747 QualType NewQType = Context.getCanonicalType(New->getType());
748
749 // Compare the signatures (C++ 1.3.10) of the two functions to
750 // determine whether they are overloads. If we find any mismatch
751 // in the signature, they are overloads.
752
753 // If either of these functions is a K&R-style function (no
754 // prototype), then we consider them to have matching signatures.
755 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
756 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
757 return false;
758
John McCall424cec92011-01-19 06:33:43 +0000759 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
760 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000761
762 // The signature of a function includes the types of its
763 // parameters (C++ 1.3.10), which includes the presence or absence
764 // of the ellipsis; see C++ DR 357).
765 if (OldQType != NewQType &&
766 (OldType->getNumArgs() != NewType->getNumArgs() ||
767 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000768 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000769 return true;
770
771 // C++ [temp.over.link]p4:
772 // The signature of a function template consists of its function
773 // signature, its return type and its template parameter list. The names
774 // of the template parameters are significant only for establishing the
775 // relationship between the template parameters and the rest of the
776 // signature.
777 //
778 // We check the return type and template parameter lists for function
779 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000780 //
781 // However, we don't consider either of these when deciding whether
782 // a member introduced by a shadow declaration is hidden.
783 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000784 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
785 OldTemplate->getTemplateParameters(),
786 false, TPL_TemplateMatch) ||
787 OldType->getResultType() != NewType->getResultType()))
788 return true;
789
790 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000791 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000792 //
793 // As part of this, also check whether one of the member functions
794 // is static, in which case they are not overloads (C++
795 // 13.1p2). While not part of the definition of the signature,
796 // this check is important to determine whether these functions
797 // can be overloaded.
798 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
799 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
800 if (OldMethod && NewMethod &&
801 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000802 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000803 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
804 if (!UseUsingDeclRules &&
805 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
806 (OldMethod->getRefQualifier() == RQ_None ||
807 NewMethod->getRefQualifier() == RQ_None)) {
808 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000809 // - Member function declarations with the same name and the same
810 // parameter-type-list as well as member function template
811 // declarations with the same name, the same parameter-type-list, and
812 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000813 // them, but not all, have a ref-qualifier (8.3.5).
814 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
815 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
816 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
817 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000818
John McCall1f82f242009-11-18 22:49:29 +0000819 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000820 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000821
John McCall1f82f242009-11-18 22:49:29 +0000822 // The signatures match; this is not an overload.
823 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000824}
825
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000826/// \brief Checks availability of the function depending on the current
827/// function context. Inside an unavailable function, unavailability is ignored.
828///
829/// \returns true if \arg FD is unavailable and current context is inside
830/// an available function, false otherwise.
831bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
832 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
833}
834
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000835/// TryImplicitConversion - Attempt to perform an implicit conversion
836/// from the given expression (Expr) to the given type (ToType). This
837/// function returns an implicit conversion sequence that can be used
838/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000839///
840/// void f(float f);
841/// void g(int i) { f(i); }
842///
843/// this routine would produce an implicit conversion sequence to
844/// describe the initialization of f from i, which will be a standard
845/// conversion sequence containing an lvalue-to-rvalue conversion (C++
846/// 4.1) followed by a floating-integral conversion (C++ 4.9).
847//
848/// Note that this routine only determines how the conversion can be
849/// performed; it does not actually perform the conversion. As such,
850/// it will not produce any diagnostics if no conversion is available,
851/// but will instead return an implicit conversion sequence of kind
852/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000853///
854/// If @p SuppressUserConversions, then user-defined conversions are
855/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000856/// If @p AllowExplicit, then explicit user-defined conversions are
857/// permitted.
John McCall31168b02011-06-15 23:02:42 +0000858///
859/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
860/// writeback conversion, which allows __autoreleasing id* parameters to
861/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +0000862static ImplicitConversionSequence
863TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
864 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000865 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000866 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000867 bool CStyle,
868 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000869 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000870 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000871 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +0000872 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000873 return ICS;
874 }
875
John McCall5c32be02010-08-24 20:38:10 +0000876 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000877 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000878 return ICS;
879 }
880
Douglas Gregor836a7e82010-08-11 02:15:33 +0000881 // C++ [over.ics.user]p4:
882 // A conversion of an expression of class type to the same class
883 // type is given Exact Match rank, and a conversion of an
884 // expression of class type to a base class of that type is
885 // given Conversion rank, in spite of the fact that a copy/move
886 // constructor (i.e., a user-defined conversion function) is
887 // called for those cases.
888 QualType FromType = From->getType();
889 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000890 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
891 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000892 ICS.setStandard();
893 ICS.Standard.setAsIdentityConversion();
894 ICS.Standard.setFromType(FromType);
895 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000896
Douglas Gregor5ab11652010-04-17 22:01:05 +0000897 // We don't actually check at this point whether there is a valid
898 // copy/move constructor, since overloading just assumes that it
899 // exists. When we actually perform initialization, we'll find the
900 // appropriate constructor to copy the returned object, if needed.
901 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000902
Douglas Gregor5ab11652010-04-17 22:01:05 +0000903 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000904 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000905 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000906
Douglas Gregor836a7e82010-08-11 02:15:33 +0000907 return ICS;
908 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000909
Douglas Gregor836a7e82010-08-11 02:15:33 +0000910 if (SuppressUserConversions) {
911 // We're not in the case above, so there is no conversion that
912 // we can perform.
913 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000914 return ICS;
915 }
916
917 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000918 OverloadCandidateSet Conversions(From->getExprLoc());
919 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000920 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000921 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000922
923 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000924 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000925 // C++ [over.ics.user]p4:
926 // A conversion of an expression of class type to the same class
927 // type is given Exact Match rank, and a conversion of an
928 // expression of class type to a base class of that type is
929 // given Conversion rank, in spite of the fact that a copy
930 // constructor (i.e., a user-defined conversion function) is
931 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000932 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000933 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000934 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000935 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
936 QualType ToCanon
937 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000938 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000939 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000940 // Turn this into a "standard" conversion sequence, so that it
941 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000942 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000943 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000944 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000945 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000946 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000947 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000948 ICS.Standard.Second = ICK_Derived_To_Base;
949 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000950 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000951
952 // C++ [over.best.ics]p4:
953 // However, when considering the argument of a user-defined
954 // conversion function that is a candidate by 13.3.1.3 when
955 // invoked for the copying of the temporary in the second step
956 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
957 // 13.3.1.6 in all cases, only standard conversion sequences and
958 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000959 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000960 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000961 }
John McCalle8c8cd22010-01-13 22:30:33 +0000962 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000963 ICS.setAmbiguous();
964 ICS.Ambiguous.setFromType(From->getType());
965 ICS.Ambiguous.setToType(ToType);
966 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
967 Cand != Conversions.end(); ++Cand)
968 if (Cand->Viable)
969 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000970 } else {
John McCall65eb8792010-02-25 01:37:24 +0000971 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000972 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000973
974 return ICS;
975}
976
John McCall31168b02011-06-15 23:02:42 +0000977ImplicitConversionSequence
978Sema::TryImplicitConversion(Expr *From, QualType ToType,
979 bool SuppressUserConversions,
980 bool AllowExplicit,
981 bool InOverloadResolution,
982 bool CStyle,
983 bool AllowObjCWritebackConversion) {
984 return clang::TryImplicitConversion(*this, From, ToType,
985 SuppressUserConversions, AllowExplicit,
986 InOverloadResolution, CStyle,
987 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +0000988}
989
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000990/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +0000991/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000992/// converted expression. Flavor is the kind of conversion we're
993/// performing, used in the error message. If @p AllowExplicit,
994/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +0000995ExprResult
996Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +0000997 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000998 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +0000999 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001000}
1001
John Wiegley01296292011-04-08 18:41:53 +00001002ExprResult
1003Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001004 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +00001005 ImplicitConversionSequence& ICS) {
John McCall31168b02011-06-15 23:02:42 +00001006 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1007 bool AllowObjCWritebackConversion
1008 = getLangOptions().ObjCAutoRefCount &&
1009 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +00001010
John McCall5c32be02010-08-24 20:38:10 +00001011 ICS = clang::TryImplicitConversion(*this, From, ToType,
1012 /*SuppressUserConversions=*/false,
1013 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +00001014 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00001015 /*CStyle=*/false,
1016 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +00001017 return PerformImplicitConversion(From, ToType, ICS, Action);
1018}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001019
1020/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001021/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +00001022bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1023 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001024 if (Context.hasSameUnqualifiedType(FromType, ToType))
1025 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001026
John McCall991eb4b2010-12-21 00:44:39 +00001027 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1028 // where F adds one of the following at most once:
1029 // - a pointer
1030 // - a member pointer
1031 // - a block pointer
1032 CanQualType CanTo = Context.getCanonicalType(ToType);
1033 CanQualType CanFrom = Context.getCanonicalType(FromType);
1034 Type::TypeClass TyClass = CanTo->getTypeClass();
1035 if (TyClass != CanFrom->getTypeClass()) return false;
1036 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1037 if (TyClass == Type::Pointer) {
1038 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1039 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1040 } else if (TyClass == Type::BlockPointer) {
1041 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1042 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1043 } else if (TyClass == Type::MemberPointer) {
1044 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1045 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1046 } else {
1047 return false;
1048 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001049
John McCall991eb4b2010-12-21 00:44:39 +00001050 TyClass = CanTo->getTypeClass();
1051 if (TyClass != CanFrom->getTypeClass()) return false;
1052 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1053 return false;
1054 }
1055
1056 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1057 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1058 if (!EInfo.getNoReturn()) return false;
1059
1060 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1061 assert(QualType(FromFn, 0).isCanonical());
1062 if (QualType(FromFn, 0) != CanTo) return false;
1063
1064 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001065 return true;
1066}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001067
Douglas Gregor46188682010-05-18 22:42:18 +00001068/// \brief Determine whether the conversion from FromType to ToType is a valid
1069/// vector conversion.
1070///
1071/// \param ICK Will be set to the vector conversion kind, if this is a vector
1072/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001073static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1074 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +00001075 // We need at least one of these types to be a vector type to have a vector
1076 // conversion.
1077 if (!ToType->isVectorType() && !FromType->isVectorType())
1078 return false;
1079
1080 // Identical types require no conversions.
1081 if (Context.hasSameUnqualifiedType(FromType, ToType))
1082 return false;
1083
1084 // There are no conversions between extended vector types, only identity.
1085 if (ToType->isExtVectorType()) {
1086 // There are no conversions between extended vector types other than the
1087 // identity conversion.
1088 if (FromType->isExtVectorType())
1089 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001090
Douglas Gregor46188682010-05-18 22:42:18 +00001091 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001092 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001093 ICK = ICK_Vector_Splat;
1094 return true;
1095 }
1096 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001097
1098 // We can perform the conversion between vector types in the following cases:
1099 // 1)vector types are equivalent AltiVec and GCC vector types
1100 // 2)lax vector conversions are permitted and the vector types are of the
1101 // same size
1102 if (ToType->isVectorType() && FromType->isVectorType()) {
1103 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001104 (Context.getLangOptions().LaxVectorConversions &&
1105 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001106 ICK = ICK_Vector_Conversion;
1107 return true;
1108 }
Douglas Gregor46188682010-05-18 22:42:18 +00001109 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001110
Douglas Gregor46188682010-05-18 22:42:18 +00001111 return false;
1112}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001113
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001114/// IsStandardConversion - Determines whether there is a standard
1115/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1116/// expression From to the type ToType. Standard conversion sequences
1117/// only consider non-class types; for conversions that involve class
1118/// types, use TryImplicitConversion. If a conversion exists, SCS will
1119/// contain the standard conversion sequence required to perform this
1120/// conversion and this routine will return true. Otherwise, this
1121/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001122static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1123 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001124 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001125 bool CStyle,
1126 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001127 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001128
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001129 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001130 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001131 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001132 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001133 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001134 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001135
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001136 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001137 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001138 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001139 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001140 return false;
1141
Mike Stump11289f42009-09-09 15:08:12 +00001142 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001143 }
1144
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001145 // The first conversion can be an lvalue-to-rvalue conversion,
1146 // array-to-pointer conversion, or function-to-pointer conversion
1147 // (C++ 4p1).
1148
John McCall5c32be02010-08-24 20:38:10 +00001149 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001150 DeclAccessPair AccessPair;
1151 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001152 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001153 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001154 // We were able to resolve the address of the overloaded function,
1155 // so we can convert to the type of that function.
1156 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001157
1158 // we can sometimes resolve &foo<int> regardless of ToType, so check
1159 // if the type matches (identity) or we are converting to bool
1160 if (!S.Context.hasSameUnqualifiedType(
1161 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1162 QualType resultTy;
1163 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001164 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001165 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1166 // otherwise, only a boolean conversion is standard
1167 if (!ToType->isBooleanType())
1168 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001169 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001170
Chandler Carruthffce2452011-03-29 08:08:18 +00001171 // Check if the "from" expression is taking the address of an overloaded
1172 // function and recompute the FromType accordingly. Take advantage of the
1173 // fact that non-static member functions *must* have such an address-of
1174 // expression.
1175 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1176 if (Method && !Method->isStatic()) {
1177 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1178 "Non-unary operator on non-static member address");
1179 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1180 == UO_AddrOf &&
1181 "Non-address-of operator on non-static member address");
1182 const Type *ClassType
1183 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1184 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001185 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1186 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1187 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001188 "Non-address-of operator for overloaded function expression");
1189 FromType = S.Context.getPointerType(FromType);
1190 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001191
Douglas Gregor980fb162010-04-29 18:24:40 +00001192 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001193 assert(S.Context.hasSameType(
1194 FromType,
1195 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001196 } else {
1197 return false;
1198 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001199 }
John McCall154a2fd2011-08-30 00:57:29 +00001200 // Lvalue-to-rvalue conversion (C++11 4.1):
1201 // A glvalue (3.10) of a non-function, non-array type T can
1202 // be converted to a prvalue.
1203 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001204 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001205 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001206 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001207 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001208
1209 // If T is a non-class type, the type of the rvalue is the
1210 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001211 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1212 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001213 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001214 } else if (FromType->isArrayType()) {
1215 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001216 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001217
1218 // An lvalue or rvalue of type "array of N T" or "array of unknown
1219 // bound of T" can be converted to an rvalue of type "pointer to
1220 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001221 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001222
John McCall5c32be02010-08-24 20:38:10 +00001223 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001224 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001225 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001226
1227 // For the purpose of ranking in overload resolution
1228 // (13.3.3.1.1), this conversion is considered an
1229 // array-to-pointer conversion followed by a qualification
1230 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001231 SCS.Second = ICK_Identity;
1232 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001233 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001234 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001235 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001236 }
John McCall086a4642010-11-24 05:12:34 +00001237 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001238 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001239 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001240
1241 // An lvalue of function type T can be converted to an rvalue of
1242 // type "pointer to T." The result is a pointer to the
1243 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001244 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001245 } else {
1246 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001247 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001248 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001249 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001250
1251 // The second conversion can be an integral promotion, floating
1252 // point promotion, integral conversion, floating point conversion,
1253 // floating-integral conversion, pointer conversion,
1254 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001255 // For overloading in C, this can also be a "compatible-type"
1256 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001257 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001258 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001259 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001260 // The unqualified versions of the types are the same: there's no
1261 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001262 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001263 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001264 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001265 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001266 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001267 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001268 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001269 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001270 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001271 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001272 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001273 SCS.Second = ICK_Complex_Promotion;
1274 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001275 } else if (ToType->isBooleanType() &&
1276 (FromType->isArithmeticType() ||
1277 FromType->isAnyPointerType() ||
1278 FromType->isBlockPointerType() ||
1279 FromType->isMemberPointerType() ||
1280 FromType->isNullPtrType())) {
1281 // Boolean conversions (C++ 4.12).
1282 SCS.Second = ICK_Boolean_Conversion;
1283 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001284 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001285 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001286 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001287 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001288 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001289 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001290 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001291 SCS.Second = ICK_Complex_Conversion;
1292 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001293 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1294 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001295 // Complex-real conversions (C99 6.3.1.7)
1296 SCS.Second = ICK_Complex_Real;
1297 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001298 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001299 // Floating point conversions (C++ 4.8).
1300 SCS.Second = ICK_Floating_Conversion;
1301 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001302 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001303 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001304 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001305 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001306 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001307 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001308 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001309 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001310 SCS.Second = ICK_Block_Pointer_Conversion;
1311 } else if (AllowObjCWritebackConversion &&
1312 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1313 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001314 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1315 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001316 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001317 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001318 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001319 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001320 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001321 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001322 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001323 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001324 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001325 SCS.Second = SecondICK;
1326 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001327 } else if (!S.getLangOptions().CPlusPlus &&
1328 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001329 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001330 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001331 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001332 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001333 // Treat a conversion that strips "noreturn" as an identity conversion.
1334 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001335 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1336 InOverloadResolution,
1337 SCS, CStyle)) {
1338 SCS.Second = ICK_TransparentUnionConversion;
1339 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001340 } else {
1341 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001342 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001343 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001344 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001345
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001346 QualType CanonFrom;
1347 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001348 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001349 bool ObjCLifetimeConversion;
1350 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1351 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001352 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001353 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001354 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001355 CanonFrom = S.Context.getCanonicalType(FromType);
1356 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001357 } else {
1358 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001359 SCS.Third = ICK_Identity;
1360
Mike Stump11289f42009-09-09 15:08:12 +00001361 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001362 // [...] Any difference in top-level cv-qualification is
1363 // subsumed by the initialization itself and does not constitute
1364 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001365 CanonFrom = S.Context.getCanonicalType(FromType);
1366 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001367 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001368 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001369 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001370 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1371 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001372 FromType = ToType;
1373 CanonFrom = CanonTo;
1374 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001375 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001376 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001377
1378 // If we have not converted the argument type to the parameter type,
1379 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001380 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001381 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001382
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001383 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001384}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001385
1386static bool
1387IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1388 QualType &ToType,
1389 bool InOverloadResolution,
1390 StandardConversionSequence &SCS,
1391 bool CStyle) {
1392
1393 const RecordType *UT = ToType->getAsUnionType();
1394 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1395 return false;
1396 // The field to initialize within the transparent union.
1397 RecordDecl *UD = UT->getDecl();
1398 // It's compatible if the expression matches any of the fields.
1399 for (RecordDecl::field_iterator it = UD->field_begin(),
1400 itend = UD->field_end();
1401 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001402 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1403 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001404 ToType = it->getType();
1405 return true;
1406 }
1407 }
1408 return false;
1409}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001410
1411/// IsIntegralPromotion - Determines whether the conversion from the
1412/// expression From (whose potentially-adjusted type is FromType) to
1413/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1414/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001415bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001416 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001417 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001418 if (!To) {
1419 return false;
1420 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001421
1422 // An rvalue of type char, signed char, unsigned char, short int, or
1423 // unsigned short int can be converted to an rvalue of type int if
1424 // int can represent all the values of the source type; otherwise,
1425 // the source rvalue can be converted to an rvalue of type unsigned
1426 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001427 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1428 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001429 if (// We can promote any signed, promotable integer type to an int
1430 (FromType->isSignedIntegerType() ||
1431 // We can promote any unsigned integer type whose size is
1432 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001433 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001434 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001435 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001436 }
1437
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001438 return To->getKind() == BuiltinType::UInt;
1439 }
1440
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001441 // C++0x [conv.prom]p3:
1442 // A prvalue of an unscoped enumeration type whose underlying type is not
1443 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1444 // following types that can represent all the values of the enumeration
1445 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1446 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001447 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001448 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001449 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001450 // with lowest integer conversion rank (4.13) greater than the rank of long
1451 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001452 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001453 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1454 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1455 // provided for a scoped enumeration.
1456 if (FromEnumType->getDecl()->isScoped())
1457 return false;
1458
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001459 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001460 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001461 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001462 return Context.hasSameUnqualifiedType(ToType,
1463 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001464 }
John McCall56774992009-12-09 09:09:27 +00001465
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001466 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001467 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1468 // to an rvalue a prvalue of the first of the following types that can
1469 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001470 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001471 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001472 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001473 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001474 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001475 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001476 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001477 // Determine whether the type we're converting from is signed or
1478 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001479 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001480 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001481
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001482 // The types we'll try to promote to, in the appropriate
1483 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001484 QualType PromoteTypes[6] = {
1485 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001486 Context.LongTy, Context.UnsignedLongTy ,
1487 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001488 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001489 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001490 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1491 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001492 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001493 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1494 // We found the type that we can promote to. If this is the
1495 // type we wanted, we have a promotion. Otherwise, no
1496 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001497 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001498 }
1499 }
1500 }
1501
1502 // An rvalue for an integral bit-field (9.6) can be converted to an
1503 // rvalue of type int if int can represent all the values of the
1504 // bit-field; otherwise, it can be converted to unsigned int if
1505 // unsigned int can represent all the values of the bit-field. If
1506 // the bit-field is larger yet, no integral promotion applies to
1507 // it. If the bit-field has an enumerated type, it is treated as any
1508 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001509 // FIXME: We should delay checking of bit-fields until we actually perform the
1510 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001511 using llvm::APSInt;
1512 if (From)
1513 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001514 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001515 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001516 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1517 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1518 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001519
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001520 // Are we promoting to an int from a bitfield that fits in an int?
1521 if (BitWidth < ToSize ||
1522 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1523 return To->getKind() == BuiltinType::Int;
1524 }
Mike Stump11289f42009-09-09 15:08:12 +00001525
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001526 // Are we promoting to an unsigned int from an unsigned bitfield
1527 // that fits into an unsigned int?
1528 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1529 return To->getKind() == BuiltinType::UInt;
1530 }
Mike Stump11289f42009-09-09 15:08:12 +00001531
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001532 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001533 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001534 }
Mike Stump11289f42009-09-09 15:08:12 +00001535
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001536 // An rvalue of type bool can be converted to an rvalue of type int,
1537 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001538 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001539 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001540 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001541
1542 return false;
1543}
1544
1545/// IsFloatingPointPromotion - Determines whether the conversion from
1546/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1547/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001548bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001549 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1550 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001551 /// An rvalue of type float can be converted to an rvalue of type
1552 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001553 if (FromBuiltin->getKind() == BuiltinType::Float &&
1554 ToBuiltin->getKind() == BuiltinType::Double)
1555 return true;
1556
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001557 // C99 6.3.1.5p1:
1558 // When a float is promoted to double or long double, or a
1559 // double is promoted to long double [...].
1560 if (!getLangOptions().CPlusPlus &&
1561 (FromBuiltin->getKind() == BuiltinType::Float ||
1562 FromBuiltin->getKind() == BuiltinType::Double) &&
1563 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1564 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001565
1566 // Half can be promoted to float.
1567 if (FromBuiltin->getKind() == BuiltinType::Half &&
1568 ToBuiltin->getKind() == BuiltinType::Float)
1569 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001570 }
1571
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001572 return false;
1573}
1574
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001575/// \brief Determine if a conversion is a complex promotion.
1576///
1577/// A complex promotion is defined as a complex -> complex conversion
1578/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001579/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001580bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001581 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001582 if (!FromComplex)
1583 return false;
1584
John McCall9dd450b2009-09-21 23:43:11 +00001585 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001586 if (!ToComplex)
1587 return false;
1588
1589 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001590 ToComplex->getElementType()) ||
1591 IsIntegralPromotion(0, FromComplex->getElementType(),
1592 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001593}
1594
Douglas Gregor237f96c2008-11-26 23:31:11 +00001595/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1596/// the pointer type FromPtr to a pointer to type ToPointee, with the
1597/// same type qualifiers as FromPtr has on its pointee type. ToType,
1598/// if non-empty, will be a pointer to ToType that may or may not have
1599/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001600///
Mike Stump11289f42009-09-09 15:08:12 +00001601static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001602BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001603 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001604 ASTContext &Context,
1605 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001606 assert((FromPtr->getTypeClass() == Type::Pointer ||
1607 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1608 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001609
John McCall31168b02011-06-15 23:02:42 +00001610 /// Conversions to 'id' subsume cv-qualifier conversions.
1611 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001612 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001613
1614 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001615 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001616 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001617 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001618
John McCall31168b02011-06-15 23:02:42 +00001619 if (StripObjCLifetime)
1620 Quals.removeObjCLifetime();
1621
Mike Stump11289f42009-09-09 15:08:12 +00001622 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001623 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001624 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001625 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001626 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001627
1628 // Build a pointer to ToPointee. It has the right qualifiers
1629 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001630 if (isa<ObjCObjectPointerType>(ToType))
1631 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001632 return Context.getPointerType(ToPointee);
1633 }
1634
1635 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001636 QualType QualifiedCanonToPointee
1637 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001638
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001639 if (isa<ObjCObjectPointerType>(ToType))
1640 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1641 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001642}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001643
Mike Stump11289f42009-09-09 15:08:12 +00001644static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001645 bool InOverloadResolution,
1646 ASTContext &Context) {
1647 // Handle value-dependent integral null pointer constants correctly.
1648 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1649 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001650 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001651 return !InOverloadResolution;
1652
Douglas Gregor56751b52009-09-25 04:25:58 +00001653 return Expr->isNullPointerConstant(Context,
1654 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1655 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001656}
Mike Stump11289f42009-09-09 15:08:12 +00001657
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001658/// IsPointerConversion - Determines whether the conversion of the
1659/// expression From, which has the (possibly adjusted) type FromType,
1660/// can be converted to the type ToType via a pointer conversion (C++
1661/// 4.10). If so, returns true and places the converted type (that
1662/// might differ from ToType in its cv-qualifiers at some level) into
1663/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001664///
Douglas Gregora29dc052008-11-27 01:19:21 +00001665/// This routine also supports conversions to and from block pointers
1666/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1667/// pointers to interfaces. FIXME: Once we've determined the
1668/// appropriate overloading rules for Objective-C, we may want to
1669/// split the Objective-C checks into a different routine; however,
1670/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001671/// conversions, so for now they live here. IncompatibleObjC will be
1672/// set if the conversion is an allowed Objective-C conversion that
1673/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001674bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001675 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001676 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001677 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001678 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001679 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1680 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001681 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001682
Mike Stump11289f42009-09-09 15:08:12 +00001683 // Conversion from a null pointer constant to any Objective-C pointer type.
1684 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001685 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001686 ConvertedType = ToType;
1687 return true;
1688 }
1689
Douglas Gregor231d1c62008-11-27 00:15:41 +00001690 // Blocks: Block pointers can be converted to void*.
1691 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001692 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001693 ConvertedType = ToType;
1694 return true;
1695 }
1696 // Blocks: A null pointer constant can be converted to a block
1697 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001698 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001699 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001700 ConvertedType = ToType;
1701 return true;
1702 }
1703
Sebastian Redl576fd422009-05-10 18:38:11 +00001704 // If the left-hand-side is nullptr_t, the right side can be a null
1705 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001706 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001707 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001708 ConvertedType = ToType;
1709 return true;
1710 }
1711
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001712 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001713 if (!ToTypePtr)
1714 return false;
1715
1716 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001717 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001718 ConvertedType = ToType;
1719 return true;
1720 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001721
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001722 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001723 // , including objective-c pointers.
1724 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001725 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1726 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001727 ConvertedType = BuildSimilarlyQualifiedPointerType(
1728 FromType->getAs<ObjCObjectPointerType>(),
1729 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001730 ToType, Context);
1731 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001732 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001733 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001734 if (!FromTypePtr)
1735 return false;
1736
1737 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001738
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001739 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001740 // pointer conversion, so don't do all of the work below.
1741 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1742 return false;
1743
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001744 // An rvalue of type "pointer to cv T," where T is an object type,
1745 // can be converted to an rvalue of type "pointer to cv void" (C++
1746 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001747 if (FromPointeeType->isIncompleteOrObjectType() &&
1748 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001749 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001750 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001751 ToType, Context,
1752 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001753 return true;
1754 }
1755
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001756 // MSVC allows implicit function to void* type conversion.
Francois Pichet0706d202011-09-17 17:15:52 +00001757 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001758 ToPointeeType->isVoidType()) {
1759 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1760 ToPointeeType,
1761 ToType, Context);
1762 return true;
1763 }
1764
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001765 // When we're overloading in C, we allow a special kind of pointer
1766 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001767 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001768 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001769 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001770 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001771 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001772 return true;
1773 }
1774
Douglas Gregor5c407d92008-10-23 00:40:37 +00001775 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001776 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001777 // An rvalue of type "pointer to cv D," where D is a class type,
1778 // can be converted to an rvalue of type "pointer to cv B," where
1779 // B is a base class (clause 10) of D. If B is an inaccessible
1780 // (clause 11) or ambiguous (10.2) base class of D, a program that
1781 // necessitates this conversion is ill-formed. The result of the
1782 // conversion is a pointer to the base class sub-object of the
1783 // derived class object. The null pointer value is converted to
1784 // the null pointer value of the destination type.
1785 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001786 // Note that we do not check for ambiguity or inaccessibility
1787 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001788 if (getLangOptions().CPlusPlus &&
1789 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001790 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001791 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001792 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001793 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001794 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001795 ToType, Context);
1796 return true;
1797 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001798
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001799 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1800 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1801 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1802 ToPointeeType,
1803 ToType, Context);
1804 return true;
1805 }
1806
Douglas Gregora119f102008-12-19 19:13:09 +00001807 return false;
1808}
Douglas Gregoraec25842011-04-26 23:16:46 +00001809
1810/// \brief Adopt the given qualifiers for the given type.
1811static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1812 Qualifiers TQs = T.getQualifiers();
1813
1814 // Check whether qualifiers already match.
1815 if (TQs == Qs)
1816 return T;
1817
1818 if (Qs.compatiblyIncludes(TQs))
1819 return Context.getQualifiedType(T, Qs);
1820
1821 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1822}
Douglas Gregora119f102008-12-19 19:13:09 +00001823
1824/// isObjCPointerConversion - Determines whether this is an
1825/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1826/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001827bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001828 QualType& ConvertedType,
1829 bool &IncompatibleObjC) {
1830 if (!getLangOptions().ObjC1)
1831 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001832
Douglas Gregoraec25842011-04-26 23:16:46 +00001833 // The set of qualifiers on the type we're converting from.
1834 Qualifiers FromQualifiers = FromType.getQualifiers();
1835
Steve Naroff7cae42b2009-07-10 23:34:53 +00001836 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001837 const ObjCObjectPointerType* ToObjCPtr =
1838 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001839 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001840 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001841
Steve Naroff7cae42b2009-07-10 23:34:53 +00001842 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001843 // If the pointee types are the same (ignoring qualifications),
1844 // then this is not a pointer conversion.
1845 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1846 FromObjCPtr->getPointeeType()))
1847 return false;
1848
Douglas Gregoraec25842011-04-26 23:16:46 +00001849 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00001850 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001851 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001852 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001853 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001854 return true;
1855 }
1856 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001857 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001858 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001859 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001860 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001861 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001862 return true;
1863 }
1864 // Objective C++: We're able to convert from a pointer to an
1865 // interface to a pointer to a different interface.
1866 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001867 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1868 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1869 if (getLangOptions().CPlusPlus && LHS && RHS &&
1870 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1871 FromObjCPtr->getPointeeType()))
1872 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001873 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001874 ToObjCPtr->getPointeeType(),
1875 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001876 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001877 return true;
1878 }
1879
1880 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1881 // Okay: this is some kind of implicit downcast of Objective-C
1882 // interfaces, which is permitted. However, we're going to
1883 // complain about it.
1884 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001885 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001886 ToObjCPtr->getPointeeType(),
1887 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001888 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001889 return true;
1890 }
Mike Stump11289f42009-09-09 15:08:12 +00001891 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001892 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001893 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001894 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001895 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001896 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001897 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001898 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001899 // to a block pointer type.
1900 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001901 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001902 return true;
1903 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001904 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001905 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001906 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001907 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001908 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001909 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00001910 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001911 return true;
1912 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001913 else
Douglas Gregora119f102008-12-19 19:13:09 +00001914 return false;
1915
Douglas Gregor033f56d2008-12-23 00:53:59 +00001916 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001917 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001918 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001919 else if (const BlockPointerType *FromBlockPtr =
1920 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001921 FromPointeeType = FromBlockPtr->getPointeeType();
1922 else
Douglas Gregora119f102008-12-19 19:13:09 +00001923 return false;
1924
Douglas Gregora119f102008-12-19 19:13:09 +00001925 // If we have pointers to pointers, recursively check whether this
1926 // is an Objective-C conversion.
1927 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1928 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1929 IncompatibleObjC)) {
1930 // We always complain about this conversion.
1931 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001932 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001933 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001934 return true;
1935 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001936 // Allow conversion of pointee being objective-c pointer to another one;
1937 // as in I* to id.
1938 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1939 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1940 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1941 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00001942
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001943 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001944 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001945 return true;
1946 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001947
Douglas Gregor033f56d2008-12-23 00:53:59 +00001948 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001949 // differences in the argument and result types are in Objective-C
1950 // pointer conversions. If so, we permit the conversion (but
1951 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001952 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001953 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001954 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001955 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001956 if (FromFunctionType && ToFunctionType) {
1957 // If the function types are exactly the same, this isn't an
1958 // Objective-C pointer conversion.
1959 if (Context.getCanonicalType(FromPointeeType)
1960 == Context.getCanonicalType(ToPointeeType))
1961 return false;
1962
1963 // Perform the quick checks that will tell us whether these
1964 // function types are obviously different.
1965 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1966 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1967 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1968 return false;
1969
1970 bool HasObjCConversion = false;
1971 if (Context.getCanonicalType(FromFunctionType->getResultType())
1972 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1973 // Okay, the types match exactly. Nothing to do.
1974 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1975 ToFunctionType->getResultType(),
1976 ConvertedType, IncompatibleObjC)) {
1977 // Okay, we have an Objective-C pointer conversion.
1978 HasObjCConversion = true;
1979 } else {
1980 // Function types are too different. Abort.
1981 return false;
1982 }
Mike Stump11289f42009-09-09 15:08:12 +00001983
Douglas Gregora119f102008-12-19 19:13:09 +00001984 // Check argument types.
1985 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1986 ArgIdx != NumArgs; ++ArgIdx) {
1987 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1988 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1989 if (Context.getCanonicalType(FromArgType)
1990 == Context.getCanonicalType(ToArgType)) {
1991 // Okay, the types match exactly. Nothing to do.
1992 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1993 ConvertedType, IncompatibleObjC)) {
1994 // Okay, we have an Objective-C pointer conversion.
1995 HasObjCConversion = true;
1996 } else {
1997 // Argument types are too different. Abort.
1998 return false;
1999 }
2000 }
2001
2002 if (HasObjCConversion) {
2003 // We had an Objective-C conversion. Allow this pointer
2004 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00002005 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00002006 IncompatibleObjC = true;
2007 return true;
2008 }
2009 }
2010
Sebastian Redl72b597d2009-01-25 19:43:20 +00002011 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002012}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002013
John McCall31168b02011-06-15 23:02:42 +00002014/// \brief Determine whether this is an Objective-C writeback conversion,
2015/// used for parameter passing when performing automatic reference counting.
2016///
2017/// \param FromType The type we're converting form.
2018///
2019/// \param ToType The type we're converting to.
2020///
2021/// \param ConvertedType The type that will be produced after applying
2022/// this conversion.
2023bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2024 QualType &ConvertedType) {
2025 if (!getLangOptions().ObjCAutoRefCount ||
2026 Context.hasSameUnqualifiedType(FromType, ToType))
2027 return false;
2028
2029 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2030 QualType ToPointee;
2031 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2032 ToPointee = ToPointer->getPointeeType();
2033 else
2034 return false;
2035
2036 Qualifiers ToQuals = ToPointee.getQualifiers();
2037 if (!ToPointee->isObjCLifetimeType() ||
2038 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2039 !ToQuals.withoutObjCGLifetime().empty())
2040 return false;
2041
2042 // Argument must be a pointer to __strong to __weak.
2043 QualType FromPointee;
2044 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2045 FromPointee = FromPointer->getPointeeType();
2046 else
2047 return false;
2048
2049 Qualifiers FromQuals = FromPointee.getQualifiers();
2050 if (!FromPointee->isObjCLifetimeType() ||
2051 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2052 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2053 return false;
2054
2055 // Make sure that we have compatible qualifiers.
2056 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2057 if (!ToQuals.compatiblyIncludes(FromQuals))
2058 return false;
2059
2060 // Remove qualifiers from the pointee type we're converting from; they
2061 // aren't used in the compatibility check belong, and we'll be adding back
2062 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2063 FromPointee = FromPointee.getUnqualifiedType();
2064
2065 // The unqualified form of the pointee types must be compatible.
2066 ToPointee = ToPointee.getUnqualifiedType();
2067 bool IncompatibleObjC;
2068 if (Context.typesAreCompatible(FromPointee, ToPointee))
2069 FromPointee = ToPointee;
2070 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2071 IncompatibleObjC))
2072 return false;
2073
2074 /// \brief Construct the type we're converting to, which is a pointer to
2075 /// __autoreleasing pointee.
2076 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2077 ConvertedType = Context.getPointerType(FromPointee);
2078 return true;
2079}
2080
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002081bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2082 QualType& ConvertedType) {
2083 QualType ToPointeeType;
2084 if (const BlockPointerType *ToBlockPtr =
2085 ToType->getAs<BlockPointerType>())
2086 ToPointeeType = ToBlockPtr->getPointeeType();
2087 else
2088 return false;
2089
2090 QualType FromPointeeType;
2091 if (const BlockPointerType *FromBlockPtr =
2092 FromType->getAs<BlockPointerType>())
2093 FromPointeeType = FromBlockPtr->getPointeeType();
2094 else
2095 return false;
2096 // We have pointer to blocks, check whether the only
2097 // differences in the argument and result types are in Objective-C
2098 // pointer conversions. If so, we permit the conversion.
2099
2100 const FunctionProtoType *FromFunctionType
2101 = FromPointeeType->getAs<FunctionProtoType>();
2102 const FunctionProtoType *ToFunctionType
2103 = ToPointeeType->getAs<FunctionProtoType>();
2104
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002105 if (!FromFunctionType || !ToFunctionType)
2106 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002107
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002108 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002109 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002110
2111 // Perform the quick checks that will tell us whether these
2112 // function types are obviously different.
2113 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2114 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2115 return false;
2116
2117 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2118 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2119 if (FromEInfo != ToEInfo)
2120 return false;
2121
2122 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002123 if (Context.hasSameType(FromFunctionType->getResultType(),
2124 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002125 // Okay, the types match exactly. Nothing to do.
2126 } else {
2127 QualType RHS = FromFunctionType->getResultType();
2128 QualType LHS = ToFunctionType->getResultType();
2129 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2130 !RHS.hasQualifiers() && LHS.hasQualifiers())
2131 LHS = LHS.getUnqualifiedType();
2132
2133 if (Context.hasSameType(RHS,LHS)) {
2134 // OK exact match.
2135 } else if (isObjCPointerConversion(RHS, LHS,
2136 ConvertedType, IncompatibleObjC)) {
2137 if (IncompatibleObjC)
2138 return false;
2139 // Okay, we have an Objective-C pointer conversion.
2140 }
2141 else
2142 return false;
2143 }
2144
2145 // Check argument types.
2146 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2147 ArgIdx != NumArgs; ++ArgIdx) {
2148 IncompatibleObjC = false;
2149 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2150 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2151 if (Context.hasSameType(FromArgType, ToArgType)) {
2152 // Okay, the types match exactly. Nothing to do.
2153 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2154 ConvertedType, IncompatibleObjC)) {
2155 if (IncompatibleObjC)
2156 return false;
2157 // Okay, we have an Objective-C pointer conversion.
2158 } else
2159 // Argument types are too different. Abort.
2160 return false;
2161 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002162 if (LangOpts.ObjCAutoRefCount &&
2163 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2164 ToFunctionType))
2165 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002166
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002167 ConvertedType = ToType;
2168 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002169}
2170
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002171/// FunctionArgTypesAreEqual - This routine checks two function proto types
2172/// for equlity of their argument types. Caller has already checked that
2173/// they have same number of arguments. This routine assumes that Objective-C
2174/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002175bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00002176 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002177 if (!getLangOptions().ObjC1)
2178 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2179 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002180
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002181 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2182 N = NewType->arg_type_begin(),
2183 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2184 QualType ToType = (*O);
2185 QualType FromType = (*N);
2186 if (ToType != FromType) {
2187 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2188 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002189 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2190 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2191 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2192 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002193 continue;
2194 }
John McCall8b07ec22010-05-15 11:32:37 +00002195 else if (const ObjCObjectPointerType *PTTo =
2196 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002197 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002198 FromType->getAs<ObjCObjectPointerType>())
2199 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2200 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002201 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002202 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002203 }
2204 }
2205 return true;
2206}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002207
Douglas Gregor39c16d42008-10-24 04:54:22 +00002208/// CheckPointerConversion - Check the pointer conversion from the
2209/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002210/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002211/// conversions for which IsPointerConversion has already returned
2212/// true. It returns true and produces a diagnostic if there was an
2213/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002214bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002215 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002216 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002217 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002218 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002219 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002220
John McCall8cb679e2010-11-15 09:13:47 +00002221 Kind = CK_BitCast;
2222
Chandler Carruthffab8732011-04-09 07:32:05 +00002223 if (!IsCStyleOrFunctionalCast &&
2224 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2225 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2226 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002227 PDiag(diag::warn_impcast_bool_to_null_pointer)
2228 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002229
John McCall9320b872011-09-09 05:25:32 +00002230 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2231 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002232 QualType FromPointeeType = FromPtrType->getPointeeType(),
2233 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002234
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002235 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2236 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002237 // We must have a derived-to-base conversion. Check an
2238 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002239 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2240 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002241 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002242 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002243 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002244
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002245 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002246 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002247 }
2248 }
John McCall9320b872011-09-09 05:25:32 +00002249 } else if (const ObjCObjectPointerType *ToPtrType =
2250 ToType->getAs<ObjCObjectPointerType>()) {
2251 if (const ObjCObjectPointerType *FromPtrType =
2252 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002253 // Objective-C++ conversions are always okay.
2254 // FIXME: We should have a different class of conversions for the
2255 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002256 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002257 return false;
John McCall9320b872011-09-09 05:25:32 +00002258 } else if (FromType->isBlockPointerType()) {
2259 Kind = CK_BlockPointerToObjCPointerCast;
2260 } else {
2261 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002262 }
John McCall9320b872011-09-09 05:25:32 +00002263 } else if (ToType->isBlockPointerType()) {
2264 if (!FromType->isBlockPointerType())
2265 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002266 }
John McCall8cb679e2010-11-15 09:13:47 +00002267
2268 // We shouldn't fall into this case unless it's valid for other
2269 // reasons.
2270 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2271 Kind = CK_NullToPointer;
2272
Douglas Gregor39c16d42008-10-24 04:54:22 +00002273 return false;
2274}
2275
Sebastian Redl72b597d2009-01-25 19:43:20 +00002276/// IsMemberPointerConversion - Determines whether the conversion of the
2277/// expression From, which has the (possibly adjusted) type FromType, can be
2278/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2279/// If so, returns true and places the converted type (that might differ from
2280/// ToType in its cv-qualifiers at some level) into ConvertedType.
2281bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002282 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002283 bool InOverloadResolution,
2284 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002285 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002286 if (!ToTypePtr)
2287 return false;
2288
2289 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002290 if (From->isNullPointerConstant(Context,
2291 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2292 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002293 ConvertedType = ToType;
2294 return true;
2295 }
2296
2297 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002298 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002299 if (!FromTypePtr)
2300 return false;
2301
2302 // A pointer to member of B can be converted to a pointer to member of D,
2303 // where D is derived from B (C++ 4.11p2).
2304 QualType FromClass(FromTypePtr->getClass(), 0);
2305 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002306
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002307 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2308 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2309 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002310 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2311 ToClass.getTypePtr());
2312 return true;
2313 }
2314
2315 return false;
2316}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002317
Sebastian Redl72b597d2009-01-25 19:43:20 +00002318/// CheckMemberPointerConversion - Check the member pointer conversion from the
2319/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002320/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002321/// for which IsMemberPointerConversion has already returned true. It returns
2322/// true and produces a diagnostic if there was an error, or returns false
2323/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002324bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002325 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002326 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002327 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002328 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002329 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002330 if (!FromPtrType) {
2331 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002332 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002333 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002334 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002335 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002336 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002337 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002338
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002339 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002340 assert(ToPtrType && "No member pointer cast has a target type "
2341 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002342
Sebastian Redled8f2002009-01-28 18:33:18 +00002343 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2344 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002345
Sebastian Redled8f2002009-01-28 18:33:18 +00002346 // FIXME: What about dependent types?
2347 assert(FromClass->isRecordType() && "Pointer into non-class.");
2348 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002349
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002350 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002351 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002352 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2353 assert(DerivationOkay &&
2354 "Should not have been called if derivation isn't OK.");
2355 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002356
Sebastian Redled8f2002009-01-28 18:33:18 +00002357 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2358 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002359 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2360 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2361 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2362 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002363 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002364
Douglas Gregor89ee6822009-02-28 01:32:25 +00002365 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002366 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2367 << FromClass << ToClass << QualType(VBase, 0)
2368 << From->getSourceRange();
2369 return true;
2370 }
2371
John McCall5b0829a2010-02-10 09:31:12 +00002372 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002373 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2374 Paths.front(),
2375 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002376
Anders Carlssond7923c62009-08-22 23:33:40 +00002377 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002378 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002379 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002380 return false;
2381}
2382
Douglas Gregor9a657932008-10-21 23:43:52 +00002383/// IsQualificationConversion - Determines whether the conversion from
2384/// an rvalue of type FromType to ToType is a qualification conversion
2385/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002386///
2387/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2388/// when the qualification conversion involves a change in the Objective-C
2389/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002390bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002391Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002392 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002393 FromType = Context.getCanonicalType(FromType);
2394 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002395 ObjCLifetimeConversion = false;
2396
Douglas Gregor9a657932008-10-21 23:43:52 +00002397 // If FromType and ToType are the same type, this is not a
2398 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002399 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002400 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002401
Douglas Gregor9a657932008-10-21 23:43:52 +00002402 // (C++ 4.4p4):
2403 // A conversion can add cv-qualifiers at levels other than the first
2404 // in multi-level pointers, subject to the following rules: [...]
2405 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002406 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002407 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002408 // Within each iteration of the loop, we check the qualifiers to
2409 // determine if this still looks like a qualification
2410 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002411 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002412 // until there are no more pointers or pointers-to-members left to
2413 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002414 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002415
Douglas Gregor90609aa2011-04-25 18:40:17 +00002416 Qualifiers FromQuals = FromType.getQualifiers();
2417 Qualifiers ToQuals = ToType.getQualifiers();
2418
John McCall31168b02011-06-15 23:02:42 +00002419 // Objective-C ARC:
2420 // Check Objective-C lifetime conversions.
2421 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2422 UnwrappedAnyPointer) {
2423 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2424 ObjCLifetimeConversion = true;
2425 FromQuals.removeObjCLifetime();
2426 ToQuals.removeObjCLifetime();
2427 } else {
2428 // Qualification conversions cannot cast between different
2429 // Objective-C lifetime qualifiers.
2430 return false;
2431 }
2432 }
2433
Douglas Gregorf30053d2011-05-08 06:09:53 +00002434 // Allow addition/removal of GC attributes but not changing GC attributes.
2435 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2436 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2437 FromQuals.removeObjCGCAttr();
2438 ToQuals.removeObjCGCAttr();
2439 }
2440
Douglas Gregor9a657932008-10-21 23:43:52 +00002441 // -- for every j > 0, if const is in cv 1,j then const is in cv
2442 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002443 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002444 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002445
Douglas Gregor9a657932008-10-21 23:43:52 +00002446 // -- if the cv 1,j and cv 2,j are different, then const is in
2447 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002448 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002449 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002450 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002451
Douglas Gregor9a657932008-10-21 23:43:52 +00002452 // Keep track of whether all prior cv-qualifiers in the "to" type
2453 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002454 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002455 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002456 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002457
2458 // We are left with FromType and ToType being the pointee types
2459 // after unwrapping the original FromType and ToType the same number
2460 // of types. If we unwrapped any pointers, and if FromType and
2461 // ToType have the same unqualified type (since we checked
2462 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002463 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002464}
2465
Douglas Gregor576e98c2009-01-30 23:27:23 +00002466/// Determines whether there is a user-defined conversion sequence
2467/// (C++ [over.ics.user]) that converts expression From to the type
2468/// ToType. If such a conversion exists, User will contain the
2469/// user-defined conversion sequence that performs such a conversion
2470/// and this routine will return true. Otherwise, this routine returns
2471/// false and User is unspecified.
2472///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002473/// \param AllowExplicit true if the conversion should consider C++0x
2474/// "explicit" conversion functions as well as non-explicit conversion
2475/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002476static OverloadingResult
2477IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2478 UserDefinedConversionSequence& User,
2479 OverloadCandidateSet& CandidateSet,
2480 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002481 // Whether we will only visit constructors.
2482 bool ConstructorsOnly = false;
2483
2484 // If the type we are conversion to is a class type, enumerate its
2485 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002486 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002487 // C++ [over.match.ctor]p1:
2488 // When objects of class type are direct-initialized (8.5), or
2489 // copy-initialized from an expression of the same or a
2490 // derived class type (8.5), overload resolution selects the
2491 // constructor. [...] For copy-initialization, the candidate
2492 // functions are all the converting constructors (12.3.1) of
2493 // that class. The argument list is the expression-list within
2494 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002495 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002496 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002497 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002498 ConstructorsOnly = true;
2499
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002500 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2501 // RequireCompleteType may have returned true due to some invalid decl
2502 // during template instantiation, but ToType may be complete enough now
2503 // to try to recover.
2504 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002505 // We're not going to find any constructors.
2506 } else if (CXXRecordDecl *ToRecordDecl
2507 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002508 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002509 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002510 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002511 NamedDecl *D = *Con;
2512 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2513
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002514 // Find the constructor (which may be a template).
2515 CXXConstructorDecl *Constructor = 0;
2516 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002517 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002518 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002519 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002520 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2521 else
John McCalla0296f72010-03-19 07:35:19 +00002522 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002523
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002524 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002525 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002526 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002527 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2528 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002529 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002530 /*SuppressUserConversions=*/
2531 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002532 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002533 // Allow one user-defined conversion when user specifies a
2534 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002535 S.AddOverloadCandidate(Constructor, FoundDecl,
2536 &From, 1, CandidateSet,
2537 /*SuppressUserConversions=*/
2538 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002539 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002540 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002541 }
2542 }
2543
Douglas Gregor5ab11652010-04-17 22:01:05 +00002544 // Enumerate conversion functions, if we're allowed to.
2545 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002546 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2547 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002548 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002549 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002550 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002551 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002552 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2553 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002554 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002555 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002556 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002557 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002558 DeclAccessPair FoundDecl = I.getPair();
2559 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002560 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2561 if (isa<UsingShadowDecl>(D))
2562 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2563
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002564 CXXConversionDecl *Conv;
2565 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002566 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2567 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002568 else
John McCallda4458e2010-03-31 01:36:47 +00002569 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002570
2571 if (AllowExplicit || !Conv->isExplicit()) {
2572 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002573 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2574 ActingContext, From, ToType,
2575 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002576 else
John McCall5c32be02010-08-24 20:38:10 +00002577 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2578 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002579 }
2580 }
2581 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002582 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002583
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002584 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2585
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002586 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002587 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002588 case OR_Success:
2589 // Record the standard conversion we used and the conversion function.
2590 if (CXXConstructorDecl *Constructor
2591 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002592 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2593
John McCall5c32be02010-08-24 20:38:10 +00002594 // C++ [over.ics.user]p1:
2595 // If the user-defined conversion is specified by a
2596 // constructor (12.3.1), the initial standard conversion
2597 // sequence converts the source type to the type required by
2598 // the argument of the constructor.
2599 //
2600 QualType ThisType = Constructor->getThisType(S.Context);
2601 if (Best->Conversions[0].isEllipsis())
2602 User.EllipsisConversion = true;
2603 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002604 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002605 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002606 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002607 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002608 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00002609 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002610 User.After.setAsIdentityConversion();
2611 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2612 User.After.setAllToTypes(ToType);
2613 return OR_Success;
2614 } else if (CXXConversionDecl *Conversion
2615 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002616 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2617
John McCall5c32be02010-08-24 20:38:10 +00002618 // C++ [over.ics.user]p1:
2619 //
2620 // [...] If the user-defined conversion is specified by a
2621 // conversion function (12.3.2), the initial standard
2622 // conversion sequence converts the source type to the
2623 // implicit object parameter of the conversion function.
2624 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002625 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002626 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00002627 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002628 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002629
John McCall5c32be02010-08-24 20:38:10 +00002630 // C++ [over.ics.user]p2:
2631 // The second standard conversion sequence converts the
2632 // result of the user-defined conversion to the target type
2633 // for the sequence. Since an implicit conversion sequence
2634 // is an initialization, the special rules for
2635 // initialization by user-defined conversion apply when
2636 // selecting the best user-defined conversion for a
2637 // user-defined conversion sequence (see 13.3.3 and
2638 // 13.3.3.1).
2639 User.After = Best->FinalConversion;
2640 return OR_Success;
2641 } else {
2642 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002643 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002644 }
2645
John McCall5c32be02010-08-24 20:38:10 +00002646 case OR_No_Viable_Function:
2647 return OR_No_Viable_Function;
2648 case OR_Deleted:
2649 // No conversion here! We're done.
2650 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002651
John McCall5c32be02010-08-24 20:38:10 +00002652 case OR_Ambiguous:
2653 return OR_Ambiguous;
2654 }
2655
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002656 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002657}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002658
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002659bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002660Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002661 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002662 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002663 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002664 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002665 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002666 if (OvResult == OR_Ambiguous)
2667 Diag(From->getSourceRange().getBegin(),
2668 diag::err_typecheck_ambiguous_condition)
2669 << From->getType() << ToType << From->getSourceRange();
2670 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2671 Diag(From->getSourceRange().getBegin(),
2672 diag::err_typecheck_nonviable_condition)
2673 << From->getType() << ToType << From->getSourceRange();
2674 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002675 return false;
John McCall5c32be02010-08-24 20:38:10 +00002676 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002677 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002678}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002679
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002680/// CompareImplicitConversionSequences - Compare two implicit
2681/// conversion sequences to determine whether one is better than the
2682/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002683static ImplicitConversionSequence::CompareKind
2684CompareImplicitConversionSequences(Sema &S,
2685 const ImplicitConversionSequence& ICS1,
2686 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002687{
2688 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2689 // conversion sequences (as defined in 13.3.3.1)
2690 // -- a standard conversion sequence (13.3.3.1.1) is a better
2691 // conversion sequence than a user-defined conversion sequence or
2692 // an ellipsis conversion sequence, and
2693 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2694 // conversion sequence than an ellipsis conversion sequence
2695 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002696 //
John McCall0d1da222010-01-12 00:44:57 +00002697 // C++0x [over.best.ics]p10:
2698 // For the purpose of ranking implicit conversion sequences as
2699 // described in 13.3.3.2, the ambiguous conversion sequence is
2700 // treated as a user-defined sequence that is indistinguishable
2701 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002702 if (ICS1.getKindRank() < ICS2.getKindRank())
2703 return ImplicitConversionSequence::Better;
2704 else if (ICS2.getKindRank() < ICS1.getKindRank())
2705 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002706
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002707 // The following checks require both conversion sequences to be of
2708 // the same kind.
2709 if (ICS1.getKind() != ICS2.getKind())
2710 return ImplicitConversionSequence::Indistinguishable;
2711
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002712 // Two implicit conversion sequences of the same form are
2713 // indistinguishable conversion sequences unless one of the
2714 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002715 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002716 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002717 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002718 // User-defined conversion sequence U1 is a better conversion
2719 // sequence than another user-defined conversion sequence U2 if
2720 // they contain the same user-defined conversion function or
2721 // constructor and if the second standard conversion sequence of
2722 // U1 is better than the second standard conversion sequence of
2723 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002724 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002725 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002726 return CompareStandardConversionSequences(S,
2727 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002728 ICS2.UserDefined.After);
2729 }
2730
2731 return ImplicitConversionSequence::Indistinguishable;
2732}
2733
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002734static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2735 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2736 Qualifiers Quals;
2737 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002738 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002739 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002740
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002741 return Context.hasSameUnqualifiedType(T1, T2);
2742}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002743
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002744// Per 13.3.3.2p3, compare the given standard conversion sequences to
2745// determine if one is a proper subset of the other.
2746static ImplicitConversionSequence::CompareKind
2747compareStandardConversionSubsets(ASTContext &Context,
2748 const StandardConversionSequence& SCS1,
2749 const StandardConversionSequence& SCS2) {
2750 ImplicitConversionSequence::CompareKind Result
2751 = ImplicitConversionSequence::Indistinguishable;
2752
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002753 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002754 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00002755 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2756 return ImplicitConversionSequence::Better;
2757 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2758 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002759
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002760 if (SCS1.Second != SCS2.Second) {
2761 if (SCS1.Second == ICK_Identity)
2762 Result = ImplicitConversionSequence::Better;
2763 else if (SCS2.Second == ICK_Identity)
2764 Result = ImplicitConversionSequence::Worse;
2765 else
2766 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002767 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002768 return ImplicitConversionSequence::Indistinguishable;
2769
2770 if (SCS1.Third == SCS2.Third) {
2771 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2772 : ImplicitConversionSequence::Indistinguishable;
2773 }
2774
2775 if (SCS1.Third == ICK_Identity)
2776 return Result == ImplicitConversionSequence::Worse
2777 ? ImplicitConversionSequence::Indistinguishable
2778 : ImplicitConversionSequence::Better;
2779
2780 if (SCS2.Third == ICK_Identity)
2781 return Result == ImplicitConversionSequence::Better
2782 ? ImplicitConversionSequence::Indistinguishable
2783 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002784
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002785 return ImplicitConversionSequence::Indistinguishable;
2786}
2787
Douglas Gregore696ebb2011-01-26 14:52:12 +00002788/// \brief Determine whether one of the given reference bindings is better
2789/// than the other based on what kind of bindings they are.
2790static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2791 const StandardConversionSequence &SCS2) {
2792 // C++0x [over.ics.rank]p3b4:
2793 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2794 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002795 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002796 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002797 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002798 // reference*.
2799 //
2800 // FIXME: Rvalue references. We're going rogue with the above edits,
2801 // because the semantics in the current C++0x working paper (N3225 at the
2802 // time of this writing) break the standard definition of std::forward
2803 // and std::reference_wrapper when dealing with references to functions.
2804 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002805 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2806 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2807 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002808
Douglas Gregore696ebb2011-01-26 14:52:12 +00002809 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2810 SCS2.IsLvalueReference) ||
2811 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2812 !SCS2.IsLvalueReference);
2813}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002814
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002815/// CompareStandardConversionSequences - Compare two standard
2816/// conversion sequences to determine whether one is better than the
2817/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002818static ImplicitConversionSequence::CompareKind
2819CompareStandardConversionSequences(Sema &S,
2820 const StandardConversionSequence& SCS1,
2821 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002822{
2823 // Standard conversion sequence S1 is a better conversion sequence
2824 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2825
2826 // -- S1 is a proper subsequence of S2 (comparing the conversion
2827 // sequences in the canonical form defined by 13.3.3.1.1,
2828 // excluding any Lvalue Transformation; the identity conversion
2829 // sequence is considered to be a subsequence of any
2830 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002831 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002832 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002833 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002834
2835 // -- the rank of S1 is better than the rank of S2 (by the rules
2836 // defined below), or, if not that,
2837 ImplicitConversionRank Rank1 = SCS1.getRank();
2838 ImplicitConversionRank Rank2 = SCS2.getRank();
2839 if (Rank1 < Rank2)
2840 return ImplicitConversionSequence::Better;
2841 else if (Rank2 < Rank1)
2842 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002843
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002844 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2845 // are indistinguishable unless one of the following rules
2846 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002847
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002848 // A conversion that is not a conversion of a pointer, or
2849 // pointer to member, to bool is better than another conversion
2850 // that is such a conversion.
2851 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2852 return SCS2.isPointerConversionToBool()
2853 ? ImplicitConversionSequence::Better
2854 : ImplicitConversionSequence::Worse;
2855
Douglas Gregor5c407d92008-10-23 00:40:37 +00002856 // C++ [over.ics.rank]p4b2:
2857 //
2858 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002859 // conversion of B* to A* is better than conversion of B* to
2860 // void*, and conversion of A* to void* is better than conversion
2861 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002862 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002863 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002864 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002865 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002866 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2867 // Exactly one of the conversion sequences is a conversion to
2868 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002869 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2870 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002871 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2872 // Neither conversion sequence converts to a void pointer; compare
2873 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002874 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002875 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002876 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002877 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2878 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002879 // Both conversion sequences are conversions to void
2880 // pointers. Compare the source types to determine if there's an
2881 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002882 QualType FromType1 = SCS1.getFromType();
2883 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002884
2885 // Adjust the types we're converting from via the array-to-pointer
2886 // conversion, if we need to.
2887 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002888 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002889 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002890 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002891
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002892 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2893 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002894
John McCall5c32be02010-08-24 20:38:10 +00002895 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002896 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002897 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002898 return ImplicitConversionSequence::Worse;
2899
2900 // Objective-C++: If one interface is more specific than the
2901 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002902 const ObjCObjectPointerType* FromObjCPtr1
2903 = FromType1->getAs<ObjCObjectPointerType>();
2904 const ObjCObjectPointerType* FromObjCPtr2
2905 = FromType2->getAs<ObjCObjectPointerType>();
2906 if (FromObjCPtr1 && FromObjCPtr2) {
2907 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2908 FromObjCPtr2);
2909 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2910 FromObjCPtr1);
2911 if (AssignLeft != AssignRight) {
2912 return AssignLeft? ImplicitConversionSequence::Better
2913 : ImplicitConversionSequence::Worse;
2914 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002915 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002916 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002917
2918 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2919 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002920 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002921 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002922 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002923
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002924 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002925 // Check for a better reference binding based on the kind of bindings.
2926 if (isBetterReferenceBindingKind(SCS1, SCS2))
2927 return ImplicitConversionSequence::Better;
2928 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2929 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002930
Sebastian Redlb28b4072009-03-22 23:49:27 +00002931 // C++ [over.ics.rank]p3b4:
2932 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2933 // which the references refer are the same type except for
2934 // top-level cv-qualifiers, and the type to which the reference
2935 // initialized by S2 refers is more cv-qualified than the type
2936 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002937 QualType T1 = SCS1.getToType(2);
2938 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002939 T1 = S.Context.getCanonicalType(T1);
2940 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002941 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002942 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2943 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002944 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00002945 // Objective-C++ ARC: If the references refer to objects with different
2946 // lifetimes, prefer bindings that don't change lifetime.
2947 if (SCS1.ObjCLifetimeConversionBinding !=
2948 SCS2.ObjCLifetimeConversionBinding) {
2949 return SCS1.ObjCLifetimeConversionBinding
2950 ? ImplicitConversionSequence::Worse
2951 : ImplicitConversionSequence::Better;
2952 }
2953
Chandler Carruth8e543b32010-12-12 08:17:55 +00002954 // If the type is an array type, promote the element qualifiers to the
2955 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002956 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002957 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002958 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002959 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002960 if (T2.isMoreQualifiedThan(T1))
2961 return ImplicitConversionSequence::Better;
2962 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00002963 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002964 }
2965 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002966
Francois Pichet08d2fa02011-09-18 21:37:37 +00002967 // In Microsoft mode, prefer an integral conversion to a
2968 // floating-to-integral conversion if the integral conversion
2969 // is between types of the same size.
2970 // For example:
2971 // void f(float);
2972 // void f(int);
2973 // int main {
2974 // long a;
2975 // f(a);
2976 // }
2977 // Here, MSVC will call f(int) instead of generating a compile error
2978 // as clang will do in standard mode.
2979 if (S.getLangOptions().MicrosoftMode &&
2980 SCS1.Second == ICK_Integral_Conversion &&
2981 SCS2.Second == ICK_Floating_Integral &&
2982 S.Context.getTypeSize(SCS1.getFromType()) ==
2983 S.Context.getTypeSize(SCS1.getToType(2)))
2984 return ImplicitConversionSequence::Better;
2985
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002986 return ImplicitConversionSequence::Indistinguishable;
2987}
2988
2989/// CompareQualificationConversions - Compares two standard conversion
2990/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002991/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2992ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002993CompareQualificationConversions(Sema &S,
2994 const StandardConversionSequence& SCS1,
2995 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002996 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002997 // -- S1 and S2 differ only in their qualification conversion and
2998 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2999 // cv-qualification signature of type T1 is a proper subset of
3000 // the cv-qualification signature of type T2, and S1 is not the
3001 // deprecated string literal array-to-pointer conversion (4.2).
3002 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3003 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3004 return ImplicitConversionSequence::Indistinguishable;
3005
3006 // FIXME: the example in the standard doesn't use a qualification
3007 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003008 QualType T1 = SCS1.getToType(2);
3009 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00003010 T1 = S.Context.getCanonicalType(T1);
3011 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003012 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00003013 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3014 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003015
3016 // If the types are the same, we won't learn anything by unwrapped
3017 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00003018 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003019 return ImplicitConversionSequence::Indistinguishable;
3020
Chandler Carruth607f38e2009-12-29 07:16:59 +00003021 // If the type is an array type, promote the element qualifiers to the type
3022 // for comparison.
3023 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00003024 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003025 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00003026 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00003027
Mike Stump11289f42009-09-09 15:08:12 +00003028 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003029 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00003030
3031 // Objective-C++ ARC:
3032 // Prefer qualification conversions not involving a change in lifetime
3033 // to qualification conversions that do not change lifetime.
3034 if (SCS1.QualificationIncludesObjCLifetime !=
3035 SCS2.QualificationIncludesObjCLifetime) {
3036 Result = SCS1.QualificationIncludesObjCLifetime
3037 ? ImplicitConversionSequence::Worse
3038 : ImplicitConversionSequence::Better;
3039 }
3040
John McCall5c32be02010-08-24 20:38:10 +00003041 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003042 // Within each iteration of the loop, we check the qualifiers to
3043 // determine if this still looks like a qualification
3044 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00003045 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003046 // until there are no more pointers or pointers-to-members left
3047 // to unwrap. This essentially mimics what
3048 // IsQualificationConversion does, but here we're checking for a
3049 // strict subset of qualifiers.
3050 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3051 // The qualifiers are the same, so this doesn't tell us anything
3052 // about how the sequences rank.
3053 ;
3054 else if (T2.isMoreQualifiedThan(T1)) {
3055 // T1 has fewer qualifiers, so it could be the better sequence.
3056 if (Result == ImplicitConversionSequence::Worse)
3057 // Neither has qualifiers that are a subset of the other's
3058 // qualifiers.
3059 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00003060
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003061 Result = ImplicitConversionSequence::Better;
3062 } else if (T1.isMoreQualifiedThan(T2)) {
3063 // T2 has fewer qualifiers, so it could be the better sequence.
3064 if (Result == ImplicitConversionSequence::Better)
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::Worse;
3070 } else {
3071 // Qualifiers are disjoint.
3072 return ImplicitConversionSequence::Indistinguishable;
3073 }
3074
3075 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00003076 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003077 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003078 }
3079
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003080 // Check that the winning standard conversion sequence isn't using
3081 // the deprecated string literal array to pointer conversion.
3082 switch (Result) {
3083 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003084 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003085 Result = ImplicitConversionSequence::Indistinguishable;
3086 break;
3087
3088 case ImplicitConversionSequence::Indistinguishable:
3089 break;
3090
3091 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003092 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003093 Result = ImplicitConversionSequence::Indistinguishable;
3094 break;
3095 }
3096
3097 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003098}
3099
Douglas Gregor5c407d92008-10-23 00:40:37 +00003100/// CompareDerivedToBaseConversions - Compares two standard conversion
3101/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003102/// various kinds of derived-to-base conversions (C++
3103/// [over.ics.rank]p4b3). As part of these checks, we also look at
3104/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003105ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003106CompareDerivedToBaseConversions(Sema &S,
3107 const StandardConversionSequence& SCS1,
3108 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003109 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003110 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003111 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003112 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003113
3114 // Adjust the types we're converting from via the array-to-pointer
3115 // conversion, if we need to.
3116 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003117 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003118 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003119 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003120
3121 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003122 FromType1 = S.Context.getCanonicalType(FromType1);
3123 ToType1 = S.Context.getCanonicalType(ToType1);
3124 FromType2 = S.Context.getCanonicalType(FromType2);
3125 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003126
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003127 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003128 //
3129 // If class B is derived directly or indirectly from class A and
3130 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003131 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003132 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003133 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003134 SCS2.Second == ICK_Pointer_Conversion &&
3135 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3136 FromType1->isPointerType() && FromType2->isPointerType() &&
3137 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003138 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003139 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003140 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003141 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003142 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003143 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003144 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003145 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003146
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003147 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003148 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003149 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003150 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003151 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003152 return ImplicitConversionSequence::Worse;
3153 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003154
3155 // -- conversion of B* to A* is better than conversion of C* to A*,
3156 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003157 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003158 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003159 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003160 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003161 }
3162 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3163 SCS2.Second == ICK_Pointer_Conversion) {
3164 const ObjCObjectPointerType *FromPtr1
3165 = FromType1->getAs<ObjCObjectPointerType>();
3166 const ObjCObjectPointerType *FromPtr2
3167 = FromType2->getAs<ObjCObjectPointerType>();
3168 const ObjCObjectPointerType *ToPtr1
3169 = ToType1->getAs<ObjCObjectPointerType>();
3170 const ObjCObjectPointerType *ToPtr2
3171 = ToType2->getAs<ObjCObjectPointerType>();
3172
3173 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3174 // Apply the same conversion ranking rules for Objective-C pointer types
3175 // that we do for C++ pointers to class types. However, we employ the
3176 // Objective-C pseudo-subtyping relationship used for assignment of
3177 // Objective-C pointer types.
3178 bool FromAssignLeft
3179 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3180 bool FromAssignRight
3181 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3182 bool ToAssignLeft
3183 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3184 bool ToAssignRight
3185 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3186
3187 // A conversion to an a non-id object pointer type or qualified 'id'
3188 // type is better than a conversion to 'id'.
3189 if (ToPtr1->isObjCIdType() &&
3190 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3191 return ImplicitConversionSequence::Worse;
3192 if (ToPtr2->isObjCIdType() &&
3193 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3194 return ImplicitConversionSequence::Better;
3195
3196 // A conversion to a non-id object pointer type is better than a
3197 // conversion to a qualified 'id' type
3198 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3199 return ImplicitConversionSequence::Worse;
3200 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3201 return ImplicitConversionSequence::Better;
3202
3203 // A conversion to an a non-Class object pointer type or qualified 'Class'
3204 // type is better than a conversion to 'Class'.
3205 if (ToPtr1->isObjCClassType() &&
3206 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3207 return ImplicitConversionSequence::Worse;
3208 if (ToPtr2->isObjCClassType() &&
3209 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3210 return ImplicitConversionSequence::Better;
3211
3212 // A conversion to a non-Class object pointer type is better than a
3213 // conversion to a qualified 'Class' type.
3214 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3215 return ImplicitConversionSequence::Worse;
3216 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3217 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003218
Douglas Gregor058d3de2011-01-31 18:51:41 +00003219 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3220 if (S.Context.hasSameType(FromType1, FromType2) &&
3221 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3222 (ToAssignLeft != ToAssignRight))
3223 return ToAssignLeft? ImplicitConversionSequence::Worse
3224 : ImplicitConversionSequence::Better;
3225
3226 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3227 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3228 (FromAssignLeft != FromAssignRight))
3229 return FromAssignLeft? ImplicitConversionSequence::Better
3230 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003231 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003232 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003233
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003234 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003235 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3236 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3237 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003238 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003239 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003240 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003241 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003242 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003243 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003244 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003245 ToType2->getAs<MemberPointerType>();
3246 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3247 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3248 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3249 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3250 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3251 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3252 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3253 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003254 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003255 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003256 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003257 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003258 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003259 return ImplicitConversionSequence::Better;
3260 }
3261 // conversion of B::* to C::* is better than conversion of A::* to C::*
3262 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003263 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003264 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003265 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003266 return ImplicitConversionSequence::Worse;
3267 }
3268 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003269
Douglas Gregor5ab11652010-04-17 22:01:05 +00003270 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003271 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003272 // -- binding of an expression of type C to a reference of type
3273 // B& is better than binding an expression of type C to a
3274 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003275 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3276 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3277 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003278 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003279 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003280 return ImplicitConversionSequence::Worse;
3281 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003282
Douglas Gregor2fe98832008-11-03 19:09:14 +00003283 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003284 // -- binding of an expression of type B to a reference of type
3285 // A& is better than binding an expression of type C to a
3286 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003287 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3288 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3289 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003290 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003291 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003292 return ImplicitConversionSequence::Worse;
3293 }
3294 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003295
Douglas Gregor5c407d92008-10-23 00:40:37 +00003296 return ImplicitConversionSequence::Indistinguishable;
3297}
3298
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003299/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3300/// determine whether they are reference-related,
3301/// reference-compatible, reference-compatible with added
3302/// qualification, or incompatible, for use in C++ initialization by
3303/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3304/// type, and the first type (T1) is the pointee type of the reference
3305/// type being initialized.
3306Sema::ReferenceCompareResult
3307Sema::CompareReferenceRelationship(SourceLocation Loc,
3308 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003309 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003310 bool &ObjCConversion,
3311 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003312 assert(!OrigT1->isReferenceType() &&
3313 "T1 must be the pointee type of the reference type");
3314 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3315
3316 QualType T1 = Context.getCanonicalType(OrigT1);
3317 QualType T2 = Context.getCanonicalType(OrigT2);
3318 Qualifiers T1Quals, T2Quals;
3319 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3320 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3321
3322 // C++ [dcl.init.ref]p4:
3323 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3324 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3325 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003326 DerivedToBase = false;
3327 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003328 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003329 if (UnqualT1 == UnqualT2) {
3330 // Nothing to do.
3331 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003332 IsDerivedFrom(UnqualT2, UnqualT1))
3333 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003334 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3335 UnqualT2->isObjCObjectOrInterfaceType() &&
3336 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3337 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003338 else
3339 return Ref_Incompatible;
3340
3341 // At this point, we know that T1 and T2 are reference-related (at
3342 // least).
3343
3344 // If the type is an array type, promote the element qualifiers to the type
3345 // for comparison.
3346 if (isa<ArrayType>(T1) && T1Quals)
3347 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3348 if (isa<ArrayType>(T2) && T2Quals)
3349 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3350
3351 // C++ [dcl.init.ref]p4:
3352 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3353 // reference-related to T2 and cv1 is the same cv-qualification
3354 // as, or greater cv-qualification than, cv2. For purposes of
3355 // overload resolution, cases for which cv1 is greater
3356 // cv-qualification than cv2 are identified as
3357 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003358 //
3359 // Note that we also require equivalence of Objective-C GC and address-space
3360 // qualifiers when performing these computations, so that e.g., an int in
3361 // address space 1 is not reference-compatible with an int in address
3362 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003363 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3364 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3365 T1Quals.removeObjCLifetime();
3366 T2Quals.removeObjCLifetime();
3367 ObjCLifetimeConversion = true;
3368 }
3369
Douglas Gregord517d552011-04-28 17:56:11 +00003370 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003371 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003372 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003373 return Ref_Compatible_With_Added_Qualification;
3374 else
3375 return Ref_Related;
3376}
3377
Douglas Gregor836a7e82010-08-11 02:15:33 +00003378/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003379/// with DeclType. Return true if something definite is found.
3380static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003381FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3382 QualType DeclType, SourceLocation DeclLoc,
3383 Expr *Init, QualType T2, bool AllowRvalues,
3384 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003385 assert(T2->isRecordType() && "Can only find conversions of record types.");
3386 CXXRecordDecl *T2RecordDecl
3387 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3388
3389 OverloadCandidateSet CandidateSet(DeclLoc);
3390 const UnresolvedSetImpl *Conversions
3391 = T2RecordDecl->getVisibleConversionFunctions();
3392 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3393 E = Conversions->end(); I != E; ++I) {
3394 NamedDecl *D = *I;
3395 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3396 if (isa<UsingShadowDecl>(D))
3397 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3398
3399 FunctionTemplateDecl *ConvTemplate
3400 = dyn_cast<FunctionTemplateDecl>(D);
3401 CXXConversionDecl *Conv;
3402 if (ConvTemplate)
3403 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3404 else
3405 Conv = cast<CXXConversionDecl>(D);
3406
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003407 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003408 // explicit conversions, skip it.
3409 if (!AllowExplicit && Conv->isExplicit())
3410 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003411
Douglas Gregor836a7e82010-08-11 02:15:33 +00003412 if (AllowRvalues) {
3413 bool DerivedToBase = false;
3414 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003415 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003416
3417 // If we are initializing an rvalue reference, don't permit conversion
3418 // functions that return lvalues.
3419 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3420 const ReferenceType *RefType
3421 = Conv->getConversionType()->getAs<LValueReferenceType>();
3422 if (RefType && !RefType->getPointeeType()->isFunctionType())
3423 continue;
3424 }
3425
Douglas Gregor836a7e82010-08-11 02:15:33 +00003426 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003427 S.CompareReferenceRelationship(
3428 DeclLoc,
3429 Conv->getConversionType().getNonReferenceType()
3430 .getUnqualifiedType(),
3431 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003432 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003433 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003434 continue;
3435 } else {
3436 // If the conversion function doesn't return a reference type,
3437 // it can't be considered for this conversion. An rvalue reference
3438 // is only acceptable if its referencee is a function type.
3439
3440 const ReferenceType *RefType =
3441 Conv->getConversionType()->getAs<ReferenceType>();
3442 if (!RefType ||
3443 (!RefType->isLValueReferenceType() &&
3444 !RefType->getPointeeType()->isFunctionType()))
3445 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003446 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003447
Douglas Gregor836a7e82010-08-11 02:15:33 +00003448 if (ConvTemplate)
3449 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003450 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003451 else
3452 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003453 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003454 }
3455
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003456 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3457
Sebastian Redld92badf2010-06-30 18:13:39 +00003458 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003459 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003460 case OR_Success:
3461 // C++ [over.ics.ref]p1:
3462 //
3463 // [...] If the parameter binds directly to the result of
3464 // applying a conversion function to the argument
3465 // expression, the implicit conversion sequence is a
3466 // user-defined conversion sequence (13.3.3.1.2), with the
3467 // second standard conversion sequence either an identity
3468 // conversion or, if the conversion function returns an
3469 // entity of a type that is a derived class of the parameter
3470 // type, a derived-to-base Conversion.
3471 if (!Best->FinalConversion.DirectBinding)
3472 return false;
3473
Chandler Carruth30141632011-02-25 19:41:05 +00003474 if (Best->Function)
3475 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003476 ICS.setUserDefined();
3477 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3478 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003479 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003480 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003481 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003482 ICS.UserDefined.EllipsisConversion = false;
3483 assert(ICS.UserDefined.After.ReferenceBinding &&
3484 ICS.UserDefined.After.DirectBinding &&
3485 "Expected a direct reference binding!");
3486 return true;
3487
3488 case OR_Ambiguous:
3489 ICS.setAmbiguous();
3490 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3491 Cand != CandidateSet.end(); ++Cand)
3492 if (Cand->Viable)
3493 ICS.Ambiguous.addConversion(Cand->Function);
3494 return true;
3495
3496 case OR_No_Viable_Function:
3497 case OR_Deleted:
3498 // There was no suitable conversion, or we found a deleted
3499 // conversion; continue with other checks.
3500 return false;
3501 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003502
Eric Christopheraba9fb22010-06-30 18:36:32 +00003503 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003504}
3505
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003506/// \brief Compute an implicit conversion sequence for reference
3507/// initialization.
3508static ImplicitConversionSequence
3509TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3510 SourceLocation DeclLoc,
3511 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003512 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003513 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3514
3515 // Most paths end in a failed conversion.
3516 ImplicitConversionSequence ICS;
3517 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3518
3519 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3520 QualType T2 = Init->getType();
3521
3522 // If the initializer is the address of an overloaded function, try
3523 // to resolve the overloaded function. If all goes well, T2 is the
3524 // type of the resulting function.
3525 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3526 DeclAccessPair Found;
3527 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3528 false, Found))
3529 T2 = Fn->getType();
3530 }
3531
3532 // Compute some basic properties of the types and the initializer.
3533 bool isRValRef = DeclType->isRValueReferenceType();
3534 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003535 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003536 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003537 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003538 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003539 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003540 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003541
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003542
Sebastian Redld92badf2010-06-30 18:13:39 +00003543 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003544 // A reference to type "cv1 T1" is initialized by an expression
3545 // of type "cv2 T2" as follows:
3546
Sebastian Redld92badf2010-06-30 18:13:39 +00003547 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003548 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003549 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3550 // reference-compatible with "cv2 T2," or
3551 //
3552 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3553 if (InitCategory.isLValue() &&
3554 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003555 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003556 // When a parameter of reference type binds directly (8.5.3)
3557 // to an argument expression, the implicit conversion sequence
3558 // is the identity conversion, unless the argument expression
3559 // has a type that is a derived class of the parameter type,
3560 // in which case the implicit conversion sequence is a
3561 // derived-to-base Conversion (13.3.3.1).
3562 ICS.setStandard();
3563 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003564 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3565 : ObjCConversion? ICK_Compatible_Conversion
3566 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003567 ICS.Standard.Third = ICK_Identity;
3568 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3569 ICS.Standard.setToType(0, T2);
3570 ICS.Standard.setToType(1, T1);
3571 ICS.Standard.setToType(2, T1);
3572 ICS.Standard.ReferenceBinding = true;
3573 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003574 ICS.Standard.IsLvalueReference = !isRValRef;
3575 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3576 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003577 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003578 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003579 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003580
Sebastian Redld92badf2010-06-30 18:13:39 +00003581 // Nothing more to do: the inaccessibility/ambiguity check for
3582 // derived-to-base conversions is suppressed when we're
3583 // computing the implicit conversion sequence (C++
3584 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003585 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003586 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003587
Sebastian Redld92badf2010-06-30 18:13:39 +00003588 // -- has a class type (i.e., T2 is a class type), where T1 is
3589 // not reference-related to T2, and can be implicitly
3590 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3591 // is reference-compatible with "cv3 T3" 92) (this
3592 // conversion is selected by enumerating the applicable
3593 // conversion functions (13.3.1.6) and choosing the best
3594 // one through overload resolution (13.3)),
3595 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003596 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003597 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003598 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3599 Init, T2, /*AllowRvalues=*/false,
3600 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003601 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003602 }
3603 }
3604
Sebastian Redld92badf2010-06-30 18:13:39 +00003605 // -- Otherwise, the reference shall be an lvalue reference to a
3606 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003607 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003608 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003609 // We actually handle one oddity of C++ [over.ics.ref] at this
3610 // point, which is that, due to p2 (which short-circuits reference
3611 // binding by only attempting a simple conversion for non-direct
3612 // bindings) and p3's strange wording, we allow a const volatile
3613 // reference to bind to an rvalue. Hence the check for the presence
3614 // of "const" rather than checking for "const" being the only
3615 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003616 // This is also the point where rvalue references and lvalue inits no longer
3617 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003618 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003619 return ICS;
3620
Douglas Gregorf143cd52011-01-24 16:14:37 +00003621 // -- If the initializer expression
3622 //
3623 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003624 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003625 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3626 (InitCategory.isXValue() ||
3627 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3628 (InitCategory.isLValue() && T2->isFunctionType()))) {
3629 ICS.setStandard();
3630 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003631 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003632 : ObjCConversion? ICK_Compatible_Conversion
3633 : ICK_Identity;
3634 ICS.Standard.Third = ICK_Identity;
3635 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3636 ICS.Standard.setToType(0, T2);
3637 ICS.Standard.setToType(1, T1);
3638 ICS.Standard.setToType(2, T1);
3639 ICS.Standard.ReferenceBinding = true;
3640 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3641 // binding unless we're binding to a class prvalue.
3642 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3643 // allow the use of rvalue references in C++98/03 for the benefit of
3644 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003645 ICS.Standard.DirectBinding =
3646 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003647 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003648 ICS.Standard.IsLvalueReference = !isRValRef;
3649 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003650 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003651 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003652 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003653 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003654 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003655 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003656
Douglas Gregorf143cd52011-01-24 16:14:37 +00003657 // -- has a class type (i.e., T2 is a class type), where T1 is not
3658 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003659 // an xvalue, class prvalue, or function lvalue of type
3660 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003661 // "cv3 T3",
3662 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003663 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003664 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003665 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003666 // class subobject).
3667 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003668 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003669 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3670 Init, T2, /*AllowRvalues=*/true,
3671 AllowExplicit)) {
3672 // In the second case, if the reference is an rvalue reference
3673 // and the second standard conversion sequence of the
3674 // user-defined conversion sequence includes an lvalue-to-rvalue
3675 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003676 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003677 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3678 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3679
Douglas Gregor95273c32011-01-21 16:36:05 +00003680 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003681 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003682
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003683 // -- Otherwise, a temporary of type "cv1 T1" is created and
3684 // initialized from the initializer expression using the
3685 // rules for a non-reference copy initialization (8.5). The
3686 // reference is then bound to the temporary. If T1 is
3687 // reference-related to T2, cv1 must be the same
3688 // cv-qualification as, or greater cv-qualification than,
3689 // cv2; otherwise, the program is ill-formed.
3690 if (RefRelationship == Sema::Ref_Related) {
3691 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3692 // we would be reference-compatible or reference-compatible with
3693 // added qualification. But that wasn't the case, so the reference
3694 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00003695 //
3696 // Note that we only want to check address spaces and cvr-qualifiers here.
3697 // ObjC GC and lifetime qualifiers aren't important.
3698 Qualifiers T1Quals = T1.getQualifiers();
3699 Qualifiers T2Quals = T2.getQualifiers();
3700 T1Quals.removeObjCGCAttr();
3701 T1Quals.removeObjCLifetime();
3702 T2Quals.removeObjCGCAttr();
3703 T2Quals.removeObjCLifetime();
3704 if (!T1Quals.compatiblyIncludes(T2Quals))
3705 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003706 }
3707
3708 // If at least one of the types is a class type, the types are not
3709 // related, and we aren't allowed any user conversions, the
3710 // reference binding fails. This case is important for breaking
3711 // recursion, since TryImplicitConversion below will attempt to
3712 // create a temporary through the use of a copy constructor.
3713 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3714 (T1->isRecordType() || T2->isRecordType()))
3715 return ICS;
3716
Douglas Gregorcba72b12011-01-21 05:18:22 +00003717 // If T1 is reference-related to T2 and the reference is an rvalue
3718 // reference, the initializer expression shall not be an lvalue.
3719 if (RefRelationship >= Sema::Ref_Related &&
3720 isRValRef && Init->Classify(S.Context).isLValue())
3721 return ICS;
3722
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003723 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003724 // When a parameter of reference type is not bound directly to
3725 // an argument expression, the conversion sequence is the one
3726 // required to convert the argument expression to the
3727 // underlying type of the reference according to
3728 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3729 // to copy-initializing a temporary of the underlying type with
3730 // the argument expression. Any difference in top-level
3731 // cv-qualification is subsumed by the initialization itself
3732 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003733 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3734 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003735 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003736 /*CStyle=*/false,
3737 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003738
3739 // Of course, that's still a reference binding.
3740 if (ICS.isStandard()) {
3741 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003742 ICS.Standard.IsLvalueReference = !isRValRef;
3743 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3744 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003745 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003746 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003747 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003748 // Don't allow rvalue references to bind to lvalues.
3749 if (DeclType->isRValueReferenceType()) {
3750 if (const ReferenceType *RefType
3751 = ICS.UserDefined.ConversionFunction->getResultType()
3752 ->getAs<LValueReferenceType>()) {
3753 if (!RefType->getPointeeType()->isFunctionType()) {
3754 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
3755 DeclType);
3756 return ICS;
3757 }
3758 }
3759 }
3760
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003761 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00003762 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3763 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3764 ICS.UserDefined.After.BindsToRvalue = true;
3765 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3766 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003767 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003768
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003769 return ICS;
3770}
3771
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003772static ImplicitConversionSequence
3773TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
3774 bool SuppressUserConversions,
3775 bool InOverloadResolution,
3776 bool AllowObjCWritebackConversion);
3777
3778/// TryListConversion - Try to copy-initialize a value of type ToType from the
3779/// initializer list From.
3780static ImplicitConversionSequence
3781TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
3782 bool SuppressUserConversions,
3783 bool InOverloadResolution,
3784 bool AllowObjCWritebackConversion) {
3785 // C++11 [over.ics.list]p1:
3786 // When an argument is an initializer list, it is not an expression and
3787 // special rules apply for converting it to a parameter type.
3788
3789 ImplicitConversionSequence Result;
3790 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
3791
3792 // C++11 [over.ics.list]p2:
3793 // If the parameter type is std::initializer_list<X> or "array of X" and
3794 // all the elements can be implicitly converted to X, the implicit
3795 // conversion sequence is the worst conversion necessary to convert an
3796 // element of the list to X.
3797 // FIXME: Recognize std::initializer_list.
3798 // FIXME: Arrays don't make sense until we can deal with references.
3799 if (ToType->isArrayType())
3800 return Result;
3801
3802 // C++11 [over.ics.list]p3:
3803 // Otherwise, if the parameter is a non-aggregate class X and overload
3804 // resolution chooses a single best constructor [...] the implicit
3805 // conversion sequence is a user-defined conversion sequence. If multiple
3806 // constructors are viable but none is better than the others, the
3807 // implicit conversion sequence is a user-defined conversion sequence.
3808 // FIXME: Implement this.
3809 if (ToType->isRecordType() && !ToType->isAggregateType())
3810 return Result;
3811
3812 // C++11 [over.ics.list]p4:
3813 // Otherwise, if the parameter has an aggregate type which can be
3814 // initialized from the initializer list [...] the implicit conversion
3815 // sequence is a user-defined conversion sequence.
3816 // FIXME: Implement this.
3817 if (ToType->isAggregateType()) {
3818 return Result;
3819 }
3820
3821 // C++11 [over.ics.list]p5:
3822 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
3823 // FIXME: Implement this.
3824 if (ToType->isReferenceType())
3825 return Result;
3826
3827 // C++11 [over.ics.list]p6:
3828 // Otherwise, if the parameter type is not a class:
3829 if (!ToType->isRecordType()) {
3830 // - if the initializer list has one element, the implicit conversion
3831 // sequence is the one required to convert the element to the
3832 // parameter type.
3833 // FIXME: Catch narrowing here?
3834 unsigned NumInits = From->getNumInits();
3835 if (NumInits == 1)
3836 Result = TryCopyInitialization(S, From->getInit(0), ToType,
3837 SuppressUserConversions,
3838 InOverloadResolution,
3839 AllowObjCWritebackConversion);
3840 // - if the initializer list has no elements, the implicit conversion
3841 // sequence is the identity conversion.
3842 else if (NumInits == 0) {
3843 Result.setStandard();
3844 Result.Standard.setAsIdentityConversion();
3845 }
3846 return Result;
3847 }
3848
3849 // C++11 [over.ics.list]p7:
3850 // In all cases other than those enumerated above, no conversion is possible
3851 return Result;
3852}
3853
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003854/// TryCopyInitialization - Try to copy-initialize a value of type
3855/// ToType from the expression From. Return the implicit conversion
3856/// sequence required to pass this argument, which may be a bad
3857/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003858/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003859/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003860static ImplicitConversionSequence
3861TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003862 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00003863 bool InOverloadResolution,
3864 bool AllowObjCWritebackConversion) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003865 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
3866 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
3867 InOverloadResolution,AllowObjCWritebackConversion);
3868
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003869 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003870 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003871 /*FIXME:*/From->getLocStart(),
3872 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003873 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003874
John McCall5c32be02010-08-24 20:38:10 +00003875 return TryImplicitConversion(S, From, ToType,
3876 SuppressUserConversions,
3877 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003878 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00003879 /*CStyle=*/false,
3880 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003881}
3882
Anna Zaks1b068122011-07-28 19:46:48 +00003883static bool TryCopyInitialization(const CanQualType FromQTy,
3884 const CanQualType ToQTy,
3885 Sema &S,
3886 SourceLocation Loc,
3887 ExprValueKind FromVK) {
3888 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
3889 ImplicitConversionSequence ICS =
3890 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
3891
3892 return !ICS.isBad();
3893}
3894
Douglas Gregor436424c2008-11-18 23:14:02 +00003895/// TryObjectArgumentInitialization - Try to initialize the object
3896/// parameter of the given member function (@c Method) from the
3897/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003898static ImplicitConversionSequence
3899TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003900 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003901 CXXMethodDecl *Method,
3902 CXXRecordDecl *ActingContext) {
3903 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003904 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3905 // const volatile object.
3906 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3907 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003908 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003909
3910 // Set up the conversion sequence as a "bad" conversion, to allow us
3911 // to exit early.
3912 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003913
3914 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003915 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003916 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003917 FromType = PT->getPointeeType();
3918
Douglas Gregor02824322011-01-26 19:30:28 +00003919 // When we had a pointer, it's implicitly dereferenced, so we
3920 // better have an lvalue.
3921 assert(FromClassification.isLValue());
3922 }
3923
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003924 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003925
Douglas Gregor02824322011-01-26 19:30:28 +00003926 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003927 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003928 // parameter is
3929 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003930 // - "lvalue reference to cv X" for functions declared without a
3931 // ref-qualifier or with the & ref-qualifier
3932 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003933 // ref-qualifier
3934 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003935 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003936 // cv-qualification on the member function declaration.
3937 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003938 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003939 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003940 // (C++ [over.match.funcs]p5). We perform a simplified version of
3941 // reference binding here, that allows class rvalues to bind to
3942 // non-constant references.
3943
Douglas Gregor02824322011-01-26 19:30:28 +00003944 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003945 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003946 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003947 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003948 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003949 ICS.setBad(BadConversionSequence::bad_qualifiers,
3950 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003951 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003952 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003953
3954 // Check that we have either the same type or a derived type. It
3955 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003956 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003957 ImplicitConversionKind SecondKind;
3958 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3959 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003960 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003961 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003962 else {
John McCall65eb8792010-02-25 01:37:24 +00003963 ICS.setBad(BadConversionSequence::unrelated_class,
3964 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003965 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003966 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003967
Douglas Gregor02824322011-01-26 19:30:28 +00003968 // Check the ref-qualifier.
3969 switch (Method->getRefQualifier()) {
3970 case RQ_None:
3971 // Do nothing; we don't care about lvalueness or rvalueness.
3972 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003973
Douglas Gregor02824322011-01-26 19:30:28 +00003974 case RQ_LValue:
3975 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3976 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003977 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003978 ImplicitParamType);
3979 return ICS;
3980 }
3981 break;
3982
3983 case RQ_RValue:
3984 if (!FromClassification.isRValue()) {
3985 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003986 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003987 ImplicitParamType);
3988 return ICS;
3989 }
3990 break;
3991 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003992
Douglas Gregor436424c2008-11-18 23:14:02 +00003993 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003994 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003995 ICS.Standard.setAsIdentityConversion();
3996 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003997 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003998 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003999 ICS.Standard.ReferenceBinding = true;
4000 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004001 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00004002 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00004003 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4004 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4005 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00004006 return ICS;
4007}
4008
4009/// PerformObjectArgumentInitialization - Perform initialization of
4010/// the implicit object parameter for the given Method with the given
4011/// expression.
John Wiegley01296292011-04-08 18:41:53 +00004012ExprResult
4013Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004014 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00004015 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004016 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004017 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00004018 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004019 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00004020
Douglas Gregor02824322011-01-26 19:30:28 +00004021 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004022 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004023 FromRecordType = PT->getPointeeType();
4024 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00004025 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004026 } else {
4027 FromRecordType = From->getType();
4028 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00004029 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004030 }
4031
John McCall6e9f8f62009-12-03 04:06:58 +00004032 // Note that we always use the true parent context when performing
4033 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00004034 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00004035 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4036 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004037 if (ICS.isBad()) {
4038 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4039 Qualifiers FromQs = FromRecordType.getQualifiers();
4040 Qualifiers ToQs = DestType.getQualifiers();
4041 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4042 if (CVR) {
4043 Diag(From->getSourceRange().getBegin(),
4044 diag::err_member_function_call_bad_cvr)
4045 << Method->getDeclName() << FromRecordType << (CVR - 1)
4046 << From->getSourceRange();
4047 Diag(Method->getLocation(), diag::note_previous_decl)
4048 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00004049 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004050 }
4051 }
4052
Douglas Gregor436424c2008-11-18 23:14:02 +00004053 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00004054 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00004055 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00004056 }
Mike Stump11289f42009-09-09 15:08:12 +00004057
John Wiegley01296292011-04-08 18:41:53 +00004058 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4059 ExprResult FromRes =
4060 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4061 if (FromRes.isInvalid())
4062 return ExprError();
4063 From = FromRes.take();
4064 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004065
Douglas Gregorcc3f3252010-03-03 23:55:11 +00004066 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00004067 From = ImpCastExprToType(From, DestType, CK_NoOp,
4068 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
4069 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00004070}
4071
Douglas Gregor5fb53972009-01-14 15:45:31 +00004072/// TryContextuallyConvertToBool - Attempt to contextually convert the
4073/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00004074static ImplicitConversionSequence
4075TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00004076 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00004077 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00004078 // FIXME: Are these flags correct?
4079 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00004080 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00004081 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004082 /*CStyle=*/false,
4083 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004084}
4085
4086/// PerformContextuallyConvertToBool - Perform a contextual conversion
4087/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004088ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004089 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004090 if (!ICS.isBad())
4091 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004092
Fariborz Jahanian76197412009-11-18 18:26:29 +00004093 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00004094 return Diag(From->getSourceRange().getBegin(),
4095 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004096 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004097 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004098}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004099
John McCallfec112d2011-09-09 06:11:02 +00004100/// dropPointerConversions - If the given standard conversion sequence
4101/// involves any pointer conversions, remove them. This may change
4102/// the result type of the conversion sequence.
4103static void dropPointerConversion(StandardConversionSequence &SCS) {
4104 if (SCS.Second == ICK_Pointer_Conversion) {
4105 SCS.Second = ICK_Identity;
4106 SCS.Third = ICK_Identity;
4107 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4108 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004109}
John McCall5c32be02010-08-24 20:38:10 +00004110
John McCallfec112d2011-09-09 06:11:02 +00004111/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4112/// convert the expression From to an Objective-C pointer type.
4113static ImplicitConversionSequence
4114TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4115 // Do an implicit conversion to 'id'.
4116 QualType Ty = S.Context.getObjCIdType();
4117 ImplicitConversionSequence ICS
4118 = TryImplicitConversion(S, From, Ty,
4119 // FIXME: Are these flags correct?
4120 /*SuppressUserConversions=*/false,
4121 /*AllowExplicit=*/true,
4122 /*InOverloadResolution=*/false,
4123 /*CStyle=*/false,
4124 /*AllowObjCWritebackConversion=*/false);
4125
4126 // Strip off any final conversions to 'id'.
4127 switch (ICS.getKind()) {
4128 case ImplicitConversionSequence::BadConversion:
4129 case ImplicitConversionSequence::AmbiguousConversion:
4130 case ImplicitConversionSequence::EllipsisConversion:
4131 break;
4132
4133 case ImplicitConversionSequence::UserDefinedConversion:
4134 dropPointerConversion(ICS.UserDefined.After);
4135 break;
4136
4137 case ImplicitConversionSequence::StandardConversion:
4138 dropPointerConversion(ICS.Standard);
4139 break;
4140 }
4141
4142 return ICS;
4143}
4144
4145/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4146/// conversion of the expression From to an Objective-C pointer type.
4147ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00004148 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004149 ImplicitConversionSequence ICS =
4150 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004151 if (!ICS.isBad())
4152 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004153 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004154}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004155
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004156/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004157/// enumeration type.
4158///
4159/// This routine will attempt to convert an expression of class type to an
4160/// integral or enumeration type, if that class type only has a single
4161/// conversion to an integral or enumeration type.
4162///
Douglas Gregor4799d032010-06-30 00:20:43 +00004163/// \param Loc The source location of the construct that requires the
4164/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004165///
Douglas Gregor4799d032010-06-30 00:20:43 +00004166/// \param FromE The expression we're converting from.
4167///
4168/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4169/// have integral or enumeration type.
4170///
4171/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4172/// incomplete class type.
4173///
4174/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4175/// explicit conversion function (because no implicit conversion functions
4176/// were available). This is a recovery mode.
4177///
4178/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4179/// showing which conversion was picked.
4180///
4181/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4182/// conversion function that could convert to integral or enumeration type.
4183///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004184/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004185/// usable conversion function.
4186///
4187/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4188/// function, which may be an extension in this case.
4189///
4190/// \returns The expression, converted to an integral or enumeration type if
4191/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004192ExprResult
John McCallb268a282010-08-23 23:25:46 +00004193Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004194 const PartialDiagnostic &NotIntDiag,
4195 const PartialDiagnostic &IncompleteDiag,
4196 const PartialDiagnostic &ExplicitConvDiag,
4197 const PartialDiagnostic &ExplicitConvNote,
4198 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004199 const PartialDiagnostic &AmbigNote,
4200 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004201 // We can't perform any more checking for type-dependent expressions.
4202 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004203 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004204
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004205 // If the expression already has integral or enumeration type, we're golden.
4206 QualType T = From->getType();
4207 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00004208 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004209
4210 // FIXME: Check for missing '()' if T is a function type?
4211
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004212 // 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 +00004213 // expression of integral or enumeration type.
4214 const RecordType *RecordTy = T->getAs<RecordType>();
4215 if (!RecordTy || !getLangOptions().CPlusPlus) {
4216 Diag(Loc, NotIntDiag)
4217 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004218 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004219 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004220
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004221 // We must have a complete class type.
4222 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004223 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004224
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004225 // Look for a conversion to an integral or enumeration type.
4226 UnresolvedSet<4> ViableConversions;
4227 UnresolvedSet<4> ExplicitConversions;
4228 const UnresolvedSetImpl *Conversions
4229 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004230
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004231 bool HadMultipleCandidates = (Conversions->size() > 1);
4232
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004233 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004234 E = Conversions->end();
4235 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004236 ++I) {
4237 if (CXXConversionDecl *Conversion
4238 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4239 if (Conversion->getConversionType().getNonReferenceType()
4240 ->isIntegralOrEnumerationType()) {
4241 if (Conversion->isExplicit())
4242 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4243 else
4244 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4245 }
4246 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004247
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004248 switch (ViableConversions.size()) {
4249 case 0:
4250 if (ExplicitConversions.size() == 1) {
4251 DeclAccessPair Found = ExplicitConversions[0];
4252 CXXConversionDecl *Conversion
4253 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004254
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004255 // The user probably meant to invoke the given explicit
4256 // conversion; use it.
4257 QualType ConvTy
4258 = Conversion->getConversionType().getNonReferenceType();
4259 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00004260 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004261
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004262 Diag(Loc, ExplicitConvDiag)
4263 << T << ConvTy
4264 << FixItHint::CreateInsertion(From->getLocStart(),
4265 "static_cast<" + TypeStr + ">(")
4266 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4267 ")");
4268 Diag(Conversion->getLocation(), ExplicitConvNote)
4269 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004270
4271 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004272 // explicit conversion function.
4273 if (isSFINAEContext())
4274 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004275
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004276 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004277 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4278 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004279 if (Result.isInvalid())
4280 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004281
Douglas Gregor668443e2011-01-20 00:18:04 +00004282 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004283 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004284
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004285 // We'll complain below about a non-integral condition type.
4286 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004287
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004288 case 1: {
4289 // Apply this conversion.
4290 DeclAccessPair Found = ViableConversions[0];
4291 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004292
Douglas Gregor4799d032010-06-30 00:20:43 +00004293 CXXConversionDecl *Conversion
4294 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4295 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004296 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004297 if (ConvDiag.getDiagID()) {
4298 if (isSFINAEContext())
4299 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004300
Douglas Gregor4799d032010-06-30 00:20:43 +00004301 Diag(Loc, ConvDiag)
4302 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4303 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004304
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004305 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4306 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004307 if (Result.isInvalid())
4308 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004309
Douglas Gregor668443e2011-01-20 00:18:04 +00004310 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004311 break;
4312 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004313
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004314 default:
4315 Diag(Loc, AmbigDiag)
4316 << T << From->getSourceRange();
4317 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4318 CXXConversionDecl *Conv
4319 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4320 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4321 Diag(Conv->getLocation(), AmbigNote)
4322 << ConvTy->isEnumeralType() << ConvTy;
4323 }
John McCallb268a282010-08-23 23:25:46 +00004324 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004325 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004326
Douglas Gregor5823da32010-06-29 23:25:20 +00004327 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004328 Diag(Loc, NotIntDiag)
4329 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004330
John McCallb268a282010-08-23 23:25:46 +00004331 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004332}
4333
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004334/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004335/// candidate functions, using the given function call arguments. If
4336/// @p SuppressUserConversions, then don't allow user-defined
4337/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004338///
4339/// \para PartialOverloading true if we are performing "partial" overloading
4340/// based on an incomplete set of function arguments. This feature is used by
4341/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004342void
4343Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004344 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004345 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004346 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004347 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004348 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004349 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004350 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004351 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004352 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004353 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004354
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004355 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004356 if (!isa<CXXConstructorDecl>(Method)) {
4357 // If we get here, it's because we're calling a member function
4358 // that is named without a member access expression (e.g.,
4359 // "this->f") that was either written explicitly or created
4360 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004361 // function, e.g., X::f(). We use an empty type for the implied
4362 // object argument (C++ [over.call.func]p3), and the acting context
4363 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004364 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004365 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004366 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004367 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004368 return;
4369 }
4370 // We treat a constructor like a non-member function, since its object
4371 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004372 }
4373
Douglas Gregorff7028a2009-11-13 23:59:09 +00004374 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004375 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004376
Douglas Gregor27381f32009-11-23 12:27:39 +00004377 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004378 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004379
Douglas Gregorffe14e32009-11-14 01:20:54 +00004380 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4381 // C++ [class.copy]p3:
4382 // A member function template is never instantiated to perform the copy
4383 // of a class object to an object of its class type.
4384 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004385 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004386 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004387 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4388 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004389 return;
4390 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004391
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004392 // Add this candidate
4393 CandidateSet.push_back(OverloadCandidate());
4394 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004395 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004396 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004397 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004398 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004399 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004400 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004401
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004402 unsigned NumArgsInProto = Proto->getNumArgs();
4403
4404 // (C++ 13.3.2p2): A candidate function having fewer than m
4405 // parameters is viable only if it has an ellipsis in its parameter
4406 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004407 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004408 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004409 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004410 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004411 return;
4412 }
4413
4414 // (C++ 13.3.2p2): A candidate function having more than m parameters
4415 // is viable only if the (m+1)st parameter has a default argument
4416 // (8.3.6). For the purposes of overload resolution, the
4417 // parameter list is truncated on the right, so that there are
4418 // exactly m parameters.
4419 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004420 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004421 // Not enough arguments.
4422 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004423 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004424 return;
4425 }
4426
Peter Collingbourne7277fe82011-10-02 23:49:40 +00004427 // (CUDA B.1): Check for invalid calls between targets.
4428 if (getLangOptions().CUDA)
4429 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4430 if (CheckCUDATarget(Caller, Function)) {
4431 Candidate.Viable = false;
4432 Candidate.FailureKind = ovl_fail_bad_target;
4433 return;
4434 }
4435
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004436 // Determine the implicit conversion sequences for each of the
4437 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004438 Candidate.Conversions.resize(NumArgs);
4439 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4440 if (ArgIdx < NumArgsInProto) {
4441 // (C++ 13.3.2p3): for F to be a viable function, there shall
4442 // exist for each argument an implicit conversion sequence
4443 // (13.3.3.1) that converts that argument to the corresponding
4444 // parameter of F.
4445 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004446 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004447 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004448 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004449 /*InOverloadResolution=*/true,
4450 /*AllowObjCWritebackConversion=*/
4451 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004452 if (Candidate.Conversions[ArgIdx].isBad()) {
4453 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004454 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004455 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004456 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004457 } else {
4458 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4459 // argument for which there is no corresponding parameter is
4460 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004461 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004462 }
4463 }
4464}
4465
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004466/// \brief Add all of the function declarations in the given function set to
4467/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004468void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004469 Expr **Args, unsigned NumArgs,
4470 OverloadCandidateSet& CandidateSet,
4471 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004472 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004473 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4474 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004475 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004476 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004477 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004478 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004479 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004480 CandidateSet, SuppressUserConversions);
4481 else
John McCalla0296f72010-03-19 07:35:19 +00004482 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004483 SuppressUserConversions);
4484 } else {
John McCalla0296f72010-03-19 07:35:19 +00004485 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004486 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4487 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004488 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004489 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004490 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004491 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004492 Args[0]->Classify(Context),
4493 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004494 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004495 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004496 else
John McCalla0296f72010-03-19 07:35:19 +00004497 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004498 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004499 Args, NumArgs, CandidateSet,
4500 SuppressUserConversions);
4501 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004502 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004503}
4504
John McCallf0f1cf02009-11-17 07:50:12 +00004505/// AddMethodCandidate - Adds a named decl (which is some kind of
4506/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004507void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004508 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004509 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004510 Expr **Args, unsigned NumArgs,
4511 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004512 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004513 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004514 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004515
4516 if (isa<UsingShadowDecl>(Decl))
4517 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004518
John McCallf0f1cf02009-11-17 07:50:12 +00004519 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4520 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4521 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004522 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4523 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004524 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004525 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004526 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004527 } else {
John McCalla0296f72010-03-19 07:35:19 +00004528 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004529 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004530 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004531 }
4532}
4533
Douglas Gregor436424c2008-11-18 23:14:02 +00004534/// AddMethodCandidate - Adds the given C++ member function to the set
4535/// of candidate functions, using the given function call arguments
4536/// and the object argument (@c Object). For example, in a call
4537/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4538/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4539/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004540/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004541void
John McCalla0296f72010-03-19 07:35:19 +00004542Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004543 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004544 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004545 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004546 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004547 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004548 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004549 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004550 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004551 assert(!isa<CXXConstructorDecl>(Method) &&
4552 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004553
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004554 if (!CandidateSet.isNewCandidate(Method))
4555 return;
4556
Douglas Gregor27381f32009-11-23 12:27:39 +00004557 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004558 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004559
Douglas Gregor436424c2008-11-18 23:14:02 +00004560 // Add this candidate
4561 CandidateSet.push_back(OverloadCandidate());
4562 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004563 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004564 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004565 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004566 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004567 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004568
4569 unsigned NumArgsInProto = Proto->getNumArgs();
4570
4571 // (C++ 13.3.2p2): A candidate function having fewer than m
4572 // parameters is viable only if it has an ellipsis in its parameter
4573 // list (8.3.5).
4574 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4575 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004576 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004577 return;
4578 }
4579
4580 // (C++ 13.3.2p2): A candidate function having more than m parameters
4581 // is viable only if the (m+1)st parameter has a default argument
4582 // (8.3.6). For the purposes of overload resolution, the
4583 // parameter list is truncated on the right, so that there are
4584 // exactly m parameters.
4585 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4586 if (NumArgs < MinRequiredArgs) {
4587 // Not enough arguments.
4588 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004589 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004590 return;
4591 }
4592
4593 Candidate.Viable = true;
4594 Candidate.Conversions.resize(NumArgs + 1);
4595
John McCall6e9f8f62009-12-03 04:06:58 +00004596 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004597 // The implicit object argument is ignored.
4598 Candidate.IgnoreObjectArgument = true;
4599 else {
4600 // Determine the implicit conversion sequence for the object
4601 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004602 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004603 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4604 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004605 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004606 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004607 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004608 return;
4609 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004610 }
4611
4612 // Determine the implicit conversion sequences for each of the
4613 // arguments.
4614 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4615 if (ArgIdx < NumArgsInProto) {
4616 // (C++ 13.3.2p3): for F to be a viable function, there shall
4617 // exist for each argument an implicit conversion sequence
4618 // (13.3.3.1) that converts that argument to the corresponding
4619 // parameter of F.
4620 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004621 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004622 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004623 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004624 /*InOverloadResolution=*/true,
4625 /*AllowObjCWritebackConversion=*/
4626 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004627 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004628 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004629 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004630 break;
4631 }
4632 } else {
4633 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4634 // argument for which there is no corresponding parameter is
4635 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004636 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004637 }
4638 }
4639}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004640
Douglas Gregor97628d62009-08-21 00:16:32 +00004641/// \brief Add a C++ member function template as a candidate to the candidate
4642/// set, using template argument deduction to produce an appropriate member
4643/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004644void
Douglas Gregor97628d62009-08-21 00:16:32 +00004645Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004646 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004647 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004648 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004649 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004650 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004651 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004652 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004653 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004654 if (!CandidateSet.isNewCandidate(MethodTmpl))
4655 return;
4656
Douglas Gregor97628d62009-08-21 00:16:32 +00004657 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004658 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004659 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004660 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004661 // candidate functions in the usual way.113) A given name can refer to one
4662 // or more function templates and also to a set of overloaded non-template
4663 // functions. In such a case, the candidate functions generated from each
4664 // function template are combined with the set of non-template candidate
4665 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004666 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004667 FunctionDecl *Specialization = 0;
4668 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004669 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004670 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004671 CandidateSet.push_back(OverloadCandidate());
4672 OverloadCandidate &Candidate = CandidateSet.back();
4673 Candidate.FoundDecl = FoundDecl;
4674 Candidate.Function = MethodTmpl->getTemplatedDecl();
4675 Candidate.Viable = false;
4676 Candidate.FailureKind = ovl_fail_bad_deduction;
4677 Candidate.IsSurrogate = false;
4678 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004679 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004680 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004681 Info);
4682 return;
4683 }
Mike Stump11289f42009-09-09 15:08:12 +00004684
Douglas Gregor97628d62009-08-21 00:16:32 +00004685 // Add the function template specialization produced by template argument
4686 // deduction as a candidate.
4687 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004688 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004689 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004690 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004691 ActingContext, ObjectType, ObjectClassification,
4692 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004693}
4694
Douglas Gregor05155d82009-08-21 23:19:43 +00004695/// \brief Add a C++ function template specialization as a candidate
4696/// in the candidate set, using template argument deduction to produce
4697/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004698void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004699Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004700 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004701 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004702 Expr **Args, unsigned NumArgs,
4703 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004704 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004705 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4706 return;
4707
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004708 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004709 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004710 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004711 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004712 // candidate functions in the usual way.113) A given name can refer to one
4713 // or more function templates and also to a set of overloaded non-template
4714 // functions. In such a case, the candidate functions generated from each
4715 // function template are combined with the set of non-template candidate
4716 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004717 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004718 FunctionDecl *Specialization = 0;
4719 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004720 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004721 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004722 CandidateSet.push_back(OverloadCandidate());
4723 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004724 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004725 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4726 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004727 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004728 Candidate.IsSurrogate = false;
4729 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004730 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004731 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004732 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004733 return;
4734 }
Mike Stump11289f42009-09-09 15:08:12 +00004735
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004736 // Add the function template specialization produced by template argument
4737 // deduction as a candidate.
4738 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004739 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004740 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004741}
Mike Stump11289f42009-09-09 15:08:12 +00004742
Douglas Gregora1f013e2008-11-07 22:36:19 +00004743/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004744/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004745/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004746/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004747/// (which may or may not be the same type as the type that the
4748/// conversion function produces).
4749void
4750Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004751 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004752 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004753 Expr *From, QualType ToType,
4754 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004755 assert(!Conversion->getDescribedFunctionTemplate() &&
4756 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004757 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004758 if (!CandidateSet.isNewCandidate(Conversion))
4759 return;
4760
Douglas Gregor27381f32009-11-23 12:27:39 +00004761 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004762 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004763
Douglas Gregora1f013e2008-11-07 22:36:19 +00004764 // Add this candidate
4765 CandidateSet.push_back(OverloadCandidate());
4766 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004767 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004768 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004769 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004770 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004771 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004772 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004773 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004774 Candidate.Viable = true;
4775 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004776 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004777
Douglas Gregor6affc782010-08-19 15:37:02 +00004778 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004779 // For conversion functions, the function is considered to be a member of
4780 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004781 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004782 //
4783 // Determine the implicit conversion sequence for the implicit
4784 // object parameter.
4785 QualType ImplicitParamType = From->getType();
4786 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4787 ImplicitParamType = FromPtrType->getPointeeType();
4788 CXXRecordDecl *ConversionContext
4789 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004790
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004791 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004792 = TryObjectArgumentInitialization(*this, From->getType(),
4793 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004794 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004795
John McCall0d1da222010-01-12 00:44:57 +00004796 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004797 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004798 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004799 return;
4800 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004801
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004802 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004803 // derived to base as such conversions are given Conversion Rank. They only
4804 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4805 QualType FromCanon
4806 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4807 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4808 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4809 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004810 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004811 return;
4812 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004813
Douglas Gregora1f013e2008-11-07 22:36:19 +00004814 // To determine what the conversion from the result of calling the
4815 // conversion function to the type we're eventually trying to
4816 // convert to (ToType), we need to synthesize a call to the
4817 // conversion function and attempt copy initialization from it. This
4818 // makes sure that we get the right semantics with respect to
4819 // lvalues/rvalues and the type. Fortunately, we can allocate this
4820 // call on the stack and we don't need its arguments to be
4821 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004822 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004823 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004824 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4825 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004826 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004827 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004828
Richard Smith48d24642011-07-13 22:53:21 +00004829 QualType ConversionType = Conversion->getConversionType();
4830 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004831 Candidate.Viable = false;
4832 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4833 return;
4834 }
4835
Richard Smith48d24642011-07-13 22:53:21 +00004836 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00004837
Mike Stump11289f42009-09-09 15:08:12 +00004838 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004839 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4840 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00004841 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004842 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004843 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004844 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004845 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004846 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00004847 /*InOverloadResolution=*/false,
4848 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004849
John McCall0d1da222010-01-12 00:44:57 +00004850 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004851 case ImplicitConversionSequence::StandardConversion:
4852 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004853
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004854 // C++ [over.ics.user]p3:
4855 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004856 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004857 // shall have exact match rank.
4858 if (Conversion->getPrimaryTemplate() &&
4859 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4860 Candidate.Viable = false;
4861 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4862 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004863
Douglas Gregorcba72b12011-01-21 05:18:22 +00004864 // C++0x [dcl.init.ref]p5:
4865 // In the second case, if the reference is an rvalue reference and
4866 // the second standard conversion sequence of the user-defined
4867 // conversion sequence includes an lvalue-to-rvalue conversion, the
4868 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004869 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004870 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4871 Candidate.Viable = false;
4872 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4873 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004874 break;
4875
4876 case ImplicitConversionSequence::BadConversion:
4877 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004878 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004879 break;
4880
4881 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004882 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00004883 "Can only end up with a standard conversion sequence or failure");
4884 }
4885}
4886
Douglas Gregor05155d82009-08-21 23:19:43 +00004887/// \brief Adds a conversion function template specialization
4888/// candidate to the overload set, using template argument deduction
4889/// to deduce the template arguments of the conversion function
4890/// template from the type that we are converting to (C++
4891/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004892void
Douglas Gregor05155d82009-08-21 23:19:43 +00004893Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004894 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004895 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004896 Expr *From, QualType ToType,
4897 OverloadCandidateSet &CandidateSet) {
4898 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4899 "Only conversion function templates permitted here");
4900
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004901 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4902 return;
4903
John McCallbc077cf2010-02-08 23:07:23 +00004904 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004905 CXXConversionDecl *Specialization = 0;
4906 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004907 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004908 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004909 CandidateSet.push_back(OverloadCandidate());
4910 OverloadCandidate &Candidate = CandidateSet.back();
4911 Candidate.FoundDecl = FoundDecl;
4912 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4913 Candidate.Viable = false;
4914 Candidate.FailureKind = ovl_fail_bad_deduction;
4915 Candidate.IsSurrogate = false;
4916 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004917 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004918 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004919 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004920 return;
4921 }
Mike Stump11289f42009-09-09 15:08:12 +00004922
Douglas Gregor05155d82009-08-21 23:19:43 +00004923 // Add the conversion function template specialization produced by
4924 // template argument deduction as a candidate.
4925 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004926 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004927 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004928}
4929
Douglas Gregorab7897a2008-11-19 22:57:39 +00004930/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4931/// converts the given @c Object to a function pointer via the
4932/// conversion function @c Conversion, and then attempts to call it
4933/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4934/// the type of function that we'll eventually be calling.
4935void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004936 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004937 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004938 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004939 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004940 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004941 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004942 if (!CandidateSet.isNewCandidate(Conversion))
4943 return;
4944
Douglas Gregor27381f32009-11-23 12:27:39 +00004945 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004946 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004947
Douglas Gregorab7897a2008-11-19 22:57:39 +00004948 CandidateSet.push_back(OverloadCandidate());
4949 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004950 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004951 Candidate.Function = 0;
4952 Candidate.Surrogate = Conversion;
4953 Candidate.Viable = true;
4954 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004955 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004956 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004957 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004958
4959 // Determine the implicit conversion sequence for the implicit
4960 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004961 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004962 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004963 Object->Classify(Context),
4964 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004965 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004966 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004967 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004968 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004969 return;
4970 }
4971
4972 // The first conversion is actually a user-defined conversion whose
4973 // first conversion is ObjectInit's standard conversion (which is
4974 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004975 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004976 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004977 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004978 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004979 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00004980 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00004981 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004982 = Candidate.Conversions[0].UserDefined.Before;
4983 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4984
Mike Stump11289f42009-09-09 15:08:12 +00004985 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004986 unsigned NumArgsInProto = Proto->getNumArgs();
4987
4988 // (C++ 13.3.2p2): A candidate function having fewer than m
4989 // parameters is viable only if it has an ellipsis in its parameter
4990 // list (8.3.5).
4991 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4992 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004993 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004994 return;
4995 }
4996
4997 // Function types don't have any default arguments, so just check if
4998 // we have enough arguments.
4999 if (NumArgs < NumArgsInProto) {
5000 // Not enough arguments.
5001 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005002 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005003 return;
5004 }
5005
5006 // Determine the implicit conversion sequences for each of the
5007 // arguments.
5008 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5009 if (ArgIdx < NumArgsInProto) {
5010 // (C++ 13.3.2p3): for F to be a viable function, there shall
5011 // exist for each argument an implicit conversion sequence
5012 // (13.3.3.1) that converts that argument to the corresponding
5013 // parameter of F.
5014 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00005015 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005016 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00005017 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00005018 /*InOverloadResolution=*/false,
5019 /*AllowObjCWritebackConversion=*/
5020 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00005021 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00005022 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005023 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005024 break;
5025 }
5026 } else {
5027 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5028 // argument for which there is no corresponding parameter is
5029 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00005030 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00005031 }
5032 }
5033}
5034
Douglas Gregor1baf54e2009-03-13 18:40:31 +00005035/// \brief Add overload candidates for overloaded operators that are
5036/// member functions.
5037///
5038/// Add the overloaded operator candidates that are member functions
5039/// for the operator Op that was used in an operator expression such
5040/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5041/// CandidateSet will store the added overload candidates. (C++
5042/// [over.match.oper]).
5043void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5044 SourceLocation OpLoc,
5045 Expr **Args, unsigned NumArgs,
5046 OverloadCandidateSet& CandidateSet,
5047 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00005048 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5049
5050 // C++ [over.match.oper]p3:
5051 // For a unary operator @ with an operand of a type whose
5052 // cv-unqualified version is T1, and for a binary operator @ with
5053 // a left operand of a type whose cv-unqualified version is T1 and
5054 // a right operand of a type whose cv-unqualified version is T2,
5055 // three sets of candidate functions, designated member
5056 // candidates, non-member candidates and built-in candidates, are
5057 // constructed as follows:
5058 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00005059
5060 // -- If T1 is a class type, the set of member candidates is the
5061 // result of the qualified lookup of T1::operator@
5062 // (13.3.1.1.1); otherwise, the set of member candidates is
5063 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005064 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005065 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00005066 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005067 return;
Mike Stump11289f42009-09-09 15:08:12 +00005068
John McCall27b18f82009-11-17 02:14:36 +00005069 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5070 LookupQualifiedName(Operators, T1Rec->getDecl());
5071 Operators.suppressDiagnostics();
5072
Mike Stump11289f42009-09-09 15:08:12 +00005073 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00005074 OperEnd = Operators.end();
5075 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00005076 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00005077 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005078 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00005079 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00005080 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00005081 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005082}
5083
Douglas Gregora11693b2008-11-12 17:17:38 +00005084/// AddBuiltinCandidate - Add a candidate for a built-in
5085/// operator. ResultTy and ParamTys are the result and parameter types
5086/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005087/// arguments being passed to the candidate. IsAssignmentOperator
5088/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005089/// operator. NumContextualBoolArguments is the number of arguments
5090/// (at the beginning of the argument list) that will be contextually
5091/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005092void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005093 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005094 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005095 bool IsAssignmentOperator,
5096 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005097 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005098 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005099
Douglas Gregora11693b2008-11-12 17:17:38 +00005100 // Add this candidate
5101 CandidateSet.push_back(OverloadCandidate());
5102 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00005103 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005104 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005105 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005106 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005107 Candidate.BuiltinTypes.ResultTy = ResultTy;
5108 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5109 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5110
5111 // Determine the implicit conversion sequences for each of the
5112 // arguments.
5113 Candidate.Viable = true;
5114 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00005115 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005116 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005117 // C++ [over.match.oper]p4:
5118 // For the built-in assignment operators, conversions of the
5119 // left operand are restricted as follows:
5120 // -- no temporaries are introduced to hold the left operand, and
5121 // -- no user-defined conversions are applied to the left
5122 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005123 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005124 //
5125 // We block these conversions by turning off user-defined
5126 // conversions, since that is the only way that initialization of
5127 // a reference to a non-class type can occur from something that
5128 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005129 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005130 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005131 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005132 Candidate.Conversions[ArgIdx]
5133 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005134 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005135 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005136 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005137 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005138 /*InOverloadResolution=*/false,
5139 /*AllowObjCWritebackConversion=*/
5140 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005141 }
John McCall0d1da222010-01-12 00:44:57 +00005142 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005143 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005144 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005145 break;
5146 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005147 }
5148}
5149
5150/// BuiltinCandidateTypeSet - A set of types that will be used for the
5151/// candidate operator functions for built-in operators (C++
5152/// [over.built]). The types are separated into pointer types and
5153/// enumeration types.
5154class BuiltinCandidateTypeSet {
5155 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005156 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005157
5158 /// PointerTypes - The set of pointer types that will be used in the
5159 /// built-in candidates.
5160 TypeSet PointerTypes;
5161
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005162 /// MemberPointerTypes - The set of member pointer types that will be
5163 /// used in the built-in candidates.
5164 TypeSet MemberPointerTypes;
5165
Douglas Gregora11693b2008-11-12 17:17:38 +00005166 /// EnumerationTypes - The set of enumeration types that will be
5167 /// used in the built-in candidates.
5168 TypeSet EnumerationTypes;
5169
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005170 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005171 /// candidates.
5172 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005173
5174 /// \brief A flag indicating non-record types are viable candidates
5175 bool HasNonRecordTypes;
5176
5177 /// \brief A flag indicating whether either arithmetic or enumeration types
5178 /// were present in the candidate set.
5179 bool HasArithmeticOrEnumeralTypes;
5180
Douglas Gregor80af3132011-05-21 23:15:46 +00005181 /// \brief A flag indicating whether the nullptr type was present in the
5182 /// candidate set.
5183 bool HasNullPtrType;
5184
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005185 /// Sema - The semantic analysis instance where we are building the
5186 /// candidate type set.
5187 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005188
Douglas Gregora11693b2008-11-12 17:17:38 +00005189 /// Context - The AST context in which we will build the type sets.
5190 ASTContext &Context;
5191
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005192 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5193 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005194 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005195
5196public:
5197 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005198 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005199
Mike Stump11289f42009-09-09 15:08:12 +00005200 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005201 : HasNonRecordTypes(false),
5202 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005203 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005204 SemaRef(SemaRef),
5205 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005206
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005207 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005208 SourceLocation Loc,
5209 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005210 bool AllowExplicitConversions,
5211 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005212
5213 /// pointer_begin - First pointer type found;
5214 iterator pointer_begin() { return PointerTypes.begin(); }
5215
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005216 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005217 iterator pointer_end() { return PointerTypes.end(); }
5218
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005219 /// member_pointer_begin - First member pointer type found;
5220 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5221
5222 /// member_pointer_end - Past the last member pointer type found;
5223 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5224
Douglas Gregora11693b2008-11-12 17:17:38 +00005225 /// enumeration_begin - First enumeration type found;
5226 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5227
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005228 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005229 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005230
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005231 iterator vector_begin() { return VectorTypes.begin(); }
5232 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005233
5234 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5235 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005236 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005237};
5238
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005239/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005240/// the set of pointer types along with any more-qualified variants of
5241/// that type. For example, if @p Ty is "int const *", this routine
5242/// will add "int const *", "int const volatile *", "int const
5243/// restrict *", and "int const volatile restrict *" to the set of
5244/// pointer types. Returns true if the add of @p Ty itself succeeded,
5245/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005246///
5247/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005248bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005249BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5250 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00005251
Douglas Gregora11693b2008-11-12 17:17:38 +00005252 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005253 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00005254 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005255
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005256 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00005257 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005258 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005259 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005260 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005261 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005262 buildObjCPtr = true;
5263 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005264 else
David Blaikie83d382b2011-09-23 05:06:16 +00005265 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005266 }
5267 else
5268 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005269
Sebastian Redl4990a632009-11-18 20:39:26 +00005270 // Don't add qualified variants of arrays. For one, they're not allowed
5271 // (the qualifier would sink to the element type), and for another, the
5272 // only overload situation where it matters is subscript or pointer +- int,
5273 // and those shouldn't have qualifier variants anyway.
5274 if (PointeeTy->isArrayType())
5275 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005276 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005277 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005278 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005279 bool hasVolatile = VisibleQuals.hasVolatile();
5280 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005281
John McCall8ccfcb52009-09-24 19:53:00 +00005282 // Iterate through all strict supersets of BaseCVR.
5283 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5284 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005285 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5286 // in the types.
5287 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5288 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005289 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005290 if (!buildObjCPtr)
5291 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5292 else
5293 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005294 }
5295
5296 return true;
5297}
5298
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005299/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5300/// to the set of pointer types along with any more-qualified variants of
5301/// that type. For example, if @p Ty is "int const *", this routine
5302/// will add "int const *", "int const volatile *", "int const
5303/// restrict *", and "int const volatile restrict *" to the set of
5304/// pointer types. Returns true if the add of @p Ty itself succeeded,
5305/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005306///
5307/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005308bool
5309BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5310 QualType Ty) {
5311 // Insert this type.
5312 if (!MemberPointerTypes.insert(Ty))
5313 return false;
5314
John McCall8ccfcb52009-09-24 19:53:00 +00005315 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5316 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005317
John McCall8ccfcb52009-09-24 19:53:00 +00005318 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005319 // Don't add qualified variants of arrays. For one, they're not allowed
5320 // (the qualifier would sink to the element type), and for another, the
5321 // only overload situation where it matters is subscript or pointer +- int,
5322 // and those shouldn't have qualifier variants anyway.
5323 if (PointeeTy->isArrayType())
5324 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005325 const Type *ClassTy = PointerTy->getClass();
5326
5327 // Iterate through all strict supersets of the pointee type's CVR
5328 // qualifiers.
5329 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5330 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5331 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005332
John McCall8ccfcb52009-09-24 19:53:00 +00005333 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005334 MemberPointerTypes.insert(
5335 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005336 }
5337
5338 return true;
5339}
5340
Douglas Gregora11693b2008-11-12 17:17:38 +00005341/// AddTypesConvertedFrom - Add each of the types to which the type @p
5342/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005343/// primarily interested in pointer types and enumeration types. We also
5344/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005345/// AllowUserConversions is true if we should look at the conversion
5346/// functions of a class type, and AllowExplicitConversions if we
5347/// should also include the explicit conversion functions of a class
5348/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005349void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005350BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005351 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005352 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005353 bool AllowExplicitConversions,
5354 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005355 // Only deal with canonical types.
5356 Ty = Context.getCanonicalType(Ty);
5357
5358 // Look through reference types; they aren't part of the type of an
5359 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005360 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005361 Ty = RefTy->getPointeeType();
5362
John McCall33ddac02011-01-19 10:06:00 +00005363 // If we're dealing with an array type, decay to the pointer.
5364 if (Ty->isArrayType())
5365 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5366
5367 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005368 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005369
Chandler Carruth00a38332010-12-13 01:44:01 +00005370 // Flag if we ever add a non-record type.
5371 const RecordType *TyRec = Ty->getAs<RecordType>();
5372 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5373
Chandler Carruth00a38332010-12-13 01:44:01 +00005374 // Flag if we encounter an arithmetic type.
5375 HasArithmeticOrEnumeralTypes =
5376 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5377
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005378 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5379 PointerTypes.insert(Ty);
5380 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005381 // Insert our type, and its more-qualified variants, into the set
5382 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005383 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005384 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005385 } else if (Ty->isMemberPointerType()) {
5386 // Member pointers are far easier, since the pointee can't be converted.
5387 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5388 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005389 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005390 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005391 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005392 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005393 // We treat vector types as arithmetic types in many contexts as an
5394 // extension.
5395 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005396 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005397 } else if (Ty->isNullPtrType()) {
5398 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005399 } else if (AllowUserConversions && TyRec) {
5400 // No conversion functions in incomplete types.
5401 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5402 return;
Mike Stump11289f42009-09-09 15:08:12 +00005403
Chandler Carruth00a38332010-12-13 01:44:01 +00005404 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5405 const UnresolvedSetImpl *Conversions
5406 = ClassDecl->getVisibleConversionFunctions();
5407 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5408 E = Conversions->end(); I != E; ++I) {
5409 NamedDecl *D = I.getDecl();
5410 if (isa<UsingShadowDecl>(D))
5411 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005412
Chandler Carruth00a38332010-12-13 01:44:01 +00005413 // Skip conversion function templates; they don't tell us anything
5414 // about which builtin types we can convert to.
5415 if (isa<FunctionTemplateDecl>(D))
5416 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005417
Chandler Carruth00a38332010-12-13 01:44:01 +00005418 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5419 if (AllowExplicitConversions || !Conv->isExplicit()) {
5420 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5421 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005422 }
5423 }
5424 }
5425}
5426
Douglas Gregor84605ae2009-08-24 13:43:27 +00005427/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5428/// the volatile- and non-volatile-qualified assignment operators for the
5429/// given type to the candidate set.
5430static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5431 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005432 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005433 unsigned NumArgs,
5434 OverloadCandidateSet &CandidateSet) {
5435 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005436
Douglas Gregor84605ae2009-08-24 13:43:27 +00005437 // T& operator=(T&, T)
5438 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5439 ParamTypes[1] = T;
5440 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5441 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005442
Douglas Gregor84605ae2009-08-24 13:43:27 +00005443 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5444 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005445 ParamTypes[0]
5446 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005447 ParamTypes[1] = T;
5448 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005449 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005450 }
5451}
Mike Stump11289f42009-09-09 15:08:12 +00005452
Sebastian Redl1054fae2009-10-25 17:03:50 +00005453/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5454/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005455static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5456 Qualifiers VRQuals;
5457 const RecordType *TyRec;
5458 if (const MemberPointerType *RHSMPType =
5459 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005460 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005461 else
5462 TyRec = ArgExpr->getType()->getAs<RecordType>();
5463 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005464 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005465 VRQuals.addVolatile();
5466 VRQuals.addRestrict();
5467 return VRQuals;
5468 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005469
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005470 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005471 if (!ClassDecl->hasDefinition())
5472 return VRQuals;
5473
John McCallad371252010-01-20 00:46:10 +00005474 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005475 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005476
John McCallad371252010-01-20 00:46:10 +00005477 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005478 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005479 NamedDecl *D = I.getDecl();
5480 if (isa<UsingShadowDecl>(D))
5481 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5482 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005483 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5484 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5485 CanTy = ResTypeRef->getPointeeType();
5486 // Need to go down the pointer/mempointer chain and add qualifiers
5487 // as see them.
5488 bool done = false;
5489 while (!done) {
5490 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5491 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005492 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005493 CanTy->getAs<MemberPointerType>())
5494 CanTy = ResTypeMPtr->getPointeeType();
5495 else
5496 done = true;
5497 if (CanTy.isVolatileQualified())
5498 VRQuals.addVolatile();
5499 if (CanTy.isRestrictQualified())
5500 VRQuals.addRestrict();
5501 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5502 return VRQuals;
5503 }
5504 }
5505 }
5506 return VRQuals;
5507}
John McCall52872982010-11-13 05:51:15 +00005508
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005509namespace {
John McCall52872982010-11-13 05:51:15 +00005510
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005511/// \brief Helper class to manage the addition of builtin operator overload
5512/// candidates. It provides shared state and utility methods used throughout
5513/// the process, as well as a helper method to add each group of builtin
5514/// operator overloads from the standard to a candidate set.
5515class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005516 // Common instance state available to all overload candidate addition methods.
5517 Sema &S;
5518 Expr **Args;
5519 unsigned NumArgs;
5520 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005521 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005522 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005523 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005524
Chandler Carruthc6586e52010-12-12 10:35:00 +00005525 // Define some constants used to index and iterate over the arithemetic types
5526 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005527 // The "promoted arithmetic types" are the arithmetic
5528 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005529 static const unsigned FirstIntegralType = 3;
5530 static const unsigned LastIntegralType = 18;
5531 static const unsigned FirstPromotedIntegralType = 3,
5532 LastPromotedIntegralType = 9;
5533 static const unsigned FirstPromotedArithmeticType = 0,
5534 LastPromotedArithmeticType = 9;
5535 static const unsigned NumArithmeticTypes = 18;
5536
Chandler Carruthc6586e52010-12-12 10:35:00 +00005537 /// \brief Get the canonical type for a given arithmetic type index.
5538 CanQualType getArithmeticType(unsigned index) {
5539 assert(index < NumArithmeticTypes);
5540 static CanQualType ASTContext::* const
5541 ArithmeticTypes[NumArithmeticTypes] = {
5542 // Start of promoted types.
5543 &ASTContext::FloatTy,
5544 &ASTContext::DoubleTy,
5545 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005546
Chandler Carruthc6586e52010-12-12 10:35:00 +00005547 // Start of integral types.
5548 &ASTContext::IntTy,
5549 &ASTContext::LongTy,
5550 &ASTContext::LongLongTy,
5551 &ASTContext::UnsignedIntTy,
5552 &ASTContext::UnsignedLongTy,
5553 &ASTContext::UnsignedLongLongTy,
5554 // End of promoted types.
5555
5556 &ASTContext::BoolTy,
5557 &ASTContext::CharTy,
5558 &ASTContext::WCharTy,
5559 &ASTContext::Char16Ty,
5560 &ASTContext::Char32Ty,
5561 &ASTContext::SignedCharTy,
5562 &ASTContext::ShortTy,
5563 &ASTContext::UnsignedCharTy,
5564 &ASTContext::UnsignedShortTy,
5565 // End of integral types.
5566 // FIXME: What about complex?
5567 };
5568 return S.Context.*ArithmeticTypes[index];
5569 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005570
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005571 /// \brief Gets the canonical type resulting from the usual arithemetic
5572 /// converions for the given arithmetic types.
5573 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5574 // Accelerator table for performing the usual arithmetic conversions.
5575 // The rules are basically:
5576 // - if either is floating-point, use the wider floating-point
5577 // - if same signedness, use the higher rank
5578 // - if same size, use unsigned of the higher rank
5579 // - use the larger type
5580 // These rules, together with the axiom that higher ranks are
5581 // never smaller, are sufficient to precompute all of these results
5582 // *except* when dealing with signed types of higher rank.
5583 // (we could precompute SLL x UI for all known platforms, but it's
5584 // better not to make any assumptions).
5585 enum PromotedType {
5586 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5587 };
5588 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5589 [LastPromotedArithmeticType] = {
5590 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5591 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5592 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5593 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5594 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5595 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5596 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5597 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5598 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5599 };
5600
5601 assert(L < LastPromotedArithmeticType);
5602 assert(R < LastPromotedArithmeticType);
5603 int Idx = ConversionsTable[L][R];
5604
5605 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005606 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005607
5608 // Slow path: we need to compare widths.
5609 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005610 CanQualType LT = getArithmeticType(L),
5611 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005612 unsigned LW = S.Context.getIntWidth(LT),
5613 RW = S.Context.getIntWidth(RT);
5614
5615 // If they're different widths, use the signed type.
5616 if (LW > RW) return LT;
5617 else if (LW < RW) return RT;
5618
5619 // Otherwise, use the unsigned type of the signed type's rank.
5620 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5621 assert(L == SLL || R == SLL);
5622 return S.Context.UnsignedLongLongTy;
5623 }
5624
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005625 /// \brief Helper method to factor out the common pattern of adding overloads
5626 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005627 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5628 bool HasVolatile) {
5629 QualType ParamTypes[2] = {
5630 S.Context.getLValueReferenceType(CandidateTy),
5631 S.Context.IntTy
5632 };
5633
5634 // Non-volatile version.
5635 if (NumArgs == 1)
5636 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5637 else
5638 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5639
5640 // Use a heuristic to reduce number of builtin candidates in the set:
5641 // add volatile version only if there are conversions to a volatile type.
5642 if (HasVolatile) {
5643 ParamTypes[0] =
5644 S.Context.getLValueReferenceType(
5645 S.Context.getVolatileType(CandidateTy));
5646 if (NumArgs == 1)
5647 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5648 else
5649 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5650 }
5651 }
5652
5653public:
5654 BuiltinOperatorOverloadBuilder(
5655 Sema &S, Expr **Args, unsigned NumArgs,
5656 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005657 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005658 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005659 OverloadCandidateSet &CandidateSet)
5660 : S(S), Args(Args), NumArgs(NumArgs),
5661 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005662 HasArithmeticOrEnumeralCandidateType(
5663 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005664 CandidateTypes(CandidateTypes),
5665 CandidateSet(CandidateSet) {
5666 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005667 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005668 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005669 assert(getArithmeticType(LastPromotedIntegralType - 1)
5670 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005671 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005672 assert(getArithmeticType(FirstPromotedArithmeticType)
5673 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005674 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005675 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5676 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005677 "Invalid last promoted arithmetic type");
5678 }
5679
5680 // C++ [over.built]p3:
5681 //
5682 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5683 // is either volatile or empty, there exist candidate operator
5684 // functions of the form
5685 //
5686 // VQ T& operator++(VQ T&);
5687 // T operator++(VQ T&, int);
5688 //
5689 // C++ [over.built]p4:
5690 //
5691 // For every pair (T, VQ), where T is an arithmetic type other
5692 // than bool, and VQ is either volatile or empty, there exist
5693 // candidate operator functions of the form
5694 //
5695 // VQ T& operator--(VQ T&);
5696 // T operator--(VQ T&, int);
5697 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005698 if (!HasArithmeticOrEnumeralCandidateType)
5699 return;
5700
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005701 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5702 Arith < NumArithmeticTypes; ++Arith) {
5703 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005704 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005705 VisibleTypeConversionsQuals.hasVolatile());
5706 }
5707 }
5708
5709 // C++ [over.built]p5:
5710 //
5711 // For every pair (T, VQ), where T is a cv-qualified or
5712 // cv-unqualified object type, and VQ is either volatile or
5713 // empty, there exist candidate operator functions of the form
5714 //
5715 // T*VQ& operator++(T*VQ&);
5716 // T*VQ& operator--(T*VQ&);
5717 // T* operator++(T*VQ&, int);
5718 // T* operator--(T*VQ&, int);
5719 void addPlusPlusMinusMinusPointerOverloads() {
5720 for (BuiltinCandidateTypeSet::iterator
5721 Ptr = CandidateTypes[0].pointer_begin(),
5722 PtrEnd = CandidateTypes[0].pointer_end();
5723 Ptr != PtrEnd; ++Ptr) {
5724 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005725 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005726 continue;
5727
5728 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5729 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5730 VisibleTypeConversionsQuals.hasVolatile()));
5731 }
5732 }
5733
5734 // C++ [over.built]p6:
5735 // For every cv-qualified or cv-unqualified object type T, there
5736 // exist candidate operator functions of the form
5737 //
5738 // T& operator*(T*);
5739 //
5740 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005741 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005742 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005743 // T& operator*(T*);
5744 void addUnaryStarPointerOverloads() {
5745 for (BuiltinCandidateTypeSet::iterator
5746 Ptr = CandidateTypes[0].pointer_begin(),
5747 PtrEnd = CandidateTypes[0].pointer_end();
5748 Ptr != PtrEnd; ++Ptr) {
5749 QualType ParamTy = *Ptr;
5750 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005751 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5752 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005753
Douglas Gregor02824322011-01-26 19:30:28 +00005754 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5755 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5756 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005757
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005758 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5759 &ParamTy, Args, 1, CandidateSet);
5760 }
5761 }
5762
5763 // C++ [over.built]p9:
5764 // For every promoted arithmetic type T, there exist candidate
5765 // operator functions of the form
5766 //
5767 // T operator+(T);
5768 // T operator-(T);
5769 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005770 if (!HasArithmeticOrEnumeralCandidateType)
5771 return;
5772
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005773 for (unsigned Arith = FirstPromotedArithmeticType;
5774 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005775 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005776 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5777 }
5778
5779 // Extension: We also add these operators for vector types.
5780 for (BuiltinCandidateTypeSet::iterator
5781 Vec = CandidateTypes[0].vector_begin(),
5782 VecEnd = CandidateTypes[0].vector_end();
5783 Vec != VecEnd; ++Vec) {
5784 QualType VecTy = *Vec;
5785 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5786 }
5787 }
5788
5789 // C++ [over.built]p8:
5790 // For every type T, there exist candidate operator functions of
5791 // the form
5792 //
5793 // T* operator+(T*);
5794 void addUnaryPlusPointerOverloads() {
5795 for (BuiltinCandidateTypeSet::iterator
5796 Ptr = CandidateTypes[0].pointer_begin(),
5797 PtrEnd = CandidateTypes[0].pointer_end();
5798 Ptr != PtrEnd; ++Ptr) {
5799 QualType ParamTy = *Ptr;
5800 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5801 }
5802 }
5803
5804 // C++ [over.built]p10:
5805 // For every promoted integral type T, there exist candidate
5806 // operator functions of the form
5807 //
5808 // T operator~(T);
5809 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005810 if (!HasArithmeticOrEnumeralCandidateType)
5811 return;
5812
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005813 for (unsigned Int = FirstPromotedIntegralType;
5814 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005815 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005816 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5817 }
5818
5819 // Extension: We also add this operator for vector types.
5820 for (BuiltinCandidateTypeSet::iterator
5821 Vec = CandidateTypes[0].vector_begin(),
5822 VecEnd = CandidateTypes[0].vector_end();
5823 Vec != VecEnd; ++Vec) {
5824 QualType VecTy = *Vec;
5825 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5826 }
5827 }
5828
5829 // C++ [over.match.oper]p16:
5830 // For every pointer to member type T, there exist candidate operator
5831 // functions of the form
5832 //
5833 // bool operator==(T,T);
5834 // bool operator!=(T,T);
5835 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5836 /// Set of (canonical) types that we've already handled.
5837 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5838
5839 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5840 for (BuiltinCandidateTypeSet::iterator
5841 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5842 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5843 MemPtr != MemPtrEnd;
5844 ++MemPtr) {
5845 // Don't add the same builtin candidate twice.
5846 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5847 continue;
5848
5849 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5850 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5851 CandidateSet);
5852 }
5853 }
5854 }
5855
5856 // C++ [over.built]p15:
5857 //
Douglas Gregor80af3132011-05-21 23:15:46 +00005858 // For every T, where T is an enumeration type, a pointer type, or
5859 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005860 //
5861 // bool operator<(T, T);
5862 // bool operator>(T, T);
5863 // bool operator<=(T, T);
5864 // bool operator>=(T, T);
5865 // bool operator==(T, T);
5866 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005867 void addRelationalPointerOrEnumeralOverloads() {
5868 // C++ [over.built]p1:
5869 // If there is a user-written candidate with the same name and parameter
5870 // types as a built-in candidate operator function, the built-in operator
5871 // function is hidden and is not included in the set of candidate
5872 // functions.
5873 //
5874 // The text is actually in a note, but if we don't implement it then we end
5875 // up with ambiguities when the user provides an overloaded operator for
5876 // an enumeration type. Note that only enumeration types have this problem,
5877 // so we track which enumeration types we've seen operators for. Also, the
5878 // only other overloaded operator with enumeration argumenst, operator=,
5879 // cannot be overloaded for enumeration types, so this is the only place
5880 // where we must suppress candidates like this.
5881 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5882 UserDefinedBinaryOperators;
5883
5884 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5885 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5886 CandidateTypes[ArgIdx].enumeration_end()) {
5887 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5888 CEnd = CandidateSet.end();
5889 C != CEnd; ++C) {
5890 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5891 continue;
5892
5893 QualType FirstParamType =
5894 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5895 QualType SecondParamType =
5896 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5897
5898 // Skip if either parameter isn't of enumeral type.
5899 if (!FirstParamType->isEnumeralType() ||
5900 !SecondParamType->isEnumeralType())
5901 continue;
5902
5903 // Add this operator to the set of known user-defined operators.
5904 UserDefinedBinaryOperators.insert(
5905 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5906 S.Context.getCanonicalType(SecondParamType)));
5907 }
5908 }
5909 }
5910
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005911 /// Set of (canonical) types that we've already handled.
5912 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5913
5914 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5915 for (BuiltinCandidateTypeSet::iterator
5916 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5917 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5918 Ptr != PtrEnd; ++Ptr) {
5919 // Don't add the same builtin candidate twice.
5920 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5921 continue;
5922
5923 QualType ParamTypes[2] = { *Ptr, *Ptr };
5924 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5925 CandidateSet);
5926 }
5927 for (BuiltinCandidateTypeSet::iterator
5928 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5929 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5930 Enum != EnumEnd; ++Enum) {
5931 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5932
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005933 // Don't add the same builtin candidate twice, or if a user defined
5934 // candidate exists.
5935 if (!AddedTypes.insert(CanonType) ||
5936 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5937 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005938 continue;
5939
5940 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005941 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5942 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005943 }
Douglas Gregor80af3132011-05-21 23:15:46 +00005944
5945 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5946 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5947 if (AddedTypes.insert(NullPtrTy) &&
5948 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5949 NullPtrTy))) {
5950 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5951 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5952 CandidateSet);
5953 }
5954 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005955 }
5956 }
5957
5958 // C++ [over.built]p13:
5959 //
5960 // For every cv-qualified or cv-unqualified object type T
5961 // there exist candidate operator functions of the form
5962 //
5963 // T* operator+(T*, ptrdiff_t);
5964 // T& operator[](T*, ptrdiff_t); [BELOW]
5965 // T* operator-(T*, ptrdiff_t);
5966 // T* operator+(ptrdiff_t, T*);
5967 // T& operator[](ptrdiff_t, T*); [BELOW]
5968 //
5969 // C++ [over.built]p14:
5970 //
5971 // For every T, where T is a pointer to object type, there
5972 // exist candidate operator functions of the form
5973 //
5974 // ptrdiff_t operator-(T, T);
5975 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5976 /// Set of (canonical) types that we've already handled.
5977 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5978
5979 for (int Arg = 0; Arg < 2; ++Arg) {
5980 QualType AsymetricParamTypes[2] = {
5981 S.Context.getPointerDiffType(),
5982 S.Context.getPointerDiffType(),
5983 };
5984 for (BuiltinCandidateTypeSet::iterator
5985 Ptr = CandidateTypes[Arg].pointer_begin(),
5986 PtrEnd = CandidateTypes[Arg].pointer_end();
5987 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005988 QualType PointeeTy = (*Ptr)->getPointeeType();
5989 if (!PointeeTy->isObjectType())
5990 continue;
5991
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005992 AsymetricParamTypes[Arg] = *Ptr;
5993 if (Arg == 0 || Op == OO_Plus) {
5994 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5995 // T* operator+(ptrdiff_t, T*);
5996 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5997 CandidateSet);
5998 }
5999 if (Op == OO_Minus) {
6000 // ptrdiff_t operator-(T, T);
6001 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6002 continue;
6003
6004 QualType ParamTypes[2] = { *Ptr, *Ptr };
6005 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6006 Args, 2, CandidateSet);
6007 }
6008 }
6009 }
6010 }
6011
6012 // C++ [over.built]p12:
6013 //
6014 // For every pair of promoted arithmetic types L and R, there
6015 // exist candidate operator functions of the form
6016 //
6017 // LR operator*(L, R);
6018 // LR operator/(L, R);
6019 // LR operator+(L, R);
6020 // LR operator-(L, R);
6021 // bool operator<(L, R);
6022 // bool operator>(L, R);
6023 // bool operator<=(L, R);
6024 // bool operator>=(L, R);
6025 // bool operator==(L, R);
6026 // bool operator!=(L, R);
6027 //
6028 // where LR is the result of the usual arithmetic conversions
6029 // between types L and R.
6030 //
6031 // C++ [over.built]p24:
6032 //
6033 // For every pair of promoted arithmetic types L and R, there exist
6034 // candidate operator functions of the form
6035 //
6036 // LR operator?(bool, L, R);
6037 //
6038 // where LR is the result of the usual arithmetic conversions
6039 // between types L and R.
6040 // Our candidates ignore the first parameter.
6041 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006042 if (!HasArithmeticOrEnumeralCandidateType)
6043 return;
6044
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006045 for (unsigned Left = FirstPromotedArithmeticType;
6046 Left < LastPromotedArithmeticType; ++Left) {
6047 for (unsigned Right = FirstPromotedArithmeticType;
6048 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006049 QualType LandR[2] = { getArithmeticType(Left),
6050 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006051 QualType Result =
6052 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006053 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006054 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6055 }
6056 }
6057
6058 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6059 // conditional operator for vector types.
6060 for (BuiltinCandidateTypeSet::iterator
6061 Vec1 = CandidateTypes[0].vector_begin(),
6062 Vec1End = CandidateTypes[0].vector_end();
6063 Vec1 != Vec1End; ++Vec1) {
6064 for (BuiltinCandidateTypeSet::iterator
6065 Vec2 = CandidateTypes[1].vector_begin(),
6066 Vec2End = CandidateTypes[1].vector_end();
6067 Vec2 != Vec2End; ++Vec2) {
6068 QualType LandR[2] = { *Vec1, *Vec2 };
6069 QualType Result = S.Context.BoolTy;
6070 if (!isComparison) {
6071 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6072 Result = *Vec1;
6073 else
6074 Result = *Vec2;
6075 }
6076
6077 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6078 }
6079 }
6080 }
6081
6082 // C++ [over.built]p17:
6083 //
6084 // For every pair of promoted integral types L and R, there
6085 // exist candidate operator functions of the form
6086 //
6087 // LR operator%(L, R);
6088 // LR operator&(L, R);
6089 // LR operator^(L, R);
6090 // LR operator|(L, R);
6091 // L operator<<(L, R);
6092 // L operator>>(L, R);
6093 //
6094 // where LR is the result of the usual arithmetic conversions
6095 // between types L and R.
6096 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006097 if (!HasArithmeticOrEnumeralCandidateType)
6098 return;
6099
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006100 for (unsigned Left = FirstPromotedIntegralType;
6101 Left < LastPromotedIntegralType; ++Left) {
6102 for (unsigned Right = FirstPromotedIntegralType;
6103 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006104 QualType LandR[2] = { getArithmeticType(Left),
6105 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006106 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6107 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006108 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006109 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6110 }
6111 }
6112 }
6113
6114 // C++ [over.built]p20:
6115 //
6116 // For every pair (T, VQ), where T is an enumeration or
6117 // pointer to member type and VQ is either volatile or
6118 // empty, there exist candidate operator functions of the form
6119 //
6120 // VQ T& operator=(VQ T&, T);
6121 void addAssignmentMemberPointerOrEnumeralOverloads() {
6122 /// Set of (canonical) types that we've already handled.
6123 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6124
6125 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6126 for (BuiltinCandidateTypeSet::iterator
6127 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6128 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6129 Enum != EnumEnd; ++Enum) {
6130 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6131 continue;
6132
6133 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6134 CandidateSet);
6135 }
6136
6137 for (BuiltinCandidateTypeSet::iterator
6138 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6139 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6140 MemPtr != MemPtrEnd; ++MemPtr) {
6141 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6142 continue;
6143
6144 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6145 CandidateSet);
6146 }
6147 }
6148 }
6149
6150 // C++ [over.built]p19:
6151 //
6152 // For every pair (T, VQ), where T is any type and VQ is either
6153 // volatile or empty, there exist candidate operator functions
6154 // of the form
6155 //
6156 // T*VQ& operator=(T*VQ&, T*);
6157 //
6158 // C++ [over.built]p21:
6159 //
6160 // For every pair (T, VQ), where T is a cv-qualified or
6161 // cv-unqualified object type and VQ is either volatile or
6162 // empty, there exist candidate operator functions of the form
6163 //
6164 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6165 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6166 void addAssignmentPointerOverloads(bool isEqualOp) {
6167 /// Set of (canonical) types that we've already handled.
6168 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6169
6170 for (BuiltinCandidateTypeSet::iterator
6171 Ptr = CandidateTypes[0].pointer_begin(),
6172 PtrEnd = CandidateTypes[0].pointer_end();
6173 Ptr != PtrEnd; ++Ptr) {
6174 // If this is operator=, keep track of the builtin candidates we added.
6175 if (isEqualOp)
6176 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006177 else if (!(*Ptr)->getPointeeType()->isObjectType())
6178 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006179
6180 // non-volatile version
6181 QualType ParamTypes[2] = {
6182 S.Context.getLValueReferenceType(*Ptr),
6183 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6184 };
6185 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6186 /*IsAssigmentOperator=*/ isEqualOp);
6187
6188 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6189 VisibleTypeConversionsQuals.hasVolatile()) {
6190 // volatile version
6191 ParamTypes[0] =
6192 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6193 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6194 /*IsAssigmentOperator=*/isEqualOp);
6195 }
6196 }
6197
6198 if (isEqualOp) {
6199 for (BuiltinCandidateTypeSet::iterator
6200 Ptr = CandidateTypes[1].pointer_begin(),
6201 PtrEnd = CandidateTypes[1].pointer_end();
6202 Ptr != PtrEnd; ++Ptr) {
6203 // Make sure we don't add the same candidate twice.
6204 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6205 continue;
6206
Chandler Carruth8e543b32010-12-12 08:17:55 +00006207 QualType ParamTypes[2] = {
6208 S.Context.getLValueReferenceType(*Ptr),
6209 *Ptr,
6210 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006211
6212 // non-volatile version
6213 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6214 /*IsAssigmentOperator=*/true);
6215
6216 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6217 VisibleTypeConversionsQuals.hasVolatile()) {
6218 // volatile version
6219 ParamTypes[0] =
6220 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006221 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6222 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006223 }
6224 }
6225 }
6226 }
6227
6228 // C++ [over.built]p18:
6229 //
6230 // For every triple (L, VQ, R), where L is an arithmetic type,
6231 // VQ is either volatile or empty, and R is a promoted
6232 // arithmetic type, there exist candidate operator functions of
6233 // the form
6234 //
6235 // VQ L& operator=(VQ L&, R);
6236 // VQ L& operator*=(VQ L&, R);
6237 // VQ L& operator/=(VQ L&, R);
6238 // VQ L& operator+=(VQ L&, R);
6239 // VQ L& operator-=(VQ L&, R);
6240 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006241 if (!HasArithmeticOrEnumeralCandidateType)
6242 return;
6243
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006244 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6245 for (unsigned Right = FirstPromotedArithmeticType;
6246 Right < LastPromotedArithmeticType; ++Right) {
6247 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006248 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006249
6250 // Add this built-in operator as a candidate (VQ is empty).
6251 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006252 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006253 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6254 /*IsAssigmentOperator=*/isEqualOp);
6255
6256 // Add this built-in operator as a candidate (VQ is 'volatile').
6257 if (VisibleTypeConversionsQuals.hasVolatile()) {
6258 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006259 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006260 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006261 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6262 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006263 /*IsAssigmentOperator=*/isEqualOp);
6264 }
6265 }
6266 }
6267
6268 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6269 for (BuiltinCandidateTypeSet::iterator
6270 Vec1 = CandidateTypes[0].vector_begin(),
6271 Vec1End = CandidateTypes[0].vector_end();
6272 Vec1 != Vec1End; ++Vec1) {
6273 for (BuiltinCandidateTypeSet::iterator
6274 Vec2 = CandidateTypes[1].vector_begin(),
6275 Vec2End = CandidateTypes[1].vector_end();
6276 Vec2 != Vec2End; ++Vec2) {
6277 QualType ParamTypes[2];
6278 ParamTypes[1] = *Vec2;
6279 // Add this built-in operator as a candidate (VQ is empty).
6280 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6281 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6282 /*IsAssigmentOperator=*/isEqualOp);
6283
6284 // Add this built-in operator as a candidate (VQ is 'volatile').
6285 if (VisibleTypeConversionsQuals.hasVolatile()) {
6286 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6287 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006288 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6289 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006290 /*IsAssigmentOperator=*/isEqualOp);
6291 }
6292 }
6293 }
6294 }
6295
6296 // C++ [over.built]p22:
6297 //
6298 // For every triple (L, VQ, R), where L is an integral type, VQ
6299 // is either volatile or empty, and R is a promoted integral
6300 // type, there exist candidate operator functions of the form
6301 //
6302 // VQ L& operator%=(VQ L&, R);
6303 // VQ L& operator<<=(VQ L&, R);
6304 // VQ L& operator>>=(VQ L&, R);
6305 // VQ L& operator&=(VQ L&, R);
6306 // VQ L& operator^=(VQ L&, R);
6307 // VQ L& operator|=(VQ L&, R);
6308 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006309 if (!HasArithmeticOrEnumeralCandidateType)
6310 return;
6311
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006312 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6313 for (unsigned Right = FirstPromotedIntegralType;
6314 Right < LastPromotedIntegralType; ++Right) {
6315 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006316 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006317
6318 // Add this built-in operator as a candidate (VQ is empty).
6319 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006320 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006321 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6322 if (VisibleTypeConversionsQuals.hasVolatile()) {
6323 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006324 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006325 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6326 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6327 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6328 CandidateSet);
6329 }
6330 }
6331 }
6332 }
6333
6334 // C++ [over.operator]p23:
6335 //
6336 // There also exist candidate operator functions of the form
6337 //
6338 // bool operator!(bool);
6339 // bool operator&&(bool, bool);
6340 // bool operator||(bool, bool);
6341 void addExclaimOverload() {
6342 QualType ParamTy = S.Context.BoolTy;
6343 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6344 /*IsAssignmentOperator=*/false,
6345 /*NumContextualBoolArguments=*/1);
6346 }
6347 void addAmpAmpOrPipePipeOverload() {
6348 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6349 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6350 /*IsAssignmentOperator=*/false,
6351 /*NumContextualBoolArguments=*/2);
6352 }
6353
6354 // C++ [over.built]p13:
6355 //
6356 // For every cv-qualified or cv-unqualified object type T there
6357 // exist candidate operator functions of the form
6358 //
6359 // T* operator+(T*, ptrdiff_t); [ABOVE]
6360 // T& operator[](T*, ptrdiff_t);
6361 // T* operator-(T*, ptrdiff_t); [ABOVE]
6362 // T* operator+(ptrdiff_t, T*); [ABOVE]
6363 // T& operator[](ptrdiff_t, T*);
6364 void addSubscriptOverloads() {
6365 for (BuiltinCandidateTypeSet::iterator
6366 Ptr = CandidateTypes[0].pointer_begin(),
6367 PtrEnd = CandidateTypes[0].pointer_end();
6368 Ptr != PtrEnd; ++Ptr) {
6369 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6370 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006371 if (!PointeeType->isObjectType())
6372 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006373
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006374 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6375
6376 // T& operator[](T*, ptrdiff_t)
6377 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6378 }
6379
6380 for (BuiltinCandidateTypeSet::iterator
6381 Ptr = CandidateTypes[1].pointer_begin(),
6382 PtrEnd = CandidateTypes[1].pointer_end();
6383 Ptr != PtrEnd; ++Ptr) {
6384 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6385 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006386 if (!PointeeType->isObjectType())
6387 continue;
6388
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006389 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6390
6391 // T& operator[](ptrdiff_t, T*)
6392 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6393 }
6394 }
6395
6396 // C++ [over.built]p11:
6397 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6398 // C1 is the same type as C2 or is a derived class of C2, T is an object
6399 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6400 // there exist candidate operator functions of the form
6401 //
6402 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6403 //
6404 // where CV12 is the union of CV1 and CV2.
6405 void addArrowStarOverloads() {
6406 for (BuiltinCandidateTypeSet::iterator
6407 Ptr = CandidateTypes[0].pointer_begin(),
6408 PtrEnd = CandidateTypes[0].pointer_end();
6409 Ptr != PtrEnd; ++Ptr) {
6410 QualType C1Ty = (*Ptr);
6411 QualType C1;
6412 QualifierCollector Q1;
6413 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6414 if (!isa<RecordType>(C1))
6415 continue;
6416 // heuristic to reduce number of builtin candidates in the set.
6417 // Add volatile/restrict version only if there are conversions to a
6418 // volatile/restrict type.
6419 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6420 continue;
6421 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6422 continue;
6423 for (BuiltinCandidateTypeSet::iterator
6424 MemPtr = CandidateTypes[1].member_pointer_begin(),
6425 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6426 MemPtr != MemPtrEnd; ++MemPtr) {
6427 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6428 QualType C2 = QualType(mptr->getClass(), 0);
6429 C2 = C2.getUnqualifiedType();
6430 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6431 break;
6432 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6433 // build CV12 T&
6434 QualType T = mptr->getPointeeType();
6435 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6436 T.isVolatileQualified())
6437 continue;
6438 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6439 T.isRestrictQualified())
6440 continue;
6441 T = Q1.apply(S.Context, T);
6442 QualType ResultTy = S.Context.getLValueReferenceType(T);
6443 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6444 }
6445 }
6446 }
6447
6448 // Note that we don't consider the first argument, since it has been
6449 // contextually converted to bool long ago. The candidates below are
6450 // therefore added as binary.
6451 //
6452 // C++ [over.built]p25:
6453 // For every type T, where T is a pointer, pointer-to-member, or scoped
6454 // enumeration type, there exist candidate operator functions of the form
6455 //
6456 // T operator?(bool, T, T);
6457 //
6458 void addConditionalOperatorOverloads() {
6459 /// Set of (canonical) types that we've already handled.
6460 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6461
6462 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6463 for (BuiltinCandidateTypeSet::iterator
6464 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6465 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6466 Ptr != PtrEnd; ++Ptr) {
6467 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6468 continue;
6469
6470 QualType ParamTypes[2] = { *Ptr, *Ptr };
6471 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6472 }
6473
6474 for (BuiltinCandidateTypeSet::iterator
6475 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6476 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6477 MemPtr != MemPtrEnd; ++MemPtr) {
6478 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6479 continue;
6480
6481 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6482 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6483 }
6484
6485 if (S.getLangOptions().CPlusPlus0x) {
6486 for (BuiltinCandidateTypeSet::iterator
6487 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6488 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6489 Enum != EnumEnd; ++Enum) {
6490 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6491 continue;
6492
6493 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6494 continue;
6495
6496 QualType ParamTypes[2] = { *Enum, *Enum };
6497 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6498 }
6499 }
6500 }
6501 }
6502};
6503
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006504} // end anonymous namespace
6505
6506/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6507/// operator overloads to the candidate set (C++ [over.built]), based
6508/// on the operator @p Op and the arguments given. For example, if the
6509/// operator is a binary '+', this routine might add "int
6510/// operator+(int, int)" to cover integer addition.
6511void
6512Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6513 SourceLocation OpLoc,
6514 Expr **Args, unsigned NumArgs,
6515 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006516 // Find all of the types that the arguments can convert to, but only
6517 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006518 // that make use of these types. Also record whether we encounter non-record
6519 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006520 Qualifiers VisibleTypeConversionsQuals;
6521 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006522 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6523 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006524
6525 bool HasNonRecordCandidateType = false;
6526 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006527 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006528 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6529 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6530 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6531 OpLoc,
6532 true,
6533 (Op == OO_Exclaim ||
6534 Op == OO_AmpAmp ||
6535 Op == OO_PipePipe),
6536 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006537 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6538 CandidateTypes[ArgIdx].hasNonRecordTypes();
6539 HasArithmeticOrEnumeralCandidateType =
6540 HasArithmeticOrEnumeralCandidateType ||
6541 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006542 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006543
Chandler Carruth00a38332010-12-13 01:44:01 +00006544 // Exit early when no non-record types have been added to the candidate set
6545 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00006546 //
6547 // We can't exit early for !, ||, or &&, since there we have always have
6548 // 'bool' overloads.
6549 if (!HasNonRecordCandidateType &&
6550 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00006551 return;
6552
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006553 // Setup an object to manage the common state for building overloads.
6554 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6555 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006556 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006557 CandidateTypes, CandidateSet);
6558
6559 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006560 switch (Op) {
6561 case OO_None:
6562 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00006563 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00006564
Chandler Carruth5184de02010-12-12 08:51:33 +00006565 case OO_New:
6566 case OO_Delete:
6567 case OO_Array_New:
6568 case OO_Array_Delete:
6569 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00006570 llvm_unreachable(
6571 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00006572
6573 case OO_Comma:
6574 case OO_Arrow:
6575 // C++ [over.match.oper]p3:
6576 // -- For the operator ',', the unary operator '&', or the
6577 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006578 break;
6579
6580 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006581 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006582 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006583 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006584
6585 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006586 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006587 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006588 } else {
6589 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6590 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6591 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006592 break;
6593
Chandler Carruth5184de02010-12-12 08:51:33 +00006594 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006595 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006596 OpBuilder.addUnaryStarPointerOverloads();
6597 else
6598 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6599 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006600
Chandler Carruth5184de02010-12-12 08:51:33 +00006601 case OO_Slash:
6602 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006603 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006604
6605 case OO_PlusPlus:
6606 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006607 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6608 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006609 break;
6610
Douglas Gregor84605ae2009-08-24 13:43:27 +00006611 case OO_EqualEqual:
6612 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006613 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006614 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006615
Douglas Gregora11693b2008-11-12 17:17:38 +00006616 case OO_Less:
6617 case OO_Greater:
6618 case OO_LessEqual:
6619 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006620 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006621 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6622 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006623
Douglas Gregora11693b2008-11-12 17:17:38 +00006624 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006625 case OO_Caret:
6626 case OO_Pipe:
6627 case OO_LessLess:
6628 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006629 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006630 break;
6631
Chandler Carruth5184de02010-12-12 08:51:33 +00006632 case OO_Amp: // '&' is either unary or binary
6633 if (NumArgs == 1)
6634 // C++ [over.match.oper]p3:
6635 // -- For the operator ',', the unary operator '&', or the
6636 // operator '->', the built-in candidates set is empty.
6637 break;
6638
6639 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6640 break;
6641
6642 case OO_Tilde:
6643 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6644 break;
6645
Douglas Gregora11693b2008-11-12 17:17:38 +00006646 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006647 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006648 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006649
6650 case OO_PlusEqual:
6651 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006652 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006653 // Fall through.
6654
6655 case OO_StarEqual:
6656 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006657 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006658 break;
6659
6660 case OO_PercentEqual:
6661 case OO_LessLessEqual:
6662 case OO_GreaterGreaterEqual:
6663 case OO_AmpEqual:
6664 case OO_CaretEqual:
6665 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006666 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006667 break;
6668
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006669 case OO_Exclaim:
6670 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006671 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006672
Douglas Gregora11693b2008-11-12 17:17:38 +00006673 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006674 case OO_PipePipe:
6675 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006676 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006677
6678 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006679 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006680 break;
6681
6682 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006683 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006684 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006685
6686 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006687 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006688 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6689 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006690 }
6691}
6692
Douglas Gregore254f902009-02-04 00:32:51 +00006693/// \brief Add function candidates found via argument-dependent lookup
6694/// to the set of overloading candidates.
6695///
6696/// This routine performs argument-dependent name lookup based on the
6697/// given function name (which may also be an operator name) and adds
6698/// all of the overload candidates found by ADL to the overload
6699/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006700void
Douglas Gregore254f902009-02-04 00:32:51 +00006701Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006702 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006703 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006704 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006705 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006706 bool PartialOverloading,
6707 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006708 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006709
John McCall91f61fc2010-01-26 06:04:06 +00006710 // FIXME: This approach for uniquing ADL results (and removing
6711 // redundant candidates from the set) relies on pointer-equality,
6712 // which means we need to key off the canonical decl. However,
6713 // always going back to the canonical decl might not get us the
6714 // right set of default arguments. What default arguments are
6715 // we supposed to consider on ADL candidates, anyway?
6716
Douglas Gregorcabea402009-09-22 15:41:20 +00006717 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006718 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6719 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006720
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006721 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006722 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6723 CandEnd = CandidateSet.end();
6724 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006725 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006726 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006727 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006728 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006729 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006730
6731 // For each of the ADL candidates we found, add it to the overload
6732 // set.
John McCall8fe68082010-01-26 07:16:45 +00006733 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006734 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006735 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006736 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006737 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006738
John McCalla0296f72010-03-19 07:35:19 +00006739 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006740 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006741 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006742 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006743 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006744 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006745 }
Douglas Gregore254f902009-02-04 00:32:51 +00006746}
6747
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006748/// isBetterOverloadCandidate - Determines whether the first overload
6749/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006750bool
John McCall5c32be02010-08-24 20:38:10 +00006751isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006752 const OverloadCandidate &Cand1,
6753 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006754 SourceLocation Loc,
6755 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006756 // Define viable functions to be better candidates than non-viable
6757 // functions.
6758 if (!Cand2.Viable)
6759 return Cand1.Viable;
6760 else if (!Cand1.Viable)
6761 return false;
6762
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006763 // C++ [over.match.best]p1:
6764 //
6765 // -- if F is a static member function, ICS1(F) is defined such
6766 // that ICS1(F) is neither better nor worse than ICS1(G) for
6767 // any function G, and, symmetrically, ICS1(G) is neither
6768 // better nor worse than ICS1(F).
6769 unsigned StartArg = 0;
6770 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6771 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006772
Douglas Gregord3cb3562009-07-07 23:38:56 +00006773 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006774 // A viable function F1 is defined to be a better function than another
6775 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006776 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006777 unsigned NumArgs = Cand1.Conversions.size();
6778 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6779 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006780 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006781 switch (CompareImplicitConversionSequences(S,
6782 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006783 Cand2.Conversions[ArgIdx])) {
6784 case ImplicitConversionSequence::Better:
6785 // Cand1 has a better conversion sequence.
6786 HasBetterConversion = true;
6787 break;
6788
6789 case ImplicitConversionSequence::Worse:
6790 // Cand1 can't be better than Cand2.
6791 return false;
6792
6793 case ImplicitConversionSequence::Indistinguishable:
6794 // Do nothing.
6795 break;
6796 }
6797 }
6798
Mike Stump11289f42009-09-09 15:08:12 +00006799 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006800 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006801 if (HasBetterConversion)
6802 return true;
6803
Mike Stump11289f42009-09-09 15:08:12 +00006804 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006805 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006806 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006807 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6808 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006809
6810 // -- F1 and F2 are function template specializations, and the function
6811 // template for F1 is more specialized than the template for F2
6812 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006813 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006814 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006815 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006816 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006817 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6818 Cand2.Function->getPrimaryTemplate(),
6819 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006820 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006821 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006822 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006823 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006824 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006825
Douglas Gregora1f013e2008-11-07 22:36:19 +00006826 // -- the context is an initialization by user-defined conversion
6827 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6828 // from the return type of F1 to the destination type (i.e.,
6829 // the type of the entity being initialized) is a better
6830 // conversion sequence than the standard conversion sequence
6831 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006832 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006833 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006834 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006835 switch (CompareStandardConversionSequences(S,
6836 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006837 Cand2.FinalConversion)) {
6838 case ImplicitConversionSequence::Better:
6839 // Cand1 has a better conversion sequence.
6840 return true;
6841
6842 case ImplicitConversionSequence::Worse:
6843 // Cand1 can't be better than Cand2.
6844 return false;
6845
6846 case ImplicitConversionSequence::Indistinguishable:
6847 // Do nothing
6848 break;
6849 }
6850 }
6851
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006852 return false;
6853}
6854
Mike Stump11289f42009-09-09 15:08:12 +00006855/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006856/// within an overload candidate set.
6857///
6858/// \param CandidateSet the set of candidate functions.
6859///
6860/// \param Loc the location of the function name (or operator symbol) for
6861/// which overload resolution occurs.
6862///
Mike Stump11289f42009-09-09 15:08:12 +00006863/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006864/// function, Best points to the candidate function found.
6865///
6866/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006867OverloadingResult
6868OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006869 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00006870 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006871 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006872 Best = end();
6873 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6874 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006875 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006876 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006877 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006878 }
6879
6880 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006881 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006882 return OR_No_Viable_Function;
6883
6884 // Make sure that this function is better than every other viable
6885 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006886 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006887 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006888 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006889 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006890 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006891 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006892 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006893 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006894 }
Mike Stump11289f42009-09-09 15:08:12 +00006895
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006896 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006897 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00006898 (Best->Function->isDeleted() ||
6899 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006900 return OR_Deleted;
6901
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006902 return OR_Success;
6903}
6904
John McCall53262c92010-01-12 02:15:36 +00006905namespace {
6906
6907enum OverloadCandidateKind {
6908 oc_function,
6909 oc_method,
6910 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006911 oc_function_template,
6912 oc_method_template,
6913 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006914 oc_implicit_default_constructor,
6915 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006916 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006917 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006918 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00006919 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006920};
6921
John McCalle1ac8d12010-01-13 00:25:19 +00006922OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6923 FunctionDecl *Fn,
6924 std::string &Description) {
6925 bool isTemplate = false;
6926
6927 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6928 isTemplate = true;
6929 Description = S.getTemplateArgumentBindingsText(
6930 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6931 }
John McCallfd0b2f82010-01-06 09:43:14 +00006932
6933 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006934 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006935 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006936
Sebastian Redl08905022011-02-05 19:23:19 +00006937 if (Ctor->getInheritedConstructor())
6938 return oc_implicit_inherited_constructor;
6939
Alexis Hunt119c10e2011-05-25 23:16:36 +00006940 if (Ctor->isDefaultConstructor())
6941 return oc_implicit_default_constructor;
6942
6943 if (Ctor->isMoveConstructor())
6944 return oc_implicit_move_constructor;
6945
6946 assert(Ctor->isCopyConstructor() &&
6947 "unexpected sort of implicit constructor");
6948 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006949 }
6950
6951 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6952 // This actually gets spelled 'candidate function' for now, but
6953 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006954 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006955 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006956
Alexis Hunt119c10e2011-05-25 23:16:36 +00006957 if (Meth->isMoveAssignmentOperator())
6958 return oc_implicit_move_assignment;
6959
Douglas Gregorec3bec02010-09-27 22:37:28 +00006960 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006961 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006962 return oc_implicit_copy_assignment;
6963 }
6964
John McCalle1ac8d12010-01-13 00:25:19 +00006965 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006966}
6967
Sebastian Redl08905022011-02-05 19:23:19 +00006968void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6969 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6970 if (!Ctor) return;
6971
6972 Ctor = Ctor->getInheritedConstructor();
6973 if (!Ctor) return;
6974
6975 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6976}
6977
John McCall53262c92010-01-12 02:15:36 +00006978} // end anonymous namespace
6979
6980// Notes the location of an overload candidate.
6981void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006982 std::string FnDesc;
6983 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6984 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6985 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00006986 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00006987}
6988
Douglas Gregorb491ed32011-02-19 21:32:49 +00006989//Notes the location of all overload candidates designated through
6990// OverloadedExpr
6991void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6992 assert(OverloadedExpr->getType() == Context.OverloadTy);
6993
6994 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6995 OverloadExpr *OvlExpr = Ovl.Expression;
6996
6997 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6998 IEnd = OvlExpr->decls_end();
6999 I != IEnd; ++I) {
7000 if (FunctionTemplateDecl *FunTmpl =
7001 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
7002 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
7003 } else if (FunctionDecl *Fun
7004 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
7005 NoteOverloadCandidate(Fun);
7006 }
7007 }
7008}
7009
John McCall0d1da222010-01-12 00:44:57 +00007010/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7011/// "lead" diagnostic; it will be given two arguments, the source and
7012/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00007013void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7014 Sema &S,
7015 SourceLocation CaretLoc,
7016 const PartialDiagnostic &PDiag) const {
7017 S.Diag(CaretLoc, PDiag)
7018 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00007019 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00007020 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7021 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00007022 }
John McCall12f97bc2010-01-08 04:41:39 +00007023}
7024
John McCall0d1da222010-01-12 00:44:57 +00007025namespace {
7026
John McCall6a61b522010-01-13 09:16:55 +00007027void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7028 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7029 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00007030 assert(Cand->Function && "for now, candidate must be a function");
7031 FunctionDecl *Fn = Cand->Function;
7032
7033 // There's a conversion slot for the object argument if this is a
7034 // non-constructor method. Note that 'I' corresponds the
7035 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00007036 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00007037 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00007038 if (I == 0)
7039 isObjectArgument = true;
7040 else
7041 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00007042 }
7043
John McCalle1ac8d12010-01-13 00:25:19 +00007044 std::string FnDesc;
7045 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7046
John McCall6a61b522010-01-13 09:16:55 +00007047 Expr *FromExpr = Conv.Bad.FromExpr;
7048 QualType FromTy = Conv.Bad.getFromType();
7049 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00007050
John McCallfb7ad0f2010-02-02 02:42:52 +00007051 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00007052 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00007053 Expr *E = FromExpr->IgnoreParens();
7054 if (isa<UnaryOperator>(E))
7055 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00007056 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00007057
7058 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7059 << (unsigned) FnKind << FnDesc
7060 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7061 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007062 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00007063 return;
7064 }
7065
John McCall6d174642010-01-23 08:10:49 +00007066 // Do some hand-waving analysis to see if the non-viability is due
7067 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00007068 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7069 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7070 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7071 CToTy = RT->getPointeeType();
7072 else {
7073 // TODO: detect and diagnose the full richness of const mismatches.
7074 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7075 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7076 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7077 }
7078
7079 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7080 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7081 // It is dumb that we have to do this here.
7082 while (isa<ArrayType>(CFromTy))
7083 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7084 while (isa<ArrayType>(CToTy))
7085 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7086
7087 Qualifiers FromQs = CFromTy.getQualifiers();
7088 Qualifiers ToQs = CToTy.getQualifiers();
7089
7090 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7091 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7092 << (unsigned) FnKind << FnDesc
7093 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7094 << FromTy
7095 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7096 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007097 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007098 return;
7099 }
7100
John McCall31168b02011-06-15 23:02:42 +00007101 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007102 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007103 << (unsigned) FnKind << FnDesc
7104 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7105 << FromTy
7106 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7107 << (unsigned) isObjectArgument << I+1;
7108 MaybeEmitInheritedConstructorNote(S, Fn);
7109 return;
7110 }
7111
Douglas Gregoraec25842011-04-26 23:16:46 +00007112 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7113 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7114 << (unsigned) FnKind << FnDesc
7115 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7116 << FromTy
7117 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7118 << (unsigned) isObjectArgument << I+1;
7119 MaybeEmitInheritedConstructorNote(S, Fn);
7120 return;
7121 }
7122
John McCall47000992010-01-14 03:28:57 +00007123 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7124 assert(CVR && "unexpected qualifiers mismatch");
7125
7126 if (isObjectArgument) {
7127 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7128 << (unsigned) FnKind << FnDesc
7129 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7130 << FromTy << (CVR - 1);
7131 } else {
7132 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7133 << (unsigned) FnKind << FnDesc
7134 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7135 << FromTy << (CVR - 1) << I+1;
7136 }
Sebastian Redl08905022011-02-05 19:23:19 +00007137 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007138 return;
7139 }
7140
Sebastian Redla72462c2011-09-24 17:48:32 +00007141 // Special diagnostic for failure to convert an initializer list, since
7142 // telling the user that it has type void is not useful.
7143 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7144 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7145 << (unsigned) FnKind << FnDesc
7146 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7147 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7148 MaybeEmitInheritedConstructorNote(S, Fn);
7149 return;
7150 }
7151
John McCall6d174642010-01-23 08:10:49 +00007152 // Diagnose references or pointers to incomplete types differently,
7153 // since it's far from impossible that the incompleteness triggered
7154 // the failure.
7155 QualType TempFromTy = FromTy.getNonReferenceType();
7156 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7157 TempFromTy = PTy->getPointeeType();
7158 if (TempFromTy->isIncompleteType()) {
7159 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7160 << (unsigned) FnKind << FnDesc
7161 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7162 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007163 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007164 return;
7165 }
7166
Douglas Gregor56f2e342010-06-30 23:01:39 +00007167 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007168 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007169 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7170 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7171 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7172 FromPtrTy->getPointeeType()) &&
7173 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7174 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007175 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007176 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007177 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007178 }
7179 } else if (const ObjCObjectPointerType *FromPtrTy
7180 = FromTy->getAs<ObjCObjectPointerType>()) {
7181 if (const ObjCObjectPointerType *ToPtrTy
7182 = ToTy->getAs<ObjCObjectPointerType>())
7183 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7184 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7185 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7186 FromPtrTy->getPointeeType()) &&
7187 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007188 BaseToDerivedConversion = 2;
7189 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7190 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7191 !FromTy->isIncompleteType() &&
7192 !ToRefTy->getPointeeType()->isIncompleteType() &&
7193 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7194 BaseToDerivedConversion = 3;
7195 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007196
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007197 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007198 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007199 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007200 << (unsigned) FnKind << FnDesc
7201 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007202 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007203 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007204 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007205 return;
7206 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007207
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007208 if (isa<ObjCObjectPointerType>(CFromTy) &&
7209 isa<PointerType>(CToTy)) {
7210 Qualifiers FromQs = CFromTy.getQualifiers();
7211 Qualifiers ToQs = CToTy.getQualifiers();
7212 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7213 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7214 << (unsigned) FnKind << FnDesc
7215 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7216 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7217 MaybeEmitInheritedConstructorNote(S, Fn);
7218 return;
7219 }
7220 }
7221
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007222 // Emit the generic diagnostic and, optionally, add the hints to it.
7223 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7224 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007225 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007226 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7227 << (unsigned) (Cand->Fix.Kind);
7228
7229 // If we can fix the conversion, suggest the FixIts.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007230 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007231 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7232 HI != HE; ++HI)
7233 FDiag << *HI;
7234 S.Diag(Fn->getLocation(), FDiag);
7235
Sebastian Redl08905022011-02-05 19:23:19 +00007236 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007237}
7238
7239void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7240 unsigned NumFormalArgs) {
7241 // TODO: treat calls to a missing default constructor as a special case
7242
7243 FunctionDecl *Fn = Cand->Function;
7244 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7245
7246 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007247
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00007248 // With invalid overloaded operators, it's possible that we think we
7249 // have an arity mismatch when it fact it looks like we have the
7250 // right number of arguments, because only overloaded operators have
7251 // the weird behavior of overloading member and non-member functions.
7252 // Just don't report anything.
7253 if (Fn->isInvalidDecl() &&
7254 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7255 return;
7256
John McCall6a61b522010-01-13 09:16:55 +00007257 // at least / at most / exactly
7258 unsigned mode, modeCount;
7259 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007260 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7261 (Cand->FailureKind == ovl_fail_bad_deduction &&
7262 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007263 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00007264 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00007265 mode = 0; // "at least"
7266 else
7267 mode = 2; // "exactly"
7268 modeCount = MinParams;
7269 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007270 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7271 (Cand->FailureKind == ovl_fail_bad_deduction &&
7272 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00007273 if (MinParams != FnTy->getNumArgs())
7274 mode = 1; // "at most"
7275 else
7276 mode = 2; // "exactly"
7277 modeCount = FnTy->getNumArgs();
7278 }
7279
7280 std::string Description;
7281 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7282
7283 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007284 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00007285 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00007286 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007287}
7288
John McCall8b9ed552010-02-01 18:53:26 +00007289/// Diagnose a failed template-argument deduction.
7290void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7291 Expr **Args, unsigned NumArgs) {
7292 FunctionDecl *Fn = Cand->Function; // pattern
7293
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007294 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007295 NamedDecl *ParamD;
7296 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7297 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7298 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007299 switch (Cand->DeductionFailure.Result) {
7300 case Sema::TDK_Success:
7301 llvm_unreachable("TDK_success while diagnosing bad deduction");
7302
7303 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007304 assert(ParamD && "no parameter found for incomplete deduction result");
7305 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7306 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007307 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007308 return;
7309 }
7310
John McCall42d7d192010-08-05 09:05:08 +00007311 case Sema::TDK_Underqualified: {
7312 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7313 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7314
7315 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7316
7317 // Param will have been canonicalized, but it should just be a
7318 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007319 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007320 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007321 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007322 assert(S.Context.hasSameType(Param, NonCanonParam));
7323
7324 // Arg has also been canonicalized, but there's nothing we can do
7325 // about that. It also doesn't matter as much, because it won't
7326 // have any template parameters in it (because deduction isn't
7327 // done on dependent types).
7328 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7329
7330 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7331 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007332 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007333 return;
7334 }
7335
7336 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007337 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007338 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007339 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007340 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007341 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007342 which = 1;
7343 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007344 which = 2;
7345 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007346
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007347 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007348 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007349 << *Cand->DeductionFailure.getFirstArg()
7350 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007351 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007352 return;
7353 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007354
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007355 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007356 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007357 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007358 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007359 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7360 << ParamD->getDeclName();
7361 else {
7362 int index = 0;
7363 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7364 index = TTP->getIndex();
7365 else if (NonTypeTemplateParmDecl *NTTP
7366 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7367 index = NTTP->getIndex();
7368 else
7369 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007370 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007371 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7372 << (index + 1);
7373 }
Sebastian Redl08905022011-02-05 19:23:19 +00007374 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007375 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007376
Douglas Gregor02eb4832010-05-08 18:13:28 +00007377 case Sema::TDK_TooManyArguments:
7378 case Sema::TDK_TooFewArguments:
7379 DiagnoseArityMismatch(S, Cand, NumArgs);
7380 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007381
7382 case Sema::TDK_InstantiationDepth:
7383 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007384 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007385 return;
7386
7387 case Sema::TDK_SubstitutionFailure: {
7388 std::string ArgString;
7389 if (TemplateArgumentList *Args
7390 = Cand->DeductionFailure.getTemplateArgumentList())
7391 ArgString = S.getTemplateArgumentBindingsText(
7392 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7393 *Args);
7394 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7395 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007396 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007397 return;
7398 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007399
John McCall8b9ed552010-02-01 18:53:26 +00007400 // TODO: diagnose these individually, then kill off
7401 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007402 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007403 case Sema::TDK_FailedOverloadResolution:
7404 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007405 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007406 return;
7407 }
7408}
7409
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007410/// CUDA: diagnose an invalid call across targets.
7411void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7412 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7413 FunctionDecl *Callee = Cand->Function;
7414
7415 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7416 CalleeTarget = S.IdentifyCUDATarget(Callee);
7417
7418 std::string FnDesc;
7419 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7420
7421 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7422 << (unsigned) FnKind << CalleeTarget << CallerTarget;
7423}
7424
John McCall8b9ed552010-02-01 18:53:26 +00007425/// Generates a 'note' diagnostic for an overload candidate. We've
7426/// already generated a primary error at the call site.
7427///
7428/// It really does need to be a single diagnostic with its caret
7429/// pointed at the candidate declaration. Yes, this creates some
7430/// major challenges of technical writing. Yes, this makes pointing
7431/// out problems with specific arguments quite awkward. It's still
7432/// better than generating twenty screens of text for every failed
7433/// overload.
7434///
7435/// It would be great to be able to express per-candidate problems
7436/// more richly for those diagnostic clients that cared, but we'd
7437/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007438void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7439 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007440 FunctionDecl *Fn = Cand->Function;
7441
John McCall12f97bc2010-01-08 04:41:39 +00007442 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007443 if (Cand->Viable && (Fn->isDeleted() ||
7444 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007445 std::string FnDesc;
7446 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007447
7448 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007449 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007450 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007451 return;
John McCall12f97bc2010-01-08 04:41:39 +00007452 }
7453
John McCalle1ac8d12010-01-13 00:25:19 +00007454 // We don't really have anything else to say about viable candidates.
7455 if (Cand->Viable) {
7456 S.NoteOverloadCandidate(Fn);
7457 return;
7458 }
John McCall0d1da222010-01-12 00:44:57 +00007459
John McCall6a61b522010-01-13 09:16:55 +00007460 switch (Cand->FailureKind) {
7461 case ovl_fail_too_many_arguments:
7462 case ovl_fail_too_few_arguments:
7463 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007464
John McCall6a61b522010-01-13 09:16:55 +00007465 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007466 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7467
John McCallfe796dd2010-01-23 05:17:32 +00007468 case ovl_fail_trivial_conversion:
7469 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007470 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007471 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007472
John McCall65eb8792010-02-25 01:37:24 +00007473 case ovl_fail_bad_conversion: {
7474 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7475 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007476 if (Cand->Conversions[I].isBad())
7477 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007478
John McCall6a61b522010-01-13 09:16:55 +00007479 // FIXME: this currently happens when we're called from SemaInit
7480 // when user-conversion overload fails. Figure out how to handle
7481 // those conditions and diagnose them well.
7482 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007483 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007484
7485 case ovl_fail_bad_target:
7486 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00007487 }
John McCalld3224162010-01-08 00:58:21 +00007488}
7489
7490void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7491 // Desugar the type of the surrogate down to a function type,
7492 // retaining as many typedefs as possible while still showing
7493 // the function type (and, therefore, its parameter types).
7494 QualType FnType = Cand->Surrogate->getConversionType();
7495 bool isLValueReference = false;
7496 bool isRValueReference = false;
7497 bool isPointer = false;
7498 if (const LValueReferenceType *FnTypeRef =
7499 FnType->getAs<LValueReferenceType>()) {
7500 FnType = FnTypeRef->getPointeeType();
7501 isLValueReference = true;
7502 } else if (const RValueReferenceType *FnTypeRef =
7503 FnType->getAs<RValueReferenceType>()) {
7504 FnType = FnTypeRef->getPointeeType();
7505 isRValueReference = true;
7506 }
7507 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7508 FnType = FnTypePtr->getPointeeType();
7509 isPointer = true;
7510 }
7511 // Desugar down to a function type.
7512 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7513 // Reconstruct the pointer/reference as appropriate.
7514 if (isPointer) FnType = S.Context.getPointerType(FnType);
7515 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7516 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7517
7518 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7519 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007520 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007521}
7522
7523void NoteBuiltinOperatorCandidate(Sema &S,
7524 const char *Opc,
7525 SourceLocation OpLoc,
7526 OverloadCandidate *Cand) {
7527 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7528 std::string TypeStr("operator");
7529 TypeStr += Opc;
7530 TypeStr += "(";
7531 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7532 if (Cand->Conversions.size() == 1) {
7533 TypeStr += ")";
7534 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7535 } else {
7536 TypeStr += ", ";
7537 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7538 TypeStr += ")";
7539 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7540 }
7541}
7542
7543void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7544 OverloadCandidate *Cand) {
7545 unsigned NoOperands = Cand->Conversions.size();
7546 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7547 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007548 if (ICS.isBad()) break; // all meaningless after first invalid
7549 if (!ICS.isAmbiguous()) continue;
7550
John McCall5c32be02010-08-24 20:38:10 +00007551 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007552 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007553 }
7554}
7555
John McCall3712d9e2010-01-15 23:32:50 +00007556SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7557 if (Cand->Function)
7558 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007559 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007560 return Cand->Surrogate->getLocation();
7561 return SourceLocation();
7562}
7563
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007564static unsigned
7565RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00007566 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007567 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00007568 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007569
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007570 case Sema::TDK_Incomplete:
7571 return 1;
7572
7573 case Sema::TDK_Underqualified:
7574 case Sema::TDK_Inconsistent:
7575 return 2;
7576
7577 case Sema::TDK_SubstitutionFailure:
7578 case Sema::TDK_NonDeducedMismatch:
7579 return 3;
7580
7581 case Sema::TDK_InstantiationDepth:
7582 case Sema::TDK_FailedOverloadResolution:
7583 return 4;
7584
7585 case Sema::TDK_InvalidExplicitArguments:
7586 return 5;
7587
7588 case Sema::TDK_TooManyArguments:
7589 case Sema::TDK_TooFewArguments:
7590 return 6;
7591 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007592 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007593}
7594
John McCallad2587a2010-01-12 00:48:53 +00007595struct CompareOverloadCandidatesForDisplay {
7596 Sema &S;
7597 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007598
7599 bool operator()(const OverloadCandidate *L,
7600 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007601 // Fast-path this check.
7602 if (L == R) return false;
7603
John McCall12f97bc2010-01-08 04:41:39 +00007604 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007605 if (L->Viable) {
7606 if (!R->Viable) return true;
7607
7608 // TODO: introduce a tri-valued comparison for overload
7609 // candidates. Would be more worthwhile if we had a sort
7610 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007611 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7612 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007613 } else if (R->Viable)
7614 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007615
John McCall3712d9e2010-01-15 23:32:50 +00007616 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007617
John McCall3712d9e2010-01-15 23:32:50 +00007618 // Criteria by which we can sort non-viable candidates:
7619 if (!L->Viable) {
7620 // 1. Arity mismatches come after other candidates.
7621 if (L->FailureKind == ovl_fail_too_many_arguments ||
7622 L->FailureKind == ovl_fail_too_few_arguments)
7623 return false;
7624 if (R->FailureKind == ovl_fail_too_many_arguments ||
7625 R->FailureKind == ovl_fail_too_few_arguments)
7626 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007627
John McCallfe796dd2010-01-23 05:17:32 +00007628 // 2. Bad conversions come first and are ordered by the number
7629 // of bad conversions and quality of good conversions.
7630 if (L->FailureKind == ovl_fail_bad_conversion) {
7631 if (R->FailureKind != ovl_fail_bad_conversion)
7632 return true;
7633
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007634 // The conversion that can be fixed with a smaller number of changes,
7635 // comes first.
7636 unsigned numLFixes = L->Fix.NumConversionsFixed;
7637 unsigned numRFixes = R->Fix.NumConversionsFixed;
7638 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7639 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007640 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007641 if (numLFixes < numRFixes)
7642 return true;
7643 else
7644 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007645 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007646
John McCallfe796dd2010-01-23 05:17:32 +00007647 // If there's any ordering between the defined conversions...
7648 // FIXME: this might not be transitive.
7649 assert(L->Conversions.size() == R->Conversions.size());
7650
7651 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007652 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7653 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007654 switch (CompareImplicitConversionSequences(S,
7655 L->Conversions[I],
7656 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007657 case ImplicitConversionSequence::Better:
7658 leftBetter++;
7659 break;
7660
7661 case ImplicitConversionSequence::Worse:
7662 leftBetter--;
7663 break;
7664
7665 case ImplicitConversionSequence::Indistinguishable:
7666 break;
7667 }
7668 }
7669 if (leftBetter > 0) return true;
7670 if (leftBetter < 0) return false;
7671
7672 } else if (R->FailureKind == ovl_fail_bad_conversion)
7673 return false;
7674
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007675 if (L->FailureKind == ovl_fail_bad_deduction) {
7676 if (R->FailureKind != ovl_fail_bad_deduction)
7677 return true;
7678
7679 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7680 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00007681 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00007682 } else if (R->FailureKind == ovl_fail_bad_deduction)
7683 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007684
John McCall3712d9e2010-01-15 23:32:50 +00007685 // TODO: others?
7686 }
7687
7688 // Sort everything else by location.
7689 SourceLocation LLoc = GetLocationForCandidate(L);
7690 SourceLocation RLoc = GetLocationForCandidate(R);
7691
7692 // Put candidates without locations (e.g. builtins) at the end.
7693 if (LLoc.isInvalid()) return false;
7694 if (RLoc.isInvalid()) return true;
7695
7696 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007697 }
7698};
7699
John McCallfe796dd2010-01-23 05:17:32 +00007700/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007701/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00007702void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7703 Expr **Args, unsigned NumArgs) {
7704 assert(!Cand->Viable);
7705
7706 // Don't do anything on failures other than bad conversion.
7707 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7708
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007709 // We only want the FixIts if all the arguments can be corrected.
7710 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00007711 // Use a implicit copy initialization to check conversion fixes.
7712 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007713
John McCallfe796dd2010-01-23 05:17:32 +00007714 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007715 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007716 unsigned ConvCount = Cand->Conversions.size();
7717 while (true) {
7718 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7719 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007720 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00007721 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00007722 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007723 }
John McCallfe796dd2010-01-23 05:17:32 +00007724 }
7725
7726 if (ConvIdx == ConvCount)
7727 return;
7728
John McCall65eb8792010-02-25 01:37:24 +00007729 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7730 "remaining conversion is initialized?");
7731
Douglas Gregoradc7a702010-04-16 17:45:54 +00007732 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007733 // operation somehow.
7734 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007735
7736 const FunctionProtoType* Proto;
7737 unsigned ArgIdx = ConvIdx;
7738
7739 if (Cand->IsSurrogate) {
7740 QualType ConvType
7741 = Cand->Surrogate->getConversionType().getNonReferenceType();
7742 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7743 ConvType = ConvPtrType->getPointeeType();
7744 Proto = ConvType->getAs<FunctionProtoType>();
7745 ArgIdx--;
7746 } else if (Cand->Function) {
7747 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7748 if (isa<CXXMethodDecl>(Cand->Function) &&
7749 !isa<CXXConstructorDecl>(Cand->Function))
7750 ArgIdx--;
7751 } else {
7752 // Builtin binary operator with a bad first conversion.
7753 assert(ConvCount <= 3);
7754 for (; ConvIdx != ConvCount; ++ConvIdx)
7755 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007756 = TryCopyInitialization(S, Args[ConvIdx],
7757 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007758 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007759 /*InOverloadResolution*/ true,
7760 /*AllowObjCWritebackConversion=*/
7761 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00007762 return;
7763 }
7764
7765 // Fill in the rest of the conversions.
7766 unsigned NumArgsInProto = Proto->getNumArgs();
7767 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007768 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00007769 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007770 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007771 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007772 /*InOverloadResolution=*/true,
7773 /*AllowObjCWritebackConversion=*/
7774 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007775 // Store the FixIt in the candidate if it exists.
7776 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00007777 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007778 }
John McCallfe796dd2010-01-23 05:17:32 +00007779 else
7780 Cand->Conversions[ConvIdx].setEllipsis();
7781 }
7782}
7783
John McCalld3224162010-01-08 00:58:21 +00007784} // end anonymous namespace
7785
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007786/// PrintOverloadCandidates - When overload resolution fails, prints
7787/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007788/// set.
John McCall5c32be02010-08-24 20:38:10 +00007789void OverloadCandidateSet::NoteCandidates(Sema &S,
7790 OverloadCandidateDisplayKind OCD,
7791 Expr **Args, unsigned NumArgs,
7792 const char *Opc,
7793 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007794 // Sort the candidates by viability and position. Sorting directly would
7795 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007796 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007797 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7798 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007799 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007800 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007801 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007802 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007803 if (Cand->Function || Cand->IsSurrogate)
7804 Cands.push_back(Cand);
7805 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7806 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007807 }
7808 }
7809
John McCallad2587a2010-01-12 00:48:53 +00007810 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007811 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007812
John McCall0d1da222010-01-12 00:44:57 +00007813 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007814
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007815 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00007816 const DiagnosticsEngine::OverloadsShown ShowOverloads =
7817 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007818 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007819 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7820 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007821
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007822 // Set an arbitrary limit on the number of candidate functions we'll spam
7823 // the user with. FIXME: This limit should depend on details of the
7824 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00007825 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007826 break;
7827 }
7828 ++CandsShown;
7829
John McCalld3224162010-01-08 00:58:21 +00007830 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007831 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007832 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007833 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007834 else {
7835 assert(Cand->Viable &&
7836 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007837 // Generally we only see ambiguities including viable builtin
7838 // operators if overload resolution got screwed up by an
7839 // ambiguous user-defined conversion.
7840 //
7841 // FIXME: It's quite possible for different conversions to see
7842 // different ambiguities, though.
7843 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007844 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007845 ReportedAmbiguousConversions = true;
7846 }
John McCalld3224162010-01-08 00:58:21 +00007847
John McCall0d1da222010-01-12 00:44:57 +00007848 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007849 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007850 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007851 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007852
7853 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007854 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007855}
7856
Douglas Gregorb491ed32011-02-19 21:32:49 +00007857// [PossiblyAFunctionType] --> [Return]
7858// NonFunctionType --> NonFunctionType
7859// R (A) --> R(A)
7860// R (*)(A) --> R (A)
7861// R (&)(A) --> R (A)
7862// R (S::*)(A) --> R (A)
7863QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7864 QualType Ret = PossiblyAFunctionType;
7865 if (const PointerType *ToTypePtr =
7866 PossiblyAFunctionType->getAs<PointerType>())
7867 Ret = ToTypePtr->getPointeeType();
7868 else if (const ReferenceType *ToTypeRef =
7869 PossiblyAFunctionType->getAs<ReferenceType>())
7870 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007871 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007872 PossiblyAFunctionType->getAs<MemberPointerType>())
7873 Ret = MemTypePtr->getPointeeType();
7874 Ret =
7875 Context.getCanonicalType(Ret).getUnqualifiedType();
7876 return Ret;
7877}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007878
Douglas Gregorb491ed32011-02-19 21:32:49 +00007879// A helper class to help with address of function resolution
7880// - allows us to avoid passing around all those ugly parameters
7881class AddressOfFunctionResolver
7882{
7883 Sema& S;
7884 Expr* SourceExpr;
7885 const QualType& TargetType;
7886 QualType TargetFunctionType; // Extracted function type from target type
7887
7888 bool Complain;
7889 //DeclAccessPair& ResultFunctionAccessPair;
7890 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007891
Douglas Gregorb491ed32011-02-19 21:32:49 +00007892 bool TargetTypeIsNonStaticMemberFunction;
7893 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007894
Douglas Gregorb491ed32011-02-19 21:32:49 +00007895 OverloadExpr::FindResult OvlExprInfo;
7896 OverloadExpr *OvlExpr;
7897 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007898 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007899
Douglas Gregorb491ed32011-02-19 21:32:49 +00007900public:
7901 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7902 const QualType& TargetType, bool Complain)
7903 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7904 Complain(Complain), Context(S.getASTContext()),
7905 TargetTypeIsNonStaticMemberFunction(
7906 !!TargetType->getAs<MemberPointerType>()),
7907 FoundNonTemplateFunction(false),
7908 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7909 OvlExpr(OvlExprInfo.Expression)
7910 {
7911 ExtractUnqualifiedFunctionTypeFromTargetType();
7912
7913 if (!TargetFunctionType->isFunctionType()) {
7914 if (OvlExpr->hasExplicitTemplateArgs()) {
7915 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00007916 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00007917 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00007918
7919 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7920 if (!Method->isStatic()) {
7921 // If the target type is a non-function type and the function
7922 // found is a non-static member function, pretend as if that was
7923 // the target, it's the only possible type to end up with.
7924 TargetTypeIsNonStaticMemberFunction = true;
7925
7926 // And skip adding the function if its not in the proper form.
7927 // We'll diagnose this due to an empty set of functions.
7928 if (!OvlExprInfo.HasFormOfMemberPointer)
7929 return;
7930 }
7931 }
7932
Douglas Gregorb491ed32011-02-19 21:32:49 +00007933 Matches.push_back(std::make_pair(dap,Fn));
7934 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007935 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007936 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007937 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007938
7939 if (OvlExpr->hasExplicitTemplateArgs())
7940 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007941
Douglas Gregorb491ed32011-02-19 21:32:49 +00007942 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7943 // C++ [over.over]p4:
7944 // If more than one function is selected, [...]
7945 if (Matches.size() > 1) {
7946 if (FoundNonTemplateFunction)
7947 EliminateAllTemplateMatches();
7948 else
7949 EliminateAllExceptMostSpecializedTemplate();
7950 }
7951 }
7952 }
7953
7954private:
7955 bool isTargetTypeAFunction() const {
7956 return TargetFunctionType->isFunctionType();
7957 }
7958
7959 // [ToType] [Return]
7960
7961 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7962 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7963 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7964 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7965 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7966 }
7967
7968 // return true if any matching specializations were found
7969 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7970 const DeclAccessPair& CurAccessFunPair) {
7971 if (CXXMethodDecl *Method
7972 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7973 // Skip non-static function templates when converting to pointer, and
7974 // static when converting to member pointer.
7975 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7976 return false;
7977 }
7978 else if (TargetTypeIsNonStaticMemberFunction)
7979 return false;
7980
7981 // C++ [over.over]p2:
7982 // If the name is a function template, template argument deduction is
7983 // done (14.8.2.2), and if the argument deduction succeeds, the
7984 // resulting template argument list is used to generate a single
7985 // function template specialization, which is added to the set of
7986 // overloaded functions considered.
7987 FunctionDecl *Specialization = 0;
7988 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7989 if (Sema::TemplateDeductionResult Result
7990 = S.DeduceTemplateArguments(FunctionTemplate,
7991 &OvlExplicitTemplateArgs,
7992 TargetFunctionType, Specialization,
7993 Info)) {
7994 // FIXME: make a note of the failed deduction for diagnostics.
7995 (void)Result;
7996 return false;
7997 }
7998
7999 // Template argument deduction ensures that we have an exact match.
8000 // This function template specicalization works.
8001 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8002 assert(TargetFunctionType
8003 == Context.getCanonicalType(Specialization->getType()));
8004 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8005 return true;
8006 }
8007
8008 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8009 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008010 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00008011 // Skip non-static functions when converting to pointer, and static
8012 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008013 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8014 return false;
8015 }
8016 else if (TargetTypeIsNonStaticMemberFunction)
8017 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008018
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00008019 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00008020 if (S.getLangOptions().CUDA)
8021 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8022 if (S.CheckCUDATarget(Caller, FunDecl))
8023 return false;
8024
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00008025 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008026 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8027 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00008028 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8029 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008030 Matches.push_back(std::make_pair(CurAccessFunPair,
8031 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008032 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00008033 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00008034 }
Mike Stump11289f42009-09-09 15:08:12 +00008035 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008036
8037 return false;
8038 }
8039
8040 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8041 bool Ret = false;
8042
8043 // If the overload expression doesn't have the form of a pointer to
8044 // member, don't try to convert it to a pointer-to-member type.
8045 if (IsInvalidFormOfPointerToMemberFunction())
8046 return false;
8047
8048 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8049 E = OvlExpr->decls_end();
8050 I != E; ++I) {
8051 // Look through any using declarations to find the underlying function.
8052 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8053
8054 // C++ [over.over]p3:
8055 // Non-member functions and static member functions match
8056 // targets of type "pointer-to-function" or "reference-to-function."
8057 // Nonstatic member functions match targets of
8058 // type "pointer-to-member-function."
8059 // Note that according to DR 247, the containing class does not matter.
8060 if (FunctionTemplateDecl *FunctionTemplate
8061 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8062 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8063 Ret = true;
8064 }
8065 // If we have explicit template arguments supplied, skip non-templates.
8066 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8067 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8068 Ret = true;
8069 }
8070 assert(Ret || Matches.empty());
8071 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008072 }
8073
Douglas Gregorb491ed32011-02-19 21:32:49 +00008074 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00008075 // [...] and any given function template specialization F1 is
8076 // eliminated if the set contains a second function template
8077 // specialization whose function template is more specialized
8078 // than the function template of F1 according to the partial
8079 // ordering rules of 14.5.5.2.
8080
8081 // The algorithm specified above is quadratic. We instead use a
8082 // two-pass algorithm (similar to the one used to identify the
8083 // best viable function in an overload set) that identifies the
8084 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008085
8086 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8087 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8088 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008089
John McCall58cc69d2010-01-27 01:50:18 +00008090 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008091 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8092 TPOC_Other, 0, SourceExpr->getLocStart(),
8093 S.PDiag(),
8094 S.PDiag(diag::err_addr_ovl_ambiguous)
8095 << Matches[0].second->getDeclName(),
8096 S.PDiag(diag::note_ovl_candidate)
8097 << (unsigned) oc_function_template,
8098 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008099
Douglas Gregorb491ed32011-02-19 21:32:49 +00008100 if (Result != MatchesCopy.end()) {
8101 // Make it the first and only element
8102 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8103 Matches[0].second = cast<FunctionDecl>(*Result);
8104 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008105 }
8106 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008107
Douglas Gregorb491ed32011-02-19 21:32:49 +00008108 void EliminateAllTemplateMatches() {
8109 // [...] any function template specializations in the set are
8110 // eliminated if the set also contains a non-template function, [...]
8111 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8112 if (Matches[I].second->getPrimaryTemplate() == 0)
8113 ++I;
8114 else {
8115 Matches[I] = Matches[--N];
8116 Matches.set_size(N);
8117 }
8118 }
8119 }
8120
8121public:
8122 void ComplainNoMatchesFound() const {
8123 assert(Matches.empty());
8124 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8125 << OvlExpr->getName() << TargetFunctionType
8126 << OvlExpr->getSourceRange();
8127 S.NoteAllOverloadCandidates(OvlExpr);
8128 }
8129
8130 bool IsInvalidFormOfPointerToMemberFunction() const {
8131 return TargetTypeIsNonStaticMemberFunction &&
8132 !OvlExprInfo.HasFormOfMemberPointer;
8133 }
8134
8135 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8136 // TODO: Should we condition this on whether any functions might
8137 // have matched, or is it more appropriate to do that in callers?
8138 // TODO: a fixit wouldn't hurt.
8139 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8140 << TargetType << OvlExpr->getSourceRange();
8141 }
8142
8143 void ComplainOfInvalidConversion() const {
8144 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8145 << OvlExpr->getName() << TargetType;
8146 }
8147
8148 void ComplainMultipleMatchesFound() const {
8149 assert(Matches.size() > 1);
8150 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8151 << OvlExpr->getName()
8152 << OvlExpr->getSourceRange();
8153 S.NoteAllOverloadCandidates(OvlExpr);
8154 }
8155
8156 int getNumMatches() const { return Matches.size(); }
8157
8158 FunctionDecl* getMatchingFunctionDecl() const {
8159 if (Matches.size() != 1) return 0;
8160 return Matches[0].second;
8161 }
8162
8163 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8164 if (Matches.size() != 1) return 0;
8165 return &Matches[0].first;
8166 }
8167};
8168
8169/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8170/// an overloaded function (C++ [over.over]), where @p From is an
8171/// expression with overloaded function type and @p ToType is the type
8172/// we're trying to resolve to. For example:
8173///
8174/// @code
8175/// int f(double);
8176/// int f(int);
8177///
8178/// int (*pfd)(double) = f; // selects f(double)
8179/// @endcode
8180///
8181/// This routine returns the resulting FunctionDecl if it could be
8182/// resolved, and NULL otherwise. When @p Complain is true, this
8183/// routine will emit diagnostics if there is an error.
8184FunctionDecl *
8185Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
8186 bool Complain,
8187 DeclAccessPair &FoundResult) {
8188
8189 assert(AddressOfExpr->getType() == Context.OverloadTy);
8190
8191 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
8192 int NumMatches = Resolver.getNumMatches();
8193 FunctionDecl* Fn = 0;
8194 if ( NumMatches == 0 && Complain) {
8195 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8196 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8197 else
8198 Resolver.ComplainNoMatchesFound();
8199 }
8200 else if (NumMatches > 1 && Complain)
8201 Resolver.ComplainMultipleMatchesFound();
8202 else if (NumMatches == 1) {
8203 Fn = Resolver.getMatchingFunctionDecl();
8204 assert(Fn);
8205 FoundResult = *Resolver.getMatchingFunctionAccessPair();
8206 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00008207 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00008208 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00008209 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008210
8211 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008212}
8213
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008214/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008215/// resolve that overloaded function expression down to a single function.
8216///
8217/// This routine can only resolve template-ids that refer to a single function
8218/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008219/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008220/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00008221FunctionDecl *
8222Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8223 bool Complain,
8224 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008225 // C++ [over.over]p1:
8226 // [...] [Note: any redundant set of parentheses surrounding the
8227 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008228 // C++ [over.over]p1:
8229 // [...] The overloaded function name can be preceded by the &
8230 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008231
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008232 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00008233 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008234 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00008235
8236 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00008237 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008238
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008239 // Look through all of the overloaded functions, searching for one
8240 // whose type matches exactly.
8241 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008242 for (UnresolvedSetIterator I = ovl->decls_begin(),
8243 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008244 // C++0x [temp.arg.explicit]p3:
8245 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008246 // where deduction is not done, if a template argument list is
8247 // specified and it, along with any default template arguments,
8248 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008249 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00008250 FunctionTemplateDecl *FunctionTemplate
8251 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008252
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008253 // C++ [over.over]p2:
8254 // If the name is a function template, template argument deduction is
8255 // done (14.8.2.2), and if the argument deduction succeeds, the
8256 // resulting template argument list is used to generate a single
8257 // function template specialization, which is added to the set of
8258 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008259 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008260 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008261 if (TemplateDeductionResult Result
8262 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8263 Specialization, Info)) {
8264 // FIXME: make a note of the failed deduction for diagnostics.
8265 (void)Result;
8266 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008267 }
8268
John McCall0009fcc2011-04-26 20:42:42 +00008269 assert(Specialization && "no specialization and no error?");
8270
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008271 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008272 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008273 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00008274 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8275 << ovl->getName();
8276 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008277 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008278 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00008279 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008280
John McCall0009fcc2011-04-26 20:42:42 +00008281 Matched = Specialization;
8282 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008283 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008284
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008285 return Matched;
8286}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008287
Douglas Gregor1beec452011-03-12 01:48:56 +00008288
8289
8290
John McCall50a2c2c2011-10-11 23:14:30 +00008291// Resolve and fix an overloaded expression that can be resolved
8292// because it identifies a single function template specialization.
8293//
Douglas Gregor1beec452011-03-12 01:48:56 +00008294// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00008295//
8296// Return true if it was logically possible to so resolve the
8297// expression, regardless of whether or not it succeeded. Always
8298// returns true if 'complain' is set.
8299bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8300 ExprResult &SrcExpr, bool doFunctionPointerConverion,
8301 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00008302 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00008303 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00008304 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00008305
John McCall50a2c2c2011-10-11 23:14:30 +00008306 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00008307
John McCall0009fcc2011-04-26 20:42:42 +00008308 DeclAccessPair found;
8309 ExprResult SingleFunctionExpression;
8310 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8311 ovl.Expression, /*complain*/ false, &found)) {
John McCall50a2c2c2011-10-11 23:14:30 +00008312 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8313 SrcExpr = ExprError();
8314 return true;
8315 }
John McCall0009fcc2011-04-26 20:42:42 +00008316
8317 // It is only correct to resolve to an instance method if we're
8318 // resolving a form that's permitted to be a pointer to member.
8319 // Otherwise we'll end up making a bound member expression, which
8320 // is illegal in all the contexts we resolve like this.
8321 if (!ovl.HasFormOfMemberPointer &&
8322 isa<CXXMethodDecl>(fn) &&
8323 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00008324 if (!complain) return false;
8325
8326 Diag(ovl.Expression->getExprLoc(),
8327 diag::err_bound_member_function)
8328 << 0 << ovl.Expression->getSourceRange();
8329
8330 // TODO: I believe we only end up here if there's a mix of
8331 // static and non-static candidates (otherwise the expression
8332 // would have 'bound member' type, not 'overload' type).
8333 // Ideally we would note which candidate was chosen and why
8334 // the static candidates were rejected.
8335 SrcExpr = ExprError();
8336 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008337 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008338
John McCall0009fcc2011-04-26 20:42:42 +00008339 // Fix the expresion to refer to 'fn'.
8340 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00008341 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00008342
8343 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00008344 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00008345 SingleFunctionExpression =
8346 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00008347 if (SingleFunctionExpression.isInvalid()) {
8348 SrcExpr = ExprError();
8349 return true;
8350 }
8351 }
John McCall0009fcc2011-04-26 20:42:42 +00008352 }
8353
8354 if (!SingleFunctionExpression.isUsable()) {
8355 if (complain) {
8356 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8357 << ovl.Expression->getName()
8358 << DestTypeForComplaining
8359 << OpRangeForComplaining
8360 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00008361 NoteAllOverloadCandidates(SrcExpr.get());
8362
8363 SrcExpr = ExprError();
8364 return true;
8365 }
8366
8367 return false;
John McCall0009fcc2011-04-26 20:42:42 +00008368 }
8369
John McCall50a2c2c2011-10-11 23:14:30 +00008370 SrcExpr = SingleFunctionExpression;
8371 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008372}
8373
Douglas Gregorcabea402009-09-22 15:41:20 +00008374/// \brief Add a single candidate to the overload set.
8375static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00008376 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008377 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008378 Expr **Args, unsigned NumArgs,
8379 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008380 bool PartialOverloading,
8381 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00008382 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00008383 if (isa<UsingShadowDecl>(Callee))
8384 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8385
Douglas Gregorcabea402009-09-22 15:41:20 +00008386 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00008387 if (ExplicitTemplateArgs) {
8388 assert(!KnownValid && "Explicit template arguments?");
8389 return;
8390 }
John McCalla0296f72010-03-19 07:35:19 +00008391 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00008392 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008393 return;
John McCalld14a8642009-11-21 08:51:07 +00008394 }
8395
8396 if (FunctionTemplateDecl *FuncTemplate
8397 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00008398 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8399 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00008400 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00008401 return;
8402 }
8403
Richard Smith95ce4f62011-06-26 22:19:54 +00008404 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00008405}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008406
Douglas Gregorcabea402009-09-22 15:41:20 +00008407/// \brief Add the overload candidates named by callee and/or found by argument
8408/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00008409void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00008410 Expr **Args, unsigned NumArgs,
8411 OverloadCandidateSet &CandidateSet,
8412 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00008413
8414#ifndef NDEBUG
8415 // Verify that ArgumentDependentLookup is consistent with the rules
8416 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00008417 //
Douglas Gregorcabea402009-09-22 15:41:20 +00008418 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8419 // and let Y be the lookup set produced by argument dependent
8420 // lookup (defined as follows). If X contains
8421 //
8422 // -- a declaration of a class member, or
8423 //
8424 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00008425 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00008426 //
8427 // -- a declaration that is neither a function or a function
8428 // template
8429 //
8430 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00008431
John McCall57500772009-12-16 12:17:52 +00008432 if (ULE->requiresADL()) {
8433 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8434 E = ULE->decls_end(); I != E; ++I) {
8435 assert(!(*I)->getDeclContext()->isRecord());
8436 assert(isa<UsingShadowDecl>(*I) ||
8437 !(*I)->getDeclContext()->isFunctionOrMethod());
8438 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008439 }
8440 }
8441#endif
8442
John McCall57500772009-12-16 12:17:52 +00008443 // It would be nice to avoid this copy.
8444 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008445 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008446 if (ULE->hasExplicitTemplateArgs()) {
8447 ULE->copyTemplateArgumentsInto(TABuffer);
8448 ExplicitTemplateArgs = &TABuffer;
8449 }
8450
8451 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8452 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008453 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008454 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008455 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008456
John McCall57500772009-12-16 12:17:52 +00008457 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008458 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8459 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008460 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008461 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008462 PartialOverloading,
8463 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008464}
John McCalld681c392009-12-16 08:11:27 +00008465
Richard Smith998a5912011-06-05 22:42:48 +00008466/// Attempt to recover from an ill-formed use of a non-dependent name in a
8467/// template, where the non-dependent name was declared after the template
8468/// was defined. This is common in code written for a compilers which do not
8469/// correctly implement two-stage name lookup.
8470///
8471/// Returns true if a viable candidate was found and a diagnostic was issued.
8472static bool
8473DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8474 const CXXScopeSpec &SS, LookupResult &R,
8475 TemplateArgumentListInfo *ExplicitTemplateArgs,
8476 Expr **Args, unsigned NumArgs) {
8477 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8478 return false;
8479
8480 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8481 SemaRef.LookupQualifiedName(R, DC);
8482
8483 if (!R.empty()) {
8484 R.suppressDiagnostics();
8485
8486 if (isa<CXXRecordDecl>(DC)) {
8487 // Don't diagnose names we find in classes; we get much better
8488 // diagnostics for these from DiagnoseEmptyLookup.
8489 R.clear();
8490 return false;
8491 }
8492
8493 OverloadCandidateSet Candidates(FnLoc);
8494 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8495 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8496 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008497 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008498
8499 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008500 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008501 // No viable functions. Don't bother the user with notes for functions
8502 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008503 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008504 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008505 }
Richard Smith998a5912011-06-05 22:42:48 +00008506
8507 // Find the namespaces where ADL would have looked, and suggest
8508 // declaring the function there instead.
8509 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8510 Sema::AssociatedClassSet AssociatedClasses;
8511 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8512 AssociatedNamespaces,
8513 AssociatedClasses);
8514 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008515 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008516 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008517 for (Sema::AssociatedNamespaceSet::iterator
8518 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008519 end = AssociatedNamespaces.end(); it != end; ++it) {
8520 if (!Std->Encloses(*it))
8521 SuggestedNamespaces.insert(*it);
8522 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008523 } else {
8524 // Lacking the 'std::' namespace, use all of the associated namespaces.
8525 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008526 }
8527
8528 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8529 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008530 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008531 SemaRef.Diag(Best->Function->getLocation(),
8532 diag::note_not_found_by_two_phase_lookup)
8533 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008534 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008535 SemaRef.Diag(Best->Function->getLocation(),
8536 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008537 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008538 } else {
8539 // FIXME: It would be useful to list the associated namespaces here,
8540 // but the diagnostics infrastructure doesn't provide a way to produce
8541 // a localized representation of a list of items.
8542 SemaRef.Diag(Best->Function->getLocation(),
8543 diag::note_not_found_by_two_phase_lookup)
8544 << R.getLookupName() << 2;
8545 }
8546
8547 // Try to recover by calling this function.
8548 return true;
8549 }
8550
8551 R.clear();
8552 }
8553
8554 return false;
8555}
8556
8557/// Attempt to recover from ill-formed use of a non-dependent operator in a
8558/// template, where the non-dependent operator was declared after the template
8559/// was defined.
8560///
8561/// Returns true if a viable candidate was found and a diagnostic was issued.
8562static bool
8563DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8564 SourceLocation OpLoc,
8565 Expr **Args, unsigned NumArgs) {
8566 DeclarationName OpName =
8567 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8568 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8569 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8570 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8571}
8572
John McCalld681c392009-12-16 08:11:27 +00008573/// Attempts to recover from a call where no functions were found.
8574///
8575/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008576static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008577BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008578 UnresolvedLookupExpr *ULE,
8579 SourceLocation LParenLoc,
8580 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008581 SourceLocation RParenLoc,
8582 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008583
8584 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008585 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008586
John McCall57500772009-12-16 12:17:52 +00008587 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008588 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008589 if (ULE->hasExplicitTemplateArgs()) {
8590 ULE->copyTemplateArgumentsInto(TABuffer);
8591 ExplicitTemplateArgs = &TABuffer;
8592 }
8593
John McCalld681c392009-12-16 08:11:27 +00008594 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8595 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008596 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8597 ExplicitTemplateArgs, Args, NumArgs) &&
8598 (!EmptyLookup ||
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00008599 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00008600 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00008601 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008602
John McCall57500772009-12-16 12:17:52 +00008603 assert(!R.empty() && "lookup results empty despite recovery");
8604
8605 // Build an implicit member call if appropriate. Just drop the
8606 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008607 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008608 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008609 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8610 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008611 else if (ExplicitTemplateArgs)
8612 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8613 else
8614 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8615
8616 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008617 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008618
8619 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008620 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008621 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008622 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008623 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008624}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008625
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008626/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008627/// (which eventually refers to the declaration Func) and the call
8628/// arguments Args/NumArgs, attempt to resolve the function call down
8629/// to a specific function. If overload resolution succeeds, returns
8630/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008631/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008632/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008633ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008634Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008635 SourceLocation LParenLoc,
8636 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008637 SourceLocation RParenLoc,
8638 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008639#ifndef NDEBUG
8640 if (ULE->requiresADL()) {
8641 // To do ADL, we must have found an unqualified name.
8642 assert(!ULE->getQualifier() && "qualified name with ADL");
8643
8644 // We don't perform ADL for implicit declarations of builtins.
8645 // Verify that this was correctly set up.
8646 FunctionDecl *F;
8647 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8648 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8649 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00008650 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008651
John McCall57500772009-12-16 12:17:52 +00008652 // We don't perform ADL in C.
8653 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008654 } else
8655 assert(!ULE->isStdAssociatedNamespace() &&
8656 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008657#endif
8658
John McCall4124c492011-10-17 18:40:02 +00008659 UnbridgedCastsSet UnbridgedCasts;
8660 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
8661 return ExprError();
8662
John McCallbc077cf2010-02-08 23:07:23 +00008663 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008664
John McCall57500772009-12-16 12:17:52 +00008665 // Add the functions denoted by the callee to the set of candidate
8666 // functions, including those from argument-dependent lookup.
8667 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008668
8669 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008670 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8671 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00008672 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008673 // In Microsoft mode, if we are inside a template class member function then
8674 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00008675 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008676 // classes.
8677 if (getLangOptions().MicrosoftExt && CurContext->isDependentContext() &&
8678 isa<CXXMethodDecl>(CurContext)) {
8679 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8680 Context.DependentTy, VK_RValue,
8681 RParenLoc);
8682 CE->setTypeDependent(true);
8683 return Owned(CE);
8684 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008685 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008686 RParenLoc, /*EmptyLookup=*/true);
Francois Pichetbcf64712011-09-07 00:14:57 +00008687 }
John McCalld681c392009-12-16 08:11:27 +00008688
John McCall4124c492011-10-17 18:40:02 +00008689 UnbridgedCasts.restore();
8690
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008691 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008692 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008693 case OR_Success: {
8694 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008695 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008696 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall4124c492011-10-17 18:40:02 +00008697 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008698 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008699 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8700 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008701 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008702
Richard Smith998a5912011-06-05 22:42:48 +00008703 case OR_No_Viable_Function: {
8704 // Try to recover by looking for viable functions which the user might
8705 // have meant to call.
8706 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8707 Args, NumArgs, RParenLoc,
8708 /*EmptyLookup=*/false);
8709 if (!Recovery.isInvalid())
8710 return Recovery;
8711
Chris Lattner45d9d602009-02-17 07:29:20 +00008712 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008713 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008714 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008715 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008716 break;
Richard Smith998a5912011-06-05 22:42:48 +00008717 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008718
8719 case OR_Ambiguous:
8720 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008721 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008722 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008723 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008724
8725 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008726 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008727 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8728 << Best->Function->isDeleted()
8729 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008730 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008731 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008732 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8733 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008734 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008735 }
8736
Douglas Gregorb412e172010-07-25 18:17:45 +00008737 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00008738 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008739}
8740
John McCall4c4c1df2010-01-26 03:27:55 +00008741static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00008742 return Functions.size() > 1 ||
8743 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8744}
8745
Douglas Gregor084d8552009-03-13 23:49:33 +00008746/// \brief Create a unary operation that may resolve to an overloaded
8747/// operator.
8748///
8749/// \param OpLoc The location of the operator itself (e.g., '*').
8750///
8751/// \param OpcIn The UnaryOperator::Opcode that describes this
8752/// operator.
8753///
8754/// \param Functions The set of non-member functions that will be
8755/// considered by overload resolution. The caller needs to build this
8756/// set based on the context using, e.g.,
8757/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8758/// set should not contain any member functions; those will be added
8759/// by CreateOverloadedUnaryOp().
8760///
8761/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00008762ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00008763Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8764 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00008765 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008766 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00008767
8768 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8769 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8770 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008771 // TODO: provide better source location info.
8772 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008773
John McCall4124c492011-10-17 18:40:02 +00008774 if (checkPlaceholderForOverload(*this, Input))
8775 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00008776
Douglas Gregor084d8552009-03-13 23:49:33 +00008777 Expr *Args[2] = { Input, 0 };
8778 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00008779
Douglas Gregor084d8552009-03-13 23:49:33 +00008780 // For post-increment and post-decrement, add the implicit '0' as
8781 // the second argument, so that we know this is a post-increment or
8782 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00008783 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008784 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008785 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8786 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00008787 NumArgs = 2;
8788 }
8789
8790 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00008791 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00008792 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008793 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00008794 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008795 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00008796 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008797
John McCall58cc69d2010-01-27 01:50:18 +00008798 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00008799 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008800 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008801 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008802 /*ADL*/ true, IsOverloaded(Fns),
8803 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00008804 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008805 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00008806 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008807 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00008808 OpLoc));
8809 }
8810
8811 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008812 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008813
8814 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008815 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00008816
8817 // Add operator candidates that are member functions.
8818 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8819
John McCall4c4c1df2010-01-26 03:27:55 +00008820 // Add candidates from ADL.
8821 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00008822 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00008823 /*ExplicitTemplateArgs*/ 0,
8824 CandidateSet);
8825
Douglas Gregor084d8552009-03-13 23:49:33 +00008826 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008827 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00008828
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008829 bool HadMultipleCandidates = (CandidateSet.size() > 1);
8830
Douglas Gregor084d8552009-03-13 23:49:33 +00008831 // Perform overload resolution.
8832 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008833 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008834 case OR_Success: {
8835 // We found a built-in operator or an overloaded operator.
8836 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00008837
Douglas Gregor084d8552009-03-13 23:49:33 +00008838 if (FnDecl) {
8839 // We matched an overloaded operator. Build a call to that
8840 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00008841
Chandler Carruth30141632011-02-25 19:41:05 +00008842 MarkDeclarationReferenced(OpLoc, FnDecl);
8843
Douglas Gregor084d8552009-03-13 23:49:33 +00008844 // Convert the arguments.
8845 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00008846 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008847
John Wiegley01296292011-04-08 18:41:53 +00008848 ExprResult InputRes =
8849 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8850 Best->FoundDecl, Method);
8851 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008852 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008853 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008854 } else {
8855 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008856 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00008857 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008858 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00008859 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008860 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00008861 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00008862 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008863 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008864 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008865 }
8866
John McCall4fa0d5f2010-05-06 18:15:07 +00008867 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8868
John McCall7decc9e2010-11-18 06:31:45 +00008869 // Determine the result type.
8870 QualType ResultTy = FnDecl->getResultType();
8871 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8872 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00008873
Douglas Gregor084d8552009-03-13 23:49:33 +00008874 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008875 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
8876 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00008877 if (FnExpr.isInvalid())
8878 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00008879
Eli Friedman030eee42009-11-18 03:58:17 +00008880 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00008881 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008882 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008883 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00008884
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008885 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00008886 FnDecl))
8887 return ExprError();
8888
John McCallb268a282010-08-23 23:25:46 +00008889 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00008890 } else {
8891 // We matched a built-in operator. Convert the arguments, then
8892 // break out so that we will build the appropriate built-in
8893 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008894 ExprResult InputRes =
8895 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8896 Best->Conversions[0], AA_Passing);
8897 if (InputRes.isInvalid())
8898 return ExprError();
8899 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008900 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00008901 }
John Wiegley01296292011-04-08 18:41:53 +00008902 }
8903
8904 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00008905 // This is an erroneous use of an operator which can be overloaded by
8906 // a non-member function. Check for non-member operators which were
8907 // defined too late to be candidates.
8908 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8909 // FIXME: Recover by calling the found function.
8910 return ExprError();
8911
John Wiegley01296292011-04-08 18:41:53 +00008912 // No viable function; fall through to handling this as a
8913 // built-in operator, which will produce an error message for us.
8914 break;
8915
8916 case OR_Ambiguous:
8917 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8918 << UnaryOperator::getOpcodeStr(Opc)
8919 << Input->getType()
8920 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008921 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00008922 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8923 return ExprError();
8924
8925 case OR_Deleted:
8926 Diag(OpLoc, diag::err_ovl_deleted_oper)
8927 << Best->Function->isDeleted()
8928 << UnaryOperator::getOpcodeStr(Opc)
8929 << getDeletedOrUnavailableSuffix(Best->Function)
8930 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008931 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
8932 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00008933 return ExprError();
8934 }
Douglas Gregor084d8552009-03-13 23:49:33 +00008935
8936 // Either we found no viable overloaded operator or we matched a
8937 // built-in operator. In either case, fall through to trying to
8938 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00008939 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008940}
8941
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008942/// \brief Create a binary operation that may resolve to an overloaded
8943/// operator.
8944///
8945/// \param OpLoc The location of the operator itself (e.g., '+').
8946///
8947/// \param OpcIn The BinaryOperator::Opcode that describes this
8948/// operator.
8949///
8950/// \param Functions The set of non-member functions that will be
8951/// considered by overload resolution. The caller needs to build this
8952/// set based on the context using, e.g.,
8953/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8954/// set should not contain any member functions; those will be added
8955/// by CreateOverloadedBinOp().
8956///
8957/// \param LHS Left-hand argument.
8958/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00008959ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008960Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008961 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00008962 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008963 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008964 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00008965 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008966
8967 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8968 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8969 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8970
8971 // If either side is type-dependent, create an appropriate dependent
8972 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00008973 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00008974 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008975 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00008976 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00008977 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00008978 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00008979 Context.DependentTy,
8980 VK_RValue, OK_Ordinary,
8981 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008982
Douglas Gregor5287f092009-11-05 00:51:44 +00008983 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8984 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008985 VK_LValue,
8986 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00008987 Context.DependentTy,
8988 Context.DependentTy,
8989 OpLoc));
8990 }
John McCall4c4c1df2010-01-26 03:27:55 +00008991
8992 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00008993 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008994 // TODO: provide better source location info in DNLoc component.
8995 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00008996 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00008997 = UnresolvedLookupExpr::Create(Context, NamingClass,
8998 NestedNameSpecifierLoc(), OpNameInfo,
8999 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009000 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009001 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00009002 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009003 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009004 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009005 OpLoc));
9006 }
9007
John McCall4124c492011-10-17 18:40:02 +00009008 // Always do placeholder-like conversions on the RHS.
9009 if (checkPlaceholderForOverload(*this, Args[1]))
9010 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009011
9012 // The LHS is more complicated.
9013 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
9014
9015 // There's a tension for assignment operators between primitive
9016 // property assignment and the overloaded operators.
9017 if (BinaryOperator::isAssignmentOp(Opc)) {
9018 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
9019
9020 // Is the property "logically" settable?
9021 bool Settable = (PRE->isExplicitProperty() ||
9022 PRE->getImplicitPropertySetter());
9023
9024 // To avoid gratuitously inventing semantics, use the primitive
9025 // unless it isn't. Thoughts in case we ever really care:
9026 // - If the property isn't logically settable, we have to
9027 // load and hope.
9028 // - If the property is settable and this is simple assignment,
9029 // we really should use the primitive.
9030 // - If the property is settable, then we could try overloading
9031 // on a generic lvalue of the appropriate type; if it works
9032 // out to a builtin candidate, we would do that same operation
9033 // on the property, and otherwise just error.
9034 if (Settable)
9035 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9036 }
9037
John Wiegley01296292011-04-08 18:41:53 +00009038 ExprResult Result = ConvertPropertyForRValue(Args[0]);
9039 if (Result.isInvalid())
9040 return ExprError();
9041 Args[0] = Result.take();
John McCalle26a8722010-12-04 08:14:53 +00009042 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009043
John McCall4124c492011-10-17 18:40:02 +00009044 // Handle all the other placeholders.
9045 if (checkPlaceholderForOverload(*this, Args[0]))
9046 return ExprError();
9047
Sebastian Redl6a96bf72009-11-18 23:10:33 +00009048 // If this is the assignment operator, we only perform overload resolution
9049 // if the left-hand side is a class or enumeration type. This is actually
9050 // a hack. The standard requires that we do overload resolution between the
9051 // various built-in candidates, but as DR507 points out, this can lead to
9052 // problems. So we do it this way, which pretty much follows what GCC does.
9053 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00009054 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00009055 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009056
John McCalle26a8722010-12-04 08:14:53 +00009057 // If this is the .* operator, which is not overloadable, just
9058 // create a built-in binary operator.
9059 if (Opc == BO_PtrMemD)
9060 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9061
Douglas Gregor084d8552009-03-13 23:49:33 +00009062 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009063 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009064
9065 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00009066 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009067
9068 // Add operator candidates that are member functions.
9069 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9070
John McCall4c4c1df2010-01-26 03:27:55 +00009071 // Add candidates from ADL.
9072 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9073 Args, 2,
9074 /*ExplicitTemplateArgs*/ 0,
9075 CandidateSet);
9076
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009077 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00009078 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009079
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009080 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9081
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009082 // Perform overload resolution.
9083 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009084 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009085 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009086 // We found a built-in operator or an overloaded operator.
9087 FunctionDecl *FnDecl = Best->Function;
9088
9089 if (FnDecl) {
9090 // We matched an overloaded operator. Build a call to that
9091 // operator.
9092
Chandler Carruth30141632011-02-25 19:41:05 +00009093 MarkDeclarationReferenced(OpLoc, FnDecl);
9094
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009095 // Convert the arguments.
9096 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009097 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009098 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009099
Chandler Carruth8e543b32010-12-12 08:17:55 +00009100 ExprResult Arg1 =
9101 PerformCopyInitialization(
9102 InitializedEntity::InitializeParameter(Context,
9103 FnDecl->getParamDecl(0)),
9104 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009105 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009106 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009107
John Wiegley01296292011-04-08 18:41:53 +00009108 ExprResult Arg0 =
9109 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9110 Best->FoundDecl, Method);
9111 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009112 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009113 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009114 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009115 } else {
9116 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009117 ExprResult Arg0 = PerformCopyInitialization(
9118 InitializedEntity::InitializeParameter(Context,
9119 FnDecl->getParamDecl(0)),
9120 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009121 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009122 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009123
Chandler Carruth8e543b32010-12-12 08:17:55 +00009124 ExprResult Arg1 =
9125 PerformCopyInitialization(
9126 InitializedEntity::InitializeParameter(Context,
9127 FnDecl->getParamDecl(1)),
9128 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009129 if (Arg1.isInvalid())
9130 return ExprError();
9131 Args[0] = LHS = Arg0.takeAs<Expr>();
9132 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009133 }
9134
John McCall4fa0d5f2010-05-06 18:15:07 +00009135 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9136
John McCall7decc9e2010-11-18 06:31:45 +00009137 // Determine the result type.
9138 QualType ResultTy = FnDecl->getResultType();
9139 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9140 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009141
9142 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009143 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9144 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009145 if (FnExpr.isInvalid())
9146 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009147
John McCallb268a282010-08-23 23:25:46 +00009148 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009149 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009150 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009151
9152 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009153 FnDecl))
9154 return ExprError();
9155
John McCallb268a282010-08-23 23:25:46 +00009156 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009157 } else {
9158 // We matched a built-in operator. Convert the arguments, then
9159 // break out so that we will build the appropriate built-in
9160 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009161 ExprResult ArgsRes0 =
9162 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9163 Best->Conversions[0], AA_Passing);
9164 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009165 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009166 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009167
John Wiegley01296292011-04-08 18:41:53 +00009168 ExprResult ArgsRes1 =
9169 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9170 Best->Conversions[1], AA_Passing);
9171 if (ArgsRes1.isInvalid())
9172 return ExprError();
9173 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009174 break;
9175 }
9176 }
9177
Douglas Gregor66950a32009-09-30 21:46:01 +00009178 case OR_No_Viable_Function: {
9179 // C++ [over.match.oper]p9:
9180 // If the operator is the operator , [...] and there are no
9181 // viable functions, then the operator is assumed to be the
9182 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00009183 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00009184 break;
9185
Chandler Carruth8e543b32010-12-12 08:17:55 +00009186 // For class as left operand for assignment or compound assigment
9187 // operator do not fall through to handling in built-in, but report that
9188 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00009189 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009190 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00009191 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00009192 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9193 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00009194 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00009195 } else {
Richard Smith998a5912011-06-05 22:42:48 +00009196 // This is an erroneous use of an operator which can be overloaded by
9197 // a non-member function. Check for non-member operators which were
9198 // defined too late to be candidates.
9199 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9200 // FIXME: Recover by calling the found function.
9201 return ExprError();
9202
Douglas Gregor66950a32009-09-30 21:46:01 +00009203 // No viable function; try to create a built-in operation, which will
9204 // produce an error. Then, show the non-viable candidates.
9205 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00009206 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009207 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00009208 "C++ binary operator overloading is missing candidates!");
9209 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00009210 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9211 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00009212 return move(Result);
9213 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009214
9215 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009216 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009217 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00009218 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00009219 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009220 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9221 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009222 return ExprError();
9223
9224 case OR_Deleted:
9225 Diag(OpLoc, diag::err_ovl_deleted_oper)
9226 << Best->Function->isDeleted()
9227 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009228 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00009229 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009230 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9231 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009232 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00009233 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009234
Douglas Gregor66950a32009-09-30 21:46:01 +00009235 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00009236 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009237}
9238
John McCalldadc5752010-08-24 06:29:42 +00009239ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00009240Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9241 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00009242 Expr *Base, Expr *Idx) {
9243 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00009244 DeclarationName OpName =
9245 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9246
9247 // If either side is type-dependent, create an appropriate dependent
9248 // expression.
9249 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9250
John McCall58cc69d2010-01-27 01:50:18 +00009251 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009252 // CHECKME: no 'operator' keyword?
9253 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9254 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00009255 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009256 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009257 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009258 /*ADL*/ true, /*Overloaded*/ false,
9259 UnresolvedSetIterator(),
9260 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00009261 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00009262
Sebastian Redladba46e2009-10-29 20:17:01 +00009263 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9264 Args, 2,
9265 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009266 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00009267 RLoc));
9268 }
9269
John McCall4124c492011-10-17 18:40:02 +00009270 // Handle placeholders on both operands.
9271 if (checkPlaceholderForOverload(*this, Args[0]))
9272 return ExprError();
9273 if (checkPlaceholderForOverload(*this, Args[1]))
9274 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009275
Sebastian Redladba46e2009-10-29 20:17:01 +00009276 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009277 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009278
9279 // Subscript can only be overloaded as a member function.
9280
9281 // Add operator candidates that are member functions.
9282 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9283
9284 // Add builtin operator candidates.
9285 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9286
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009287 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9288
Sebastian Redladba46e2009-10-29 20:17:01 +00009289 // Perform overload resolution.
9290 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009291 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00009292 case OR_Success: {
9293 // We found a built-in operator or an overloaded operator.
9294 FunctionDecl *FnDecl = Best->Function;
9295
9296 if (FnDecl) {
9297 // We matched an overloaded operator. Build a call to that
9298 // operator.
9299
Chandler Carruth30141632011-02-25 19:41:05 +00009300 MarkDeclarationReferenced(LLoc, FnDecl);
9301
John McCalla0296f72010-03-19 07:35:19 +00009302 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009303 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00009304
Sebastian Redladba46e2009-10-29 20:17:01 +00009305 // Convert the arguments.
9306 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00009307 ExprResult Arg0 =
9308 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9309 Best->FoundDecl, Method);
9310 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009311 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009312 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009313
Anders Carlssona68e51e2010-01-29 18:37:50 +00009314 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009315 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00009316 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009317 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00009318 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009319 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00009320 Owned(Args[1]));
9321 if (InputInit.isInvalid())
9322 return ExprError();
9323
9324 Args[1] = InputInit.takeAs<Expr>();
9325
Sebastian Redladba46e2009-10-29 20:17:01 +00009326 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00009327 QualType ResultTy = FnDecl->getResultType();
9328 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9329 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00009330
9331 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00009332 DeclarationNameLoc LocInfo;
9333 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9334 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009335 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9336 HadMultipleCandidates,
9337 LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00009338 if (FnExpr.isInvalid())
9339 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009340
John McCallb268a282010-08-23 23:25:46 +00009341 CXXOperatorCallExpr *TheCall =
9342 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00009343 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00009344 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009345
John McCallb268a282010-08-23 23:25:46 +00009346 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00009347 FnDecl))
9348 return ExprError();
9349
John McCallb268a282010-08-23 23:25:46 +00009350 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00009351 } else {
9352 // We matched a built-in operator. Convert the arguments, then
9353 // break out so that we will build the appropriate built-in
9354 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009355 ExprResult ArgsRes0 =
9356 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9357 Best->Conversions[0], AA_Passing);
9358 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009359 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009360 Args[0] = ArgsRes0.take();
9361
9362 ExprResult ArgsRes1 =
9363 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9364 Best->Conversions[1], AA_Passing);
9365 if (ArgsRes1.isInvalid())
9366 return ExprError();
9367 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009368
9369 break;
9370 }
9371 }
9372
9373 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00009374 if (CandidateSet.empty())
9375 Diag(LLoc, diag::err_ovl_no_oper)
9376 << Args[0]->getType() << /*subscript*/ 0
9377 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9378 else
9379 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9380 << Args[0]->getType()
9381 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009382 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9383 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00009384 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009385 }
9386
9387 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009388 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009389 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00009390 << Args[0]->getType() << Args[1]->getType()
9391 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009392 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9393 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009394 return ExprError();
9395
9396 case OR_Deleted:
9397 Diag(LLoc, diag::err_ovl_deleted_oper)
9398 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009399 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00009400 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009401 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9402 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009403 return ExprError();
9404 }
9405
9406 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00009407 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009408}
9409
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009410/// BuildCallToMemberFunction - Build a call to a member
9411/// function. MemExpr is the expression that refers to the member
9412/// function (and includes the object parameter), Args/NumArgs are the
9413/// arguments to the function call (not including the object
9414/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00009415/// expression refers to a non-static member function or an overloaded
9416/// member function.
John McCalldadc5752010-08-24 06:29:42 +00009417ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00009418Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9419 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009420 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00009421 assert(MemExprE->getType() == Context.BoundMemberTy ||
9422 MemExprE->getType() == Context.OverloadTy);
9423
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009424 // Dig out the member expression. This holds both the object
9425 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00009426 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009427
John McCall0009fcc2011-04-26 20:42:42 +00009428 // Determine whether this is a call to a pointer-to-member function.
9429 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9430 assert(op->getType() == Context.BoundMemberTy);
9431 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9432
9433 QualType fnType =
9434 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9435
9436 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9437 QualType resultType = proto->getCallResultType(Context);
9438 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9439
9440 // Check that the object type isn't more qualified than the
9441 // member function we're calling.
9442 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9443
9444 QualType objectType = op->getLHS()->getType();
9445 if (op->getOpcode() == BO_PtrMemI)
9446 objectType = objectType->castAs<PointerType>()->getPointeeType();
9447 Qualifiers objectQuals = objectType.getQualifiers();
9448
9449 Qualifiers difference = objectQuals - funcQuals;
9450 difference.removeObjCGCAttr();
9451 difference.removeAddressSpace();
9452 if (difference) {
9453 std::string qualsString = difference.getAsString();
9454 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9455 << fnType.getUnqualifiedType()
9456 << qualsString
9457 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9458 }
9459
9460 CXXMemberCallExpr *call
9461 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9462 resultType, valueKind, RParenLoc);
9463
9464 if (CheckCallReturnType(proto->getResultType(),
9465 op->getRHS()->getSourceRange().getBegin(),
9466 call, 0))
9467 return ExprError();
9468
9469 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9470 return ExprError();
9471
9472 return MaybeBindToTemporary(call);
9473 }
9474
John McCall4124c492011-10-17 18:40:02 +00009475 UnbridgedCastsSet UnbridgedCasts;
9476 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9477 return ExprError();
9478
John McCall10eae182009-11-30 22:42:35 +00009479 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009480 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009481 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009482 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009483 if (isa<MemberExpr>(NakedMemExpr)) {
9484 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009485 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009486 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009487 Qualifier = MemExpr->getQualifier();
John McCall4124c492011-10-17 18:40:02 +00009488 UnbridgedCasts.restore();
John McCall10eae182009-11-30 22:42:35 +00009489 } else {
9490 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009491 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009492
John McCall6e9f8f62009-12-03 04:06:58 +00009493 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009494 Expr::Classification ObjectClassification
9495 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9496 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009497
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009498 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009499 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009500
John McCall2d74de92009-12-01 22:10:20 +00009501 // FIXME: avoid copy.
9502 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9503 if (UnresExpr->hasExplicitTemplateArgs()) {
9504 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9505 TemplateArgs = &TemplateArgsBuffer;
9506 }
9507
John McCall10eae182009-11-30 22:42:35 +00009508 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9509 E = UnresExpr->decls_end(); I != E; ++I) {
9510
John McCall6e9f8f62009-12-03 04:06:58 +00009511 NamedDecl *Func = *I;
9512 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9513 if (isa<UsingShadowDecl>(Func))
9514 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9515
Douglas Gregor02824322011-01-26 19:30:28 +00009516
Francois Pichet64225792011-01-18 05:04:39 +00009517 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +00009518 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +00009519 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9520 CandidateSet);
9521 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009522 // If explicit template arguments were provided, we can't call a
9523 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009524 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009525 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009526
John McCalla0296f72010-03-19 07:35:19 +00009527 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009528 ObjectClassification,
9529 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009530 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009531 } else {
John McCall10eae182009-11-30 22:42:35 +00009532 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009533 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009534 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009535 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009536 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009537 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009538 }
Mike Stump11289f42009-09-09 15:08:12 +00009539
John McCall10eae182009-11-30 22:42:35 +00009540 DeclarationName DeclName = UnresExpr->getMemberName();
9541
John McCall4124c492011-10-17 18:40:02 +00009542 UnbridgedCasts.restore();
9543
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009544 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009545 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009546 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009547 case OR_Success:
9548 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009549 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009550 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009551 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009552 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009553 break;
9554
9555 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009556 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009557 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009558 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009559 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009560 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009561 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009562
9563 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009564 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009565 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009566 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009567 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009568 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009569
9570 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009571 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009572 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009573 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009574 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009575 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009576 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009577 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009578 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009579 }
9580
John McCall16df1e52010-03-30 21:47:33 +00009581 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009582
John McCall2d74de92009-12-01 22:10:20 +00009583 // If overload resolution picked a static member, build a
9584 // non-member call based on that function.
9585 if (Method->isStatic()) {
9586 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9587 Args, NumArgs, RParenLoc);
9588 }
9589
John McCall10eae182009-11-30 22:42:35 +00009590 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009591 }
9592
John McCall7decc9e2010-11-18 06:31:45 +00009593 QualType ResultType = Method->getResultType();
9594 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9595 ResultType = ResultType.getNonLValueExprType(Context);
9596
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009597 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009598 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009599 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009600 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009601
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009602 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009603 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009604 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009605 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009606
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009607 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009608 // We only need to do this if there was actually an overload; otherwise
9609 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009610 if (!Method->isStatic()) {
9611 ExprResult ObjectArg =
9612 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9613 FoundDecl, Method);
9614 if (ObjectArg.isInvalid())
9615 return ExprError();
9616 MemExpr->setBase(ObjectArg.take());
9617 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009618
9619 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009620 const FunctionProtoType *Proto =
9621 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009622 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009623 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009624 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009625
John McCallb268a282010-08-23 23:25:46 +00009626 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009627 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009628
Anders Carlsson47061ee2011-05-06 14:25:31 +00009629 if ((isa<CXXConstructorDecl>(CurContext) ||
9630 isa<CXXDestructorDecl>(CurContext)) &&
9631 TheCall->getMethodDecl()->isPure()) {
9632 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9633
Chandler Carruth59259262011-06-27 08:31:58 +00009634 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009635 Diag(MemExpr->getLocStart(),
9636 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9637 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9638 << MD->getParent()->getDeclName();
9639
9640 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009641 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009642 }
John McCallb268a282010-08-23 23:25:46 +00009643 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009644}
9645
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009646/// BuildCallToObjectOfClassType - Build a call to an object of class
9647/// type (C++ [over.call.object]), which can end up invoking an
9648/// overloaded function call operator (@c operator()) or performing a
9649/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009650ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009651Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009652 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009653 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009654 SourceLocation RParenLoc) {
John McCall4124c492011-10-17 18:40:02 +00009655 if (checkPlaceholderForOverload(*this, Obj))
9656 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009657 ExprResult Object = Owned(Obj);
John McCall4124c492011-10-17 18:40:02 +00009658
9659 UnbridgedCastsSet UnbridgedCasts;
9660 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9661 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009662
John Wiegley01296292011-04-08 18:41:53 +00009663 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9664 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009665
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009666 // C++ [over.call.object]p1:
9667 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009668 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009669 // candidate functions includes at least the function call
9670 // operators of T. The function call operators of T are obtained by
9671 // ordinary lookup of the name operator() in the context of
9672 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009673 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009674 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009675
John Wiegley01296292011-04-08 18:41:53 +00009676 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009677 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009678 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009679 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009680
John McCall27b18f82009-11-17 02:14:36 +00009681 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9682 LookupQualifiedName(R, Record->getDecl());
9683 R.suppressDiagnostics();
9684
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009685 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009686 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009687 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9688 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009689 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009690 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009691
Douglas Gregorab7897a2008-11-19 22:57:39 +00009692 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009693 // In addition, for each (non-explicit in C++0x) conversion function
9694 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +00009695 //
9696 // operator conversion-type-id () cv-qualifier;
9697 //
9698 // where cv-qualifier is the same cv-qualification as, or a
9699 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009700 // denotes the type "pointer to function of (P1,...,Pn) returning
9701 // R", or the type "reference to pointer to function of
9702 // (P1,...,Pn) returning R", or the type "reference to function
9703 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009704 // is also considered as a candidate function. Similarly,
9705 // surrogate call functions are added to the set of candidate
9706 // functions for each conversion function declared in an
9707 // accessible base class provided the function is not hidden
9708 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009709 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009710 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009711 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009712 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009713 NamedDecl *D = *I;
9714 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9715 if (isa<UsingShadowDecl>(D))
9716 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009717
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009718 // Skip over templated conversion functions; they aren't
9719 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009720 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009721 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009722
John McCall6e9f8f62009-12-03 04:06:58 +00009723 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009724 if (!Conv->isExplicit()) {
9725 // Strip the reference type (if any) and then the pointer type (if
9726 // any) to get down to what might be a function type.
9727 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9728 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9729 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +00009730
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009731 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9732 {
9733 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9734 Object.get(), Args, NumArgs, CandidateSet);
9735 }
9736 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00009737 }
Mike Stump11289f42009-09-09 15:08:12 +00009738
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009739 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9740
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009741 // Perform overload resolution.
9742 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009743 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009744 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009745 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009746 // Overload resolution succeeded; we'll build the appropriate call
9747 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009748 break;
9749
9750 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009751 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009752 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9753 << Object.get()->getType() << /*call*/ 1
9754 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009755 else
John Wiegley01296292011-04-08 18:41:53 +00009756 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009757 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009758 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009759 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009760 break;
9761
9762 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009763 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009764 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009765 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009766 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009767 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009768
9769 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00009770 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00009771 diag::err_ovl_deleted_object_call)
9772 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +00009773 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009774 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +00009775 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009776 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009777 break;
Mike Stump11289f42009-09-09 15:08:12 +00009778 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009779
Douglas Gregorb412e172010-07-25 18:17:45 +00009780 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009781 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009782
John McCall4124c492011-10-17 18:40:02 +00009783 UnbridgedCasts.restore();
9784
Douglas Gregorab7897a2008-11-19 22:57:39 +00009785 if (Best->Function == 0) {
9786 // Since there is no function declaration, this is one of the
9787 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00009788 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00009789 = cast<CXXConversionDecl>(
9790 Best->Conversions[0].UserDefined.ConversionFunction);
9791
John Wiegley01296292011-04-08 18:41:53 +00009792 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009793 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009794
Douglas Gregorab7897a2008-11-19 22:57:39 +00009795 // We selected one of the surrogate functions that converts the
9796 // object parameter to a function pointer. Perform the conversion
9797 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009798
Fariborz Jahanian774cf792009-09-28 18:35:46 +00009799 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00009800 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009801 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
9802 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00009803 if (Call.isInvalid())
9804 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009805
Douglas Gregor668443e2011-01-20 00:18:04 +00009806 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00009807 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00009808 }
9809
Chandler Carruth30141632011-02-25 19:41:05 +00009810 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009811 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009812 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009813
Douglas Gregorab7897a2008-11-19 22:57:39 +00009814 // We found an overloaded operator(). Build a CXXOperatorCallExpr
9815 // that calls this method, using Object for the implicit object
9816 // parameter and passing along the remaining arguments.
9817 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00009818 const FunctionProtoType *Proto =
9819 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009820
9821 unsigned NumArgsInProto = Proto->getNumArgs();
9822 unsigned NumArgsToCheck = NumArgs;
9823
9824 // Build the full argument list for the method call (the
9825 // implicit object parameter is placed at the beginning of the
9826 // list).
9827 Expr **MethodArgs;
9828 if (NumArgs < NumArgsInProto) {
9829 NumArgsToCheck = NumArgsInProto;
9830 MethodArgs = new Expr*[NumArgsInProto + 1];
9831 } else {
9832 MethodArgs = new Expr*[NumArgs + 1];
9833 }
John Wiegley01296292011-04-08 18:41:53 +00009834 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009835 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9836 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00009837
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009838 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
9839 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00009840 if (NewFn.isInvalid())
9841 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009842
9843 // Once we've built TheCall, all of the expressions are properly
9844 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00009845 QualType ResultTy = Method->getResultType();
9846 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9847 ResultTy = ResultTy.getNonLValueExprType(Context);
9848
John McCallb268a282010-08-23 23:25:46 +00009849 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009850 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +00009851 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00009852 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009853 delete [] MethodArgs;
9854
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009855 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00009856 Method))
9857 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009858
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009859 // We may have default arguments. If so, we need to allocate more
9860 // slots in the call for them.
9861 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00009862 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009863 else if (NumArgs > NumArgsInProto)
9864 NumArgsToCheck = NumArgsInProto;
9865
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009866 bool IsError = false;
9867
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009868 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +00009869 ExprResult ObjRes =
9870 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9871 Best->FoundDecl, Method);
9872 if (ObjRes.isInvalid())
9873 IsError = true;
9874 else
9875 Object = move(ObjRes);
9876 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009877
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009878 // Check the argument types.
9879 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009880 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009881 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009882 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00009883
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009884 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009885
John McCalldadc5752010-08-24 06:29:42 +00009886 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009887 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009888 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009889 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00009890 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009891
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009892 IsError |= InputInit.isInvalid();
9893 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009894 } else {
John McCalldadc5752010-08-24 06:29:42 +00009895 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009896 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9897 if (DefArg.isInvalid()) {
9898 IsError = true;
9899 break;
9900 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009901
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009902 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009903 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009904
9905 TheCall->setArg(i + 1, Arg);
9906 }
9907
9908 // If this is a variadic call, handle args passed through "...".
9909 if (Proto->isVariadic()) {
9910 // Promote the arguments (C99 6.5.2.2p7).
9911 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +00009912 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9913 IsError |= Arg.isInvalid();
9914 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009915 }
9916 }
9917
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009918 if (IsError) return true;
9919
John McCallb268a282010-08-23 23:25:46 +00009920 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00009921 return true;
9922
John McCalle172be52010-08-24 06:09:16 +00009923 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009924}
9925
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009926/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00009927/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009928/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00009929ExprResult
John McCallb268a282010-08-23 23:25:46 +00009930Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009931 assert(Base->getType()->isRecordType() &&
9932 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00009933
John McCall4124c492011-10-17 18:40:02 +00009934 if (checkPlaceholderForOverload(*this, Base))
9935 return ExprError();
John McCalle26a8722010-12-04 08:14:53 +00009936
John McCallbc077cf2010-02-08 23:07:23 +00009937 SourceLocation Loc = Base->getExprLoc();
9938
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009939 // C++ [over.ref]p1:
9940 //
9941 // [...] An expression x->m is interpreted as (x.operator->())->m
9942 // for a class object x of type T if T::operator->() exists and if
9943 // the operator is selected as the best match function by the
9944 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00009945 DeclarationName OpName =
9946 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00009947 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009948 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00009949
John McCallbc077cf2010-02-08 23:07:23 +00009950 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00009951 PDiag(diag::err_typecheck_incomplete_tag)
9952 << Base->getSourceRange()))
9953 return ExprError();
9954
John McCall27b18f82009-11-17 02:14:36 +00009955 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9956 LookupQualifiedName(R, BaseRecord->getDecl());
9957 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00009958
9959 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00009960 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00009961 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9962 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00009963 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009964
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009965 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9966
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009967 // Perform overload resolution.
9968 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009969 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009970 case OR_Success:
9971 // Overload resolution succeeded; we'll build the call below.
9972 break;
9973
9974 case OR_No_Viable_Function:
9975 if (CandidateSet.empty())
9976 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00009977 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009978 else
9979 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00009980 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009981 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009982 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009983
9984 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009985 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9986 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009987 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009988 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009989
9990 case OR_Deleted:
9991 Diag(OpLoc, diag::err_ovl_deleted_oper)
9992 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009993 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009994 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009995 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009996 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009997 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009998 }
9999
Chandler Carruth30141632011-02-25 19:41:05 +000010000 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +000010001 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +000010002 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +000010003
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010004 // Convert the object parameter.
10005 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +000010006 ExprResult BaseResult =
10007 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10008 Best->FoundDecl, Method);
10009 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +000010010 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +000010011 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +000010012
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010013 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010014 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
10015 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +000010016 if (FnExpr.isInvalid())
10017 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010018
John McCall7decc9e2010-11-18 06:31:45 +000010019 QualType ResultTy = Method->getResultType();
10020 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10021 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +000010022 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +000010023 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +000010024 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010025
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010026 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +000010027 Method))
10028 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +000010029
10030 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +000010031}
10032
Douglas Gregorcd695e52008-11-10 20:40:00 +000010033/// FixOverloadedFunctionReference - E is an expression that refers to
10034/// a C++ overloaded function (possibly with some parentheses and
10035/// perhaps a '&' around it). We have resolved the overloaded function
10036/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +000010037/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +000010038Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +000010039 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +000010040 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010041 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10042 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010043 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010044 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010045
Douglas Gregor51c538b2009-11-20 19:42:02 +000010046 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010047 }
10048
Douglas Gregor51c538b2009-11-20 19:42:02 +000010049 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +000010050 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10051 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010052 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +000010053 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +000010054 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +000010055 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +000010056 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010057 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010058
10059 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +000010060 ICE->getCastKind(),
10061 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +000010062 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010063 }
10064
Douglas Gregor51c538b2009-11-20 19:42:02 +000010065 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +000010066 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +000010067 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010068 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10069 if (Method->isStatic()) {
10070 // Do nothing: static member functions aren't any different
10071 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +000010072 } else {
John McCalle66edc12009-11-24 19:00:30 +000010073 // Fix the sub expression, which really has to be an
10074 // UnresolvedLookupExpr holding an overloaded member function
10075 // or template.
John McCall16df1e52010-03-30 21:47:33 +000010076 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10077 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +000010078 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010079 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010080
John McCalld14a8642009-11-21 08:51:07 +000010081 assert(isa<DeclRefExpr>(SubExpr)
10082 && "fixed to something other than a decl ref");
10083 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10084 && "fixed to a member ref with no nested name qualifier");
10085
10086 // We have taken the address of a pointer to member
10087 // function. Perform the computation here so that we get the
10088 // appropriate pointer to member type.
10089 QualType ClassType
10090 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10091 QualType MemPtrType
10092 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10093
John McCall7decc9e2010-11-18 06:31:45 +000010094 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10095 VK_RValue, OK_Ordinary,
10096 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010097 }
10098 }
John McCall16df1e52010-03-30 21:47:33 +000010099 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10100 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010101 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010102 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010103
John McCalle3027922010-08-25 11:45:40 +000010104 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010105 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000010106 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010107 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010108 }
John McCalld14a8642009-11-21 08:51:07 +000010109
10110 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000010111 // FIXME: avoid copy.
10112 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000010113 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000010114 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10115 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000010116 }
10117
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010118 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10119 ULE->getQualifierLoc(),
10120 Fn,
10121 ULE->getNameLoc(),
10122 Fn->getType(),
10123 VK_LValue,
10124 Found.getDecl(),
10125 TemplateArgs);
10126 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10127 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000010128 }
10129
John McCall10eae182009-11-30 22:42:35 +000010130 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000010131 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000010132 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10133 if (MemExpr->hasExplicitTemplateArgs()) {
10134 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10135 TemplateArgs = &TemplateArgsBuffer;
10136 }
John McCall6b51f282009-11-23 01:53:49 +000010137
John McCall2d74de92009-12-01 22:10:20 +000010138 Expr *Base;
10139
John McCall7decc9e2010-11-18 06:31:45 +000010140 // If we're filling in a static method where we used to have an
10141 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000010142 if (MemExpr->isImplicitAccess()) {
10143 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010144 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10145 MemExpr->getQualifierLoc(),
10146 Fn,
10147 MemExpr->getMemberLoc(),
10148 Fn->getType(),
10149 VK_LValue,
10150 Found.getDecl(),
10151 TemplateArgs);
10152 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10153 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000010154 } else {
10155 SourceLocation Loc = MemExpr->getMemberLoc();
10156 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000010157 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +000010158 Base = new (Context) CXXThisExpr(Loc,
10159 MemExpr->getBaseType(),
10160 /*isImplicit=*/true);
10161 }
John McCall2d74de92009-12-01 22:10:20 +000010162 } else
John McCallc3007a22010-10-26 07:05:15 +000010163 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000010164
John McCall4adb38c2011-04-27 00:36:17 +000010165 ExprValueKind valueKind;
10166 QualType type;
10167 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10168 valueKind = VK_LValue;
10169 type = Fn->getType();
10170 } else {
10171 valueKind = VK_RValue;
10172 type = Context.BoundMemberTy;
10173 }
10174
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010175 MemberExpr *ME = MemberExpr::Create(Context, Base,
10176 MemExpr->isArrow(),
10177 MemExpr->getQualifierLoc(),
10178 Fn,
10179 Found,
10180 MemExpr->getMemberNameInfo(),
10181 TemplateArgs,
10182 type, valueKind, OK_Ordinary);
10183 ME->setHadMultipleCandidates(true);
10184 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010185 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010186
John McCallc3007a22010-10-26 07:05:15 +000010187 llvm_unreachable("Invalid reference to overloaded function");
10188 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010189}
10190
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010191ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000010192 DeclAccessPair Found,
10193 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000010194 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000010195}
10196
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010197} // end namespace clang