blob: 931f60fbc77701acd56a5c9265d5ad97c395fe92 [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
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000545// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000546// overload of the declarations in Old. This routine returns false if
547// New and Old cannot be overloaded, e.g., if New has the same
548// signature as some function in Old (C++ 1.3.10) or if the Old
549// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000550// it does return false, MatchedDecl will point to the decl that New
551// cannot be overloaded with. This decl may be a UsingShadowDecl on
552// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000553//
554// Example: Given the following input:
555//
556// void f(int, float); // #1
557// void f(int, int); // #2
558// int f(int, int); // #3
559//
560// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000561// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000562//
John McCall3d988d92009-12-02 08:47:38 +0000563// When we process #2, Old contains only the FunctionDecl for #1. By
564// comparing the parameter types, we see that #1 and #2 are overloaded
565// (since they have different signatures), so this routine returns
566// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000567//
John McCall3d988d92009-12-02 08:47:38 +0000568// When we process #3, Old is an overload set containing #1 and #2. We
569// compare the signatures of #3 to #1 (they're overloaded, so we do
570// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
571// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000572// signature), IsOverload returns false and MatchedDecl will be set to
573// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000574//
575// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
576// into a class by a using declaration. The rules for whether to hide
577// shadow declarations ignore some properties which otherwise figure
578// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000579Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000580Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
581 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000582 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000583 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000584 NamedDecl *OldD = *I;
585
586 bool OldIsUsingDecl = false;
587 if (isa<UsingShadowDecl>(OldD)) {
588 OldIsUsingDecl = true;
589
590 // We can always introduce two using declarations into the same
591 // context, even if they have identical signatures.
592 if (NewIsUsingDecl) continue;
593
594 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
595 }
596
597 // If either declaration was introduced by a using declaration,
598 // we'll need to use slightly different rules for matching.
599 // Essentially, these rules are the normal rules, except that
600 // function templates hide function templates with different
601 // return types or template parameter lists.
602 bool UseMemberUsingDeclRules =
603 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
604
John McCall3d988d92009-12-02 08:47:38 +0000605 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000606 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
607 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
608 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
609 continue;
610 }
611
John McCalldaa3d6b2009-12-09 03:35:25 +0000612 Match = *I;
613 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000614 }
John McCall3d988d92009-12-02 08:47:38 +0000615 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000616 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
617 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
618 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
619 continue;
620 }
621
John McCalldaa3d6b2009-12-09 03:35:25 +0000622 Match = *I;
623 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000624 }
John McCalla8987a2942010-11-10 03:01:53 +0000625 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000626 // We can overload with these, which can show up when doing
627 // redeclaration checks for UsingDecls.
628 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000629 } else if (isa<TagDecl>(OldD)) {
630 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000631 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
632 // Optimistically assume that an unresolved using decl will
633 // overload; if it doesn't, we'll have to diagnose during
634 // template instantiation.
635 } else {
John McCall1f82f242009-11-18 22:49:29 +0000636 // (C++ 13p1):
637 // Only function declarations can be overloaded; object and type
638 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000639 Match = *I;
640 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000641 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000642 }
John McCall1f82f242009-11-18 22:49:29 +0000643
John McCalldaa3d6b2009-12-09 03:35:25 +0000644 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000645}
646
John McCalle9cccd82010-06-16 08:42:20 +0000647bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
648 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000649 // If both of the functions are extern "C", then they are not
650 // overloads.
651 if (Old->isExternC() && New->isExternC())
652 return false;
653
John McCall1f82f242009-11-18 22:49:29 +0000654 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
655 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
656
657 // C++ [temp.fct]p2:
658 // A function template can be overloaded with other function templates
659 // and with normal (non-template) functions.
660 if ((OldTemplate == 0) != (NewTemplate == 0))
661 return true;
662
663 // Is the function New an overload of the function Old?
664 QualType OldQType = Context.getCanonicalType(Old->getType());
665 QualType NewQType = Context.getCanonicalType(New->getType());
666
667 // Compare the signatures (C++ 1.3.10) of the two functions to
668 // determine whether they are overloads. If we find any mismatch
669 // in the signature, they are overloads.
670
671 // If either of these functions is a K&R-style function (no
672 // prototype), then we consider them to have matching signatures.
673 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
674 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
675 return false;
676
John McCall424cec92011-01-19 06:33:43 +0000677 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
678 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000679
680 // The signature of a function includes the types of its
681 // parameters (C++ 1.3.10), which includes the presence or absence
682 // of the ellipsis; see C++ DR 357).
683 if (OldQType != NewQType &&
684 (OldType->getNumArgs() != NewType->getNumArgs() ||
685 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000686 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000687 return true;
688
689 // C++ [temp.over.link]p4:
690 // The signature of a function template consists of its function
691 // signature, its return type and its template parameter list. The names
692 // of the template parameters are significant only for establishing the
693 // relationship between the template parameters and the rest of the
694 // signature.
695 //
696 // We check the return type and template parameter lists for function
697 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000698 //
699 // However, we don't consider either of these when deciding whether
700 // a member introduced by a shadow declaration is hidden.
701 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000702 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
703 OldTemplate->getTemplateParameters(),
704 false, TPL_TemplateMatch) ||
705 OldType->getResultType() != NewType->getResultType()))
706 return true;
707
708 // If the function is a class member, its signature includes the
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000709 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall1f82f242009-11-18 22:49:29 +0000710 //
711 // As part of this, also check whether one of the member functions
712 // is static, in which case they are not overloads (C++
713 // 13.1p2). While not part of the definition of the signature,
714 // this check is important to determine whether these functions
715 // can be overloaded.
716 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
717 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
718 if (OldMethod && NewMethod &&
719 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregorb2f8aa92011-01-26 17:47:49 +0000720 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorc83f98652011-01-26 21:20:37 +0000721 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
722 if (!UseUsingDeclRules &&
723 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
724 (OldMethod->getRefQualifier() == RQ_None ||
725 NewMethod->getRefQualifier() == RQ_None)) {
726 // C++0x [over.load]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000727 // - Member function declarations with the same name and the same
728 // parameter-type-list as well as member function template
729 // declarations with the same name, the same parameter-type-list, and
730 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorc83f98652011-01-26 21:20:37 +0000731 // them, but not all, have a ref-qualifier (8.3.5).
732 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
733 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
734 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
735 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000736
John McCall1f82f242009-11-18 22:49:29 +0000737 return true;
Douglas Gregorc83f98652011-01-26 21:20:37 +0000738 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000739
John McCall1f82f242009-11-18 22:49:29 +0000740 // The signatures match; this is not an overload.
741 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000742}
743
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +0000744/// \brief Checks availability of the function depending on the current
745/// function context. Inside an unavailable function, unavailability is ignored.
746///
747/// \returns true if \arg FD is unavailable and current context is inside
748/// an available function, false otherwise.
749bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
750 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
751}
752
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000753/// TryImplicitConversion - Attempt to perform an implicit conversion
754/// from the given expression (Expr) to the given type (ToType). This
755/// function returns an implicit conversion sequence that can be used
756/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000757///
758/// void f(float f);
759/// void g(int i) { f(i); }
760///
761/// this routine would produce an implicit conversion sequence to
762/// describe the initialization of f from i, which will be a standard
763/// conversion sequence containing an lvalue-to-rvalue conversion (C++
764/// 4.1) followed by a floating-integral conversion (C++ 4.9).
765//
766/// Note that this routine only determines how the conversion can be
767/// performed; it does not actually perform the conversion. As such,
768/// it will not produce any diagnostics if no conversion is available,
769/// but will instead return an implicit conversion sequence of kind
770/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000771///
772/// If @p SuppressUserConversions, then user-defined conversions are
773/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000774/// If @p AllowExplicit, then explicit user-defined conversions are
775/// permitted.
John McCall31168b02011-06-15 23:02:42 +0000776///
777/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
778/// writeback conversion, which allows __autoreleasing id* parameters to
779/// be initialized with __strong id* or __weak id* arguments.
John McCall5c32be02010-08-24 20:38:10 +0000780static ImplicitConversionSequence
781TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
782 bool SuppressUserConversions,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000783 bool AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000784 bool InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000785 bool CStyle,
786 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000787 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000788 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +0000789 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall0d1da222010-01-12 00:44:57 +0000790 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000791 return ICS;
792 }
793
John McCall5c32be02010-08-24 20:38:10 +0000794 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000795 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000796 return ICS;
797 }
798
Douglas Gregor836a7e82010-08-11 02:15:33 +0000799 // C++ [over.ics.user]p4:
800 // A conversion of an expression of class type to the same class
801 // type is given Exact Match rank, and a conversion of an
802 // expression of class type to a base class of that type is
803 // given Conversion rank, in spite of the fact that a copy/move
804 // constructor (i.e., a user-defined conversion function) is
805 // called for those cases.
806 QualType FromType = From->getType();
807 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000808 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
809 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000810 ICS.setStandard();
811 ICS.Standard.setAsIdentityConversion();
812 ICS.Standard.setFromType(FromType);
813 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000814
Douglas Gregor5ab11652010-04-17 22:01:05 +0000815 // We don't actually check at this point whether there is a valid
816 // copy/move constructor, since overloading just assumes that it
817 // exists. When we actually perform initialization, we'll find the
818 // appropriate constructor to copy the returned object, if needed.
819 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000820
Douglas Gregor5ab11652010-04-17 22:01:05 +0000821 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000822 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000823 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000824
Douglas Gregor836a7e82010-08-11 02:15:33 +0000825 return ICS;
826 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000827
Douglas Gregor836a7e82010-08-11 02:15:33 +0000828 if (SuppressUserConversions) {
829 // We're not in the case above, so there is no conversion that
830 // we can perform.
831 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000832 return ICS;
833 }
834
835 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000836 OverloadCandidateSet Conversions(From->getExprLoc());
837 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000838 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000839 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000840
841 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000842 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000843 // C++ [over.ics.user]p4:
844 // A conversion of an expression of class type to the same class
845 // type is given Exact Match rank, and a conversion of an
846 // expression of class type to a base class of that type is
847 // given Conversion rank, in spite of the fact that a copy
848 // constructor (i.e., a user-defined conversion function) is
849 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000850 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000851 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000852 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000853 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
854 QualType ToCanon
855 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000856 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000857 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000858 // Turn this into a "standard" conversion sequence, so that it
859 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000860 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000861 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000862 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000863 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000864 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000865 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000866 ICS.Standard.Second = ICK_Derived_To_Base;
867 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000868 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000869
870 // C++ [over.best.ics]p4:
871 // However, when considering the argument of a user-defined
872 // conversion function that is a candidate by 13.3.1.3 when
873 // invoked for the copying of the temporary in the second step
874 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
875 // 13.3.1.6 in all cases, only standard conversion sequences and
876 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000877 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000878 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000879 }
John McCalle8c8cd22010-01-13 22:30:33 +0000880 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000881 ICS.setAmbiguous();
882 ICS.Ambiguous.setFromType(From->getType());
883 ICS.Ambiguous.setToType(ToType);
884 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
885 Cand != Conversions.end(); ++Cand)
886 if (Cand->Viable)
887 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000888 } else {
John McCall65eb8792010-02-25 01:37:24 +0000889 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000890 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000891
892 return ICS;
893}
894
John McCall31168b02011-06-15 23:02:42 +0000895ImplicitConversionSequence
896Sema::TryImplicitConversion(Expr *From, QualType ToType,
897 bool SuppressUserConversions,
898 bool AllowExplicit,
899 bool InOverloadResolution,
900 bool CStyle,
901 bool AllowObjCWritebackConversion) {
902 return clang::TryImplicitConversion(*this, From, ToType,
903 SuppressUserConversions, AllowExplicit,
904 InOverloadResolution, CStyle,
905 AllowObjCWritebackConversion);
John McCall5c32be02010-08-24 20:38:10 +0000906}
907
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000908/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley01296292011-04-08 18:41:53 +0000909/// expression From to the type ToType. Returns the
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000910/// converted expression. Flavor is the kind of conversion we're
911/// performing, used in the error message. If @p AllowExplicit,
912/// explicit user-defined conversions are permitted.
John Wiegley01296292011-04-08 18:41:53 +0000913ExprResult
914Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redlcc152642011-10-16 18:19:06 +0000915 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000916 ImplicitConversionSequence ICS;
Sebastian Redlcc152642011-10-16 18:19:06 +0000917 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000918}
919
John Wiegley01296292011-04-08 18:41:53 +0000920ExprResult
921Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000922 AssignmentAction Action, bool AllowExplicit,
Sebastian Redlcc152642011-10-16 18:19:06 +0000923 ImplicitConversionSequence& ICS) {
John McCall31168b02011-06-15 23:02:42 +0000924 // Objective-C ARC: Determine whether we will allow the writeback conversion.
925 bool AllowObjCWritebackConversion
926 = getLangOptions().ObjCAutoRefCount &&
927 (Action == AA_Passing || Action == AA_Sending);
John McCall31168b02011-06-15 23:02:42 +0000928
John McCall5c32be02010-08-24 20:38:10 +0000929 ICS = clang::TryImplicitConversion(*this, From, ToType,
930 /*SuppressUserConversions=*/false,
931 AllowExplicit,
Douglas Gregor58281352011-01-27 00:58:17 +0000932 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +0000933 /*CStyle=*/false,
934 AllowObjCWritebackConversion);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000935 return PerformImplicitConversion(From, ToType, ICS, Action);
936}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000937
938/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000939/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth53e61b02011-06-18 01:19:03 +0000940bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
941 QualType &ResultTy) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000942 if (Context.hasSameUnqualifiedType(FromType, ToType))
943 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000944
John McCall991eb4b2010-12-21 00:44:39 +0000945 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
946 // where F adds one of the following at most once:
947 // - a pointer
948 // - a member pointer
949 // - a block pointer
950 CanQualType CanTo = Context.getCanonicalType(ToType);
951 CanQualType CanFrom = Context.getCanonicalType(FromType);
952 Type::TypeClass TyClass = CanTo->getTypeClass();
953 if (TyClass != CanFrom->getTypeClass()) return false;
954 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
955 if (TyClass == Type::Pointer) {
956 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
957 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
958 } else if (TyClass == Type::BlockPointer) {
959 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
960 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
961 } else if (TyClass == Type::MemberPointer) {
962 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
963 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
964 } else {
965 return false;
966 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000967
John McCall991eb4b2010-12-21 00:44:39 +0000968 TyClass = CanTo->getTypeClass();
969 if (TyClass != CanFrom->getTypeClass()) return false;
970 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
971 return false;
972 }
973
974 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
975 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
976 if (!EInfo.getNoReturn()) return false;
977
978 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
979 assert(QualType(FromFn, 0).isCanonical());
980 if (QualType(FromFn, 0) != CanTo) return false;
981
982 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000983 return true;
984}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000985
Douglas Gregor46188682010-05-18 22:42:18 +0000986/// \brief Determine whether the conversion from FromType to ToType is a valid
987/// vector conversion.
988///
989/// \param ICK Will be set to the vector conversion kind, if this is a vector
990/// conversion.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +0000991static bool IsVectorConversion(ASTContext &Context, QualType FromType,
992 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregor46188682010-05-18 22:42:18 +0000993 // We need at least one of these types to be a vector type to have a vector
994 // conversion.
995 if (!ToType->isVectorType() && !FromType->isVectorType())
996 return false;
997
998 // Identical types require no conversions.
999 if (Context.hasSameUnqualifiedType(FromType, ToType))
1000 return false;
1001
1002 // There are no conversions between extended vector types, only identity.
1003 if (ToType->isExtVectorType()) {
1004 // There are no conversions between extended vector types other than the
1005 // identity conversion.
1006 if (FromType->isExtVectorType())
1007 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001008
Douglas Gregor46188682010-05-18 22:42:18 +00001009 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +00001010 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +00001011 ICK = ICK_Vector_Splat;
1012 return true;
1013 }
1014 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001015
1016 // We can perform the conversion between vector types in the following cases:
1017 // 1)vector types are equivalent AltiVec and GCC vector types
1018 // 2)lax vector conversions are permitted and the vector types are of the
1019 // same size
1020 if (ToType->isVectorType() && FromType->isVectorType()) {
1021 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +00001022 (Context.getLangOptions().LaxVectorConversions &&
1023 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001024 ICK = ICK_Vector_Conversion;
1025 return true;
1026 }
Douglas Gregor46188682010-05-18 22:42:18 +00001027 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +00001028
Douglas Gregor46188682010-05-18 22:42:18 +00001029 return false;
1030}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001031
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001032/// IsStandardConversion - Determines whether there is a standard
1033/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1034/// expression From to the type ToType. Standard conversion sequences
1035/// only consider non-class types; for conversions that involve class
1036/// types, use TryImplicitConversion. If a conversion exists, SCS will
1037/// contain the standard conversion sequence required to perform this
1038/// conversion and this routine will return true. Otherwise, this
1039/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +00001040static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1041 bool InOverloadResolution,
Douglas Gregor58281352011-01-27 00:58:17 +00001042 StandardConversionSequence &SCS,
John McCall31168b02011-06-15 23:02:42 +00001043 bool CStyle,
1044 bool AllowObjCWritebackConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001045 QualType FromType = From->getType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001046
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001047 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +00001048 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +00001049 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001050 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +00001051 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +00001052 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001053
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001054 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +00001055 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001056 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +00001057 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001058 return false;
1059
Mike Stump11289f42009-09-09 15:08:12 +00001060 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001061 }
1062
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001063 // The first conversion can be an lvalue-to-rvalue conversion,
1064 // array-to-pointer conversion, or function-to-pointer conversion
1065 // (C++ 4p1).
1066
John McCall5c32be02010-08-24 20:38:10 +00001067 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001068 DeclAccessPair AccessPair;
1069 if (FunctionDecl *Fn
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001070 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall5c32be02010-08-24 20:38:10 +00001071 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001072 // We were able to resolve the address of the overloaded function,
1073 // so we can convert to the type of that function.
1074 FromType = Fn->getType();
Douglas Gregorb491ed32011-02-19 21:32:49 +00001075
1076 // we can sometimes resolve &foo<int> regardless of ToType, so check
1077 // if the type matches (identity) or we are converting to bool
1078 if (!S.Context.hasSameUnqualifiedType(
1079 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1080 QualType resultTy;
1081 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth53e61b02011-06-18 01:19:03 +00001082 if (!S.IsNoReturnConversion(FromType,
Douglas Gregorb491ed32011-02-19 21:32:49 +00001083 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1084 // otherwise, only a boolean conversion is standard
1085 if (!ToType->isBooleanType())
1086 return false;
Douglas Gregor980fb162010-04-29 18:24:40 +00001087 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001088
Chandler Carruthffce2452011-03-29 08:08:18 +00001089 // Check if the "from" expression is taking the address of an overloaded
1090 // function and recompute the FromType accordingly. Take advantage of the
1091 // fact that non-static member functions *must* have such an address-of
1092 // expression.
1093 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1094 if (Method && !Method->isStatic()) {
1095 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1096 "Non-unary operator on non-static member address");
1097 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1098 == UO_AddrOf &&
1099 "Non-address-of operator on non-static member address");
1100 const Type *ClassType
1101 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1102 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruth7750f762011-03-29 18:38:10 +00001103 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1104 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1105 UO_AddrOf &&
Chandler Carruthffce2452011-03-29 08:08:18 +00001106 "Non-address-of operator for overloaded function expression");
1107 FromType = S.Context.getPointerType(FromType);
1108 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001109
Douglas Gregor980fb162010-04-29 18:24:40 +00001110 // Check that we've computed the proper type after overload resolution.
Chandler Carruthffce2452011-03-29 08:08:18 +00001111 assert(S.Context.hasSameType(
1112 FromType,
1113 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001114 } else {
1115 return false;
1116 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001117 }
John McCall154a2fd2011-08-30 00:57:29 +00001118 // Lvalue-to-rvalue conversion (C++11 4.1):
1119 // A glvalue (3.10) of a non-function, non-array type T can
1120 // be converted to a prvalue.
1121 bool argIsLValue = From->isGLValue();
John McCall086a4642010-11-24 05:12:34 +00001122 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001123 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001124 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001125 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001126
1127 // If T is a non-class type, the type of the rvalue is the
1128 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001129 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1130 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001131 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001132 } else if (FromType->isArrayType()) {
1133 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001134 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001135
1136 // An lvalue or rvalue of type "array of N T" or "array of unknown
1137 // bound of T" can be converted to an rvalue of type "pointer to
1138 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001139 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001140
John McCall5c32be02010-08-24 20:38:10 +00001141 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001142 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001143 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001144
1145 // For the purpose of ranking in overload resolution
1146 // (13.3.3.1.1), this conversion is considered an
1147 // array-to-pointer conversion followed by a qualification
1148 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001149 SCS.Second = ICK_Identity;
1150 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001151 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001152 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001153 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001154 }
John McCall086a4642010-11-24 05:12:34 +00001155 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001156 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001157 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001158
1159 // An lvalue of function type T can be converted to an rvalue of
1160 // type "pointer to T." The result is a pointer to the
1161 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001162 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001163 } else {
1164 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001165 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001166 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001167 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001168
1169 // The second conversion can be an integral promotion, floating
1170 // point promotion, integral conversion, floating point conversion,
1171 // floating-integral conversion, pointer conversion,
1172 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001173 // For overloading in C, this can also be a "compatible-type"
1174 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001175 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001176 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001177 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001178 // The unqualified versions of the types are the same: there's no
1179 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001180 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001181 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001182 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001183 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001184 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001185 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001186 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001187 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001188 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001189 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001190 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001191 SCS.Second = ICK_Complex_Promotion;
1192 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001193 } else if (ToType->isBooleanType() &&
1194 (FromType->isArithmeticType() ||
1195 FromType->isAnyPointerType() ||
1196 FromType->isBlockPointerType() ||
1197 FromType->isMemberPointerType() ||
1198 FromType->isNullPtrType())) {
1199 // Boolean conversions (C++ 4.12).
1200 SCS.Second = ICK_Boolean_Conversion;
1201 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001202 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001203 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001204 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001205 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001206 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001207 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001208 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001209 SCS.Second = ICK_Complex_Conversion;
1210 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001211 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1212 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001213 // Complex-real conversions (C99 6.3.1.7)
1214 SCS.Second = ICK_Complex_Real;
1215 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001216 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001217 // Floating point conversions (C++ 4.8).
1218 SCS.Second = ICK_Floating_Conversion;
1219 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001220 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001221 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001222 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001223 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001224 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001225 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001226 FromType = ToType.getUnqualifiedType();
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001227 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCall31168b02011-06-15 23:02:42 +00001228 SCS.Second = ICK_Block_Pointer_Conversion;
1229 } else if (AllowObjCWritebackConversion &&
1230 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1231 SCS.Second = ICK_Writeback_Conversion;
John McCall5c32be02010-08-24 20:38:10 +00001232 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1233 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001234 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001235 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001236 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregoraec25842011-04-26 23:16:46 +00001237 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001238 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall5c32be02010-08-24 20:38:10 +00001239 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001240 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001241 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001242 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001243 SCS.Second = SecondICK;
1244 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001245 } else if (!S.getLangOptions().CPlusPlus &&
1246 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001247 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001248 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001249 FromType = ToType.getUnqualifiedType();
Chandler Carruth53e61b02011-06-18 01:19:03 +00001250 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001251 // Treat a conversion that strips "noreturn" as an identity conversion.
1252 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001253 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1254 InOverloadResolution,
1255 SCS, CStyle)) {
1256 SCS.Second = ICK_TransparentUnionConversion;
1257 FromType = ToType;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001258 } else {
1259 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001260 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001261 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001262 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001263
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001264 QualType CanonFrom;
1265 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001266 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall31168b02011-06-15 23:02:42 +00001267 bool ObjCLifetimeConversion;
1268 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1269 ObjCLifetimeConversion)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001270 SCS.Third = ICK_Qualification;
John McCall31168b02011-06-15 23:02:42 +00001271 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001272 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001273 CanonFrom = S.Context.getCanonicalType(FromType);
1274 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001275 } else {
1276 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001277 SCS.Third = ICK_Identity;
1278
Mike Stump11289f42009-09-09 15:08:12 +00001279 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001280 // [...] Any difference in top-level cv-qualification is
1281 // subsumed by the initialization itself and does not constitute
1282 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001283 CanonFrom = S.Context.getCanonicalType(FromType);
1284 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001285 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001286 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001287 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCall31168b02011-06-15 23:02:42 +00001288 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1289 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001290 FromType = ToType;
1291 CanonFrom = CanonTo;
1292 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001293 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001294 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001295
1296 // If we have not converted the argument type to the parameter type,
1297 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001298 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001299 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001300
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001301 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001302}
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001303
1304static bool
1305IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1306 QualType &ToType,
1307 bool InOverloadResolution,
1308 StandardConversionSequence &SCS,
1309 bool CStyle) {
1310
1311 const RecordType *UT = ToType->getAsUnionType();
1312 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1313 return false;
1314 // The field to initialize within the transparent union.
1315 RecordDecl *UD = UT->getDecl();
1316 // It's compatible if the expression matches any of the fields.
1317 for (RecordDecl::field_iterator it = UD->field_begin(),
1318 itend = UD->field_end();
1319 it != itend; ++it) {
John McCall31168b02011-06-15 23:02:42 +00001320 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1321 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahanian16f92ce2011-03-23 19:50:54 +00001322 ToType = it->getType();
1323 return true;
1324 }
1325 }
1326 return false;
1327}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001328
1329/// IsIntegralPromotion - Determines whether the conversion from the
1330/// expression From (whose potentially-adjusted type is FromType) to
1331/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1332/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001333bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001334 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001335 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001336 if (!To) {
1337 return false;
1338 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001339
1340 // An rvalue of type char, signed char, unsigned char, short int, or
1341 // unsigned short int can be converted to an rvalue of type int if
1342 // int can represent all the values of the source type; otherwise,
1343 // the source rvalue can be converted to an rvalue of type unsigned
1344 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001345 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1346 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001347 if (// We can promote any signed, promotable integer type to an int
1348 (FromType->isSignedIntegerType() ||
1349 // We can promote any unsigned integer type whose size is
1350 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001351 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001352 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001353 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001354 }
1355
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001356 return To->getKind() == BuiltinType::UInt;
1357 }
1358
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001359 // C++0x [conv.prom]p3:
1360 // A prvalue of an unscoped enumeration type whose underlying type is not
1361 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1362 // following types that can represent all the values of the enumeration
1363 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1364 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001365 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001366 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001367 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001368 // with lowest integer conversion rank (4.13) greater than the rank of long
1369 // long in which all the values of the enumeration can be represented. If
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001370 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001371 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1372 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1373 // provided for a scoped enumeration.
1374 if (FromEnumType->getDecl()->isScoped())
1375 return false;
1376
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001377 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001378 if (ToType->isIntegerType() &&
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001379 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001380 return Context.hasSameUnqualifiedType(ToType,
1381 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001382 }
John McCall56774992009-12-09 09:09:27 +00001383
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001384 // C++0x [conv.prom]p2:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001385 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1386 // to an rvalue a prvalue of the first of the following types that can
1387 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001388 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001389 // If none of the types in that list can represent all the values of its
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001390 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001391 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001392 // type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001393 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001394 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001395 // Determine whether the type we're converting from is signed or
1396 // unsigned.
David Majnemerfa01a582011-07-22 21:09:04 +00001397 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001398 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001399
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001400 // The types we'll try to promote to, in the appropriate
1401 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001402 QualType PromoteTypes[6] = {
1403 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001404 Context.LongTy, Context.UnsignedLongTy ,
1405 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001406 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001407 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001408 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1409 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001410 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001411 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1412 // We found the type that we can promote to. If this is the
1413 // type we wanted, we have a promotion. Otherwise, no
1414 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001415 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001416 }
1417 }
1418 }
1419
1420 // An rvalue for an integral bit-field (9.6) can be converted to an
1421 // rvalue of type int if int can represent all the values of the
1422 // bit-field; otherwise, it can be converted to unsigned int if
1423 // unsigned int can represent all the values of the bit-field. If
1424 // the bit-field is larger yet, no integral promotion applies to
1425 // it. If the bit-field has an enumerated type, it is treated as any
1426 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001427 // FIXME: We should delay checking of bit-fields until we actually perform the
1428 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001429 using llvm::APSInt;
1430 if (From)
1431 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001432 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001433 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001434 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1435 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1436 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001437
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001438 // Are we promoting to an int from a bitfield that fits in an int?
1439 if (BitWidth < ToSize ||
1440 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1441 return To->getKind() == BuiltinType::Int;
1442 }
Mike Stump11289f42009-09-09 15:08:12 +00001443
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001444 // Are we promoting to an unsigned int from an unsigned bitfield
1445 // that fits into an unsigned int?
1446 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1447 return To->getKind() == BuiltinType::UInt;
1448 }
Mike Stump11289f42009-09-09 15:08:12 +00001449
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001450 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001451 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001452 }
Mike Stump11289f42009-09-09 15:08:12 +00001453
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001454 // An rvalue of type bool can be converted to an rvalue of type int,
1455 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001456 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001457 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001458 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001459
1460 return false;
1461}
1462
1463/// IsFloatingPointPromotion - Determines whether the conversion from
1464/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1465/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001466bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001467 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1468 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001469 /// An rvalue of type float can be converted to an rvalue of type
1470 /// double. (C++ 4.6p1).
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001471 if (FromBuiltin->getKind() == BuiltinType::Float &&
1472 ToBuiltin->getKind() == BuiltinType::Double)
1473 return true;
1474
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001475 // C99 6.3.1.5p1:
1476 // When a float is promoted to double or long double, or a
1477 // double is promoted to long double [...].
1478 if (!getLangOptions().CPlusPlus &&
1479 (FromBuiltin->getKind() == BuiltinType::Float ||
1480 FromBuiltin->getKind() == BuiltinType::Double) &&
1481 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1482 return true;
Anton Korobeynikovf0c267e2011-10-14 23:23:15 +00001483
1484 // Half can be promoted to float.
1485 if (FromBuiltin->getKind() == BuiltinType::Half &&
1486 ToBuiltin->getKind() == BuiltinType::Float)
1487 return true;
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001488 }
1489
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001490 return false;
1491}
1492
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001493/// \brief Determine if a conversion is a complex promotion.
1494///
1495/// A complex promotion is defined as a complex -> complex conversion
1496/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001497/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001498bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001499 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001500 if (!FromComplex)
1501 return false;
1502
John McCall9dd450b2009-09-21 23:43:11 +00001503 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001504 if (!ToComplex)
1505 return false;
1506
1507 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001508 ToComplex->getElementType()) ||
1509 IsIntegralPromotion(0, FromComplex->getElementType(),
1510 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001511}
1512
Douglas Gregor237f96c2008-11-26 23:31:11 +00001513/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1514/// the pointer type FromPtr to a pointer to type ToPointee, with the
1515/// same type qualifiers as FromPtr has on its pointee type. ToType,
1516/// if non-empty, will be a pointer to ToType that may or may not have
1517/// the right set of qualifiers on its pointee.
John McCall31168b02011-06-15 23:02:42 +00001518///
Mike Stump11289f42009-09-09 15:08:12 +00001519static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001520BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001521 QualType ToPointee, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00001522 ASTContext &Context,
1523 bool StripObjCLifetime = false) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001524 assert((FromPtr->getTypeClass() == Type::Pointer ||
1525 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1526 "Invalid similarly-qualified pointer type");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001527
John McCall31168b02011-06-15 23:02:42 +00001528 /// Conversions to 'id' subsume cv-qualifier conversions.
1529 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001530 return ToType.getUnqualifiedType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001531
1532 QualType CanonFromPointee
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001533 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001534 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001535 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001536
John McCall31168b02011-06-15 23:02:42 +00001537 if (StripObjCLifetime)
1538 Quals.removeObjCLifetime();
1539
Mike Stump11289f42009-09-09 15:08:12 +00001540 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001541 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001542 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001543 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001544 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001545
1546 // Build a pointer to ToPointee. It has the right qualifiers
1547 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001548 if (isa<ObjCObjectPointerType>(ToType))
1549 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001550 return Context.getPointerType(ToPointee);
1551 }
1552
1553 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001554 QualType QualifiedCanonToPointee
1555 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001556
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001557 if (isa<ObjCObjectPointerType>(ToType))
1558 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1559 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001560}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001561
Mike Stump11289f42009-09-09 15:08:12 +00001562static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001563 bool InOverloadResolution,
1564 ASTContext &Context) {
1565 // Handle value-dependent integral null pointer constants correctly.
1566 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1567 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001568 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001569 return !InOverloadResolution;
1570
Douglas Gregor56751b52009-09-25 04:25:58 +00001571 return Expr->isNullPointerConstant(Context,
1572 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1573 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001574}
Mike Stump11289f42009-09-09 15:08:12 +00001575
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001576/// IsPointerConversion - Determines whether the conversion of the
1577/// expression From, which has the (possibly adjusted) type FromType,
1578/// can be converted to the type ToType via a pointer conversion (C++
1579/// 4.10). If so, returns true and places the converted type (that
1580/// might differ from ToType in its cv-qualifiers at some level) into
1581/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001582///
Douglas Gregora29dc052008-11-27 01:19:21 +00001583/// This routine also supports conversions to and from block pointers
1584/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1585/// pointers to interfaces. FIXME: Once we've determined the
1586/// appropriate overloading rules for Objective-C, we may want to
1587/// split the Objective-C checks into a different routine; however,
1588/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001589/// conversions, so for now they live here. IncompatibleObjC will be
1590/// set if the conversion is an allowed Objective-C conversion that
1591/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001592bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001593 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001594 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001595 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001596 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001597 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1598 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001599 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001600
Mike Stump11289f42009-09-09 15:08:12 +00001601 // Conversion from a null pointer constant to any Objective-C pointer type.
1602 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001603 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001604 ConvertedType = ToType;
1605 return true;
1606 }
1607
Douglas Gregor231d1c62008-11-27 00:15:41 +00001608 // Blocks: Block pointers can be converted to void*.
1609 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001610 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001611 ConvertedType = ToType;
1612 return true;
1613 }
1614 // Blocks: A null pointer constant can be converted to a block
1615 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001616 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001617 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001618 ConvertedType = ToType;
1619 return true;
1620 }
1621
Sebastian Redl576fd422009-05-10 18:38:11 +00001622 // If the left-hand-side is nullptr_t, the right side can be a null
1623 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001624 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001625 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001626 ConvertedType = ToType;
1627 return true;
1628 }
1629
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001630 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001631 if (!ToTypePtr)
1632 return false;
1633
1634 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001635 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001636 ConvertedType = ToType;
1637 return true;
1638 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001639
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001640 // Beyond this point, both types need to be pointers
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001641 // , including objective-c pointers.
1642 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCall31168b02011-06-15 23:02:42 +00001643 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1644 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001645 ConvertedType = BuildSimilarlyQualifiedPointerType(
1646 FromType->getAs<ObjCObjectPointerType>(),
1647 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001648 ToType, Context);
1649 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001650 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001651 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001652 if (!FromTypePtr)
1653 return false;
1654
1655 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001656
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001657 // If the unqualified pointee types are the same, this can't be a
Douglas Gregorfb640862010-08-18 21:25:30 +00001658 // pointer conversion, so don't do all of the work below.
1659 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1660 return false;
1661
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001662 // An rvalue of type "pointer to cv T," where T is an object type,
1663 // can be converted to an rvalue of type "pointer to cv void" (C++
1664 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001665 if (FromPointeeType->isIncompleteOrObjectType() &&
1666 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001667 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001668 ToPointeeType,
John McCall31168b02011-06-15 23:02:42 +00001669 ToType, Context,
1670 /*StripObjCLifetime=*/true);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001671 return true;
1672 }
1673
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001674 // MSVC allows implicit function to void* type conversion.
Francois Pichet0706d202011-09-17 17:15:52 +00001675 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Pichetbc6ebb52011-05-08 22:52:41 +00001676 ToPointeeType->isVoidType()) {
1677 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1678 ToPointeeType,
1679 ToType, Context);
1680 return true;
1681 }
1682
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001683 // When we're overloading in C, we allow a special kind of pointer
1684 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001685 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001686 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001687 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001688 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001689 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001690 return true;
1691 }
1692
Douglas Gregor5c407d92008-10-23 00:40:37 +00001693 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001694 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001695 // An rvalue of type "pointer to cv D," where D is a class type,
1696 // can be converted to an rvalue of type "pointer to cv B," where
1697 // B is a base class (clause 10) of D. If B is an inaccessible
1698 // (clause 11) or ambiguous (10.2) base class of D, a program that
1699 // necessitates this conversion is ill-formed. The result of the
1700 // conversion is a pointer to the base class sub-object of the
1701 // derived class object. The null pointer value is converted to
1702 // the null pointer value of the destination type.
1703 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001704 // Note that we do not check for ambiguity or inaccessibility
1705 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001706 if (getLangOptions().CPlusPlus &&
1707 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001708 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001709 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001710 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001711 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001712 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001713 ToType, Context);
1714 return true;
1715 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001716
Fariborz Jahanianbc2ee932011-04-14 20:33:36 +00001717 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1718 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1719 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1720 ToPointeeType,
1721 ToType, Context);
1722 return true;
1723 }
1724
Douglas Gregora119f102008-12-19 19:13:09 +00001725 return false;
1726}
Douglas Gregoraec25842011-04-26 23:16:46 +00001727
1728/// \brief Adopt the given qualifiers for the given type.
1729static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1730 Qualifiers TQs = T.getQualifiers();
1731
1732 // Check whether qualifiers already match.
1733 if (TQs == Qs)
1734 return T;
1735
1736 if (Qs.compatiblyIncludes(TQs))
1737 return Context.getQualifiedType(T, Qs);
1738
1739 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1740}
Douglas Gregora119f102008-12-19 19:13:09 +00001741
1742/// isObjCPointerConversion - Determines whether this is an
1743/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1744/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001745bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001746 QualType& ConvertedType,
1747 bool &IncompatibleObjC) {
1748 if (!getLangOptions().ObjC1)
1749 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001750
Douglas Gregoraec25842011-04-26 23:16:46 +00001751 // The set of qualifiers on the type we're converting from.
1752 Qualifiers FromQualifiers = FromType.getQualifiers();
1753
Steve Naroff7cae42b2009-07-10 23:34:53 +00001754 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001755 const ObjCObjectPointerType* ToObjCPtr =
1756 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001757 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001758 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001759
Steve Naroff7cae42b2009-07-10 23:34:53 +00001760 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001761 // If the pointee types are the same (ignoring qualifications),
1762 // then this is not a pointer conversion.
1763 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1764 FromObjCPtr->getPointeeType()))
1765 return false;
1766
Douglas Gregoraec25842011-04-26 23:16:46 +00001767 // Check for compatible
Steve Naroff1329fa02009-07-15 18:40:39 +00001768 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001769 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001770 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001771 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001772 return true;
1773 }
1774 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001775 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001776 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001777 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001778 /*compare=*/false)) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001779 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001780 return true;
1781 }
1782 // Objective C++: We're able to convert from a pointer to an
1783 // interface to a pointer to a different interface.
1784 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001785 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1786 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1787 if (getLangOptions().CPlusPlus && LHS && RHS &&
1788 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1789 FromObjCPtr->getPointeeType()))
1790 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001791 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001792 ToObjCPtr->getPointeeType(),
1793 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001794 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001795 return true;
1796 }
1797
1798 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1799 // Okay: this is some kind of implicit downcast of Objective-C
1800 // interfaces, which is permitted. However, we're going to
1801 // complain about it.
1802 IncompatibleObjC = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001803 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001804 ToObjCPtr->getPointeeType(),
1805 ToType, Context);
Douglas Gregoraec25842011-04-26 23:16:46 +00001806 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001807 return true;
1808 }
Mike Stump11289f42009-09-09 15:08:12 +00001809 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001810 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001811 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001812 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001813 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001814 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001815 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001816 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001817 // to a block pointer type.
1818 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregoraec25842011-04-26 23:16:46 +00001819 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001820 return true;
1821 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001822 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001823 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001824 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001825 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001826 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001827 // pointer to any object.
Douglas Gregoraec25842011-04-26 23:16:46 +00001828 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001829 return true;
1830 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001831 else
Douglas Gregora119f102008-12-19 19:13:09 +00001832 return false;
1833
Douglas Gregor033f56d2008-12-23 00:53:59 +00001834 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001835 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001836 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001837 else if (const BlockPointerType *FromBlockPtr =
1838 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001839 FromPointeeType = FromBlockPtr->getPointeeType();
1840 else
Douglas Gregora119f102008-12-19 19:13:09 +00001841 return false;
1842
Douglas Gregora119f102008-12-19 19:13:09 +00001843 // If we have pointers to pointers, recursively check whether this
1844 // is an Objective-C conversion.
1845 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1846 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1847 IncompatibleObjC)) {
1848 // We always complain about this conversion.
1849 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001850 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001851 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001852 return true;
1853 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001854 // Allow conversion of pointee being objective-c pointer to another one;
1855 // as in I* to id.
1856 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1857 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1858 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1859 IncompatibleObjC)) {
John McCall31168b02011-06-15 23:02:42 +00001860
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001861 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregoraec25842011-04-26 23:16:46 +00001862 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001863 return true;
1864 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001865
Douglas Gregor033f56d2008-12-23 00:53:59 +00001866 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001867 // differences in the argument and result types are in Objective-C
1868 // pointer conversions. If so, we permit the conversion (but
1869 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001870 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001871 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001872 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001873 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001874 if (FromFunctionType && ToFunctionType) {
1875 // If the function types are exactly the same, this isn't an
1876 // Objective-C pointer conversion.
1877 if (Context.getCanonicalType(FromPointeeType)
1878 == Context.getCanonicalType(ToPointeeType))
1879 return false;
1880
1881 // Perform the quick checks that will tell us whether these
1882 // function types are obviously different.
1883 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1884 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1885 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1886 return false;
1887
1888 bool HasObjCConversion = false;
1889 if (Context.getCanonicalType(FromFunctionType->getResultType())
1890 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1891 // Okay, the types match exactly. Nothing to do.
1892 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1893 ToFunctionType->getResultType(),
1894 ConvertedType, IncompatibleObjC)) {
1895 // Okay, we have an Objective-C pointer conversion.
1896 HasObjCConversion = true;
1897 } else {
1898 // Function types are too different. Abort.
1899 return false;
1900 }
Mike Stump11289f42009-09-09 15:08:12 +00001901
Douglas Gregora119f102008-12-19 19:13:09 +00001902 // Check argument types.
1903 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1904 ArgIdx != NumArgs; ++ArgIdx) {
1905 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1906 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1907 if (Context.getCanonicalType(FromArgType)
1908 == Context.getCanonicalType(ToArgType)) {
1909 // Okay, the types match exactly. Nothing to do.
1910 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1911 ConvertedType, IncompatibleObjC)) {
1912 // Okay, we have an Objective-C pointer conversion.
1913 HasObjCConversion = true;
1914 } else {
1915 // Argument types are too different. Abort.
1916 return false;
1917 }
1918 }
1919
1920 if (HasObjCConversion) {
1921 // We had an Objective-C conversion. Allow this pointer
1922 // conversion, but complain about it.
Douglas Gregoraec25842011-04-26 23:16:46 +00001923 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregora119f102008-12-19 19:13:09 +00001924 IncompatibleObjC = true;
1925 return true;
1926 }
1927 }
1928
Sebastian Redl72b597d2009-01-25 19:43:20 +00001929 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001930}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00001931
John McCall31168b02011-06-15 23:02:42 +00001932/// \brief Determine whether this is an Objective-C writeback conversion,
1933/// used for parameter passing when performing automatic reference counting.
1934///
1935/// \param FromType The type we're converting form.
1936///
1937/// \param ToType The type we're converting to.
1938///
1939/// \param ConvertedType The type that will be produced after applying
1940/// this conversion.
1941bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
1942 QualType &ConvertedType) {
1943 if (!getLangOptions().ObjCAutoRefCount ||
1944 Context.hasSameUnqualifiedType(FromType, ToType))
1945 return false;
1946
1947 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
1948 QualType ToPointee;
1949 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
1950 ToPointee = ToPointer->getPointeeType();
1951 else
1952 return false;
1953
1954 Qualifiers ToQuals = ToPointee.getQualifiers();
1955 if (!ToPointee->isObjCLifetimeType() ||
1956 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
1957 !ToQuals.withoutObjCGLifetime().empty())
1958 return false;
1959
1960 // Argument must be a pointer to __strong to __weak.
1961 QualType FromPointee;
1962 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
1963 FromPointee = FromPointer->getPointeeType();
1964 else
1965 return false;
1966
1967 Qualifiers FromQuals = FromPointee.getQualifiers();
1968 if (!FromPointee->isObjCLifetimeType() ||
1969 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
1970 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
1971 return false;
1972
1973 // Make sure that we have compatible qualifiers.
1974 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
1975 if (!ToQuals.compatiblyIncludes(FromQuals))
1976 return false;
1977
1978 // Remove qualifiers from the pointee type we're converting from; they
1979 // aren't used in the compatibility check belong, and we'll be adding back
1980 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
1981 FromPointee = FromPointee.getUnqualifiedType();
1982
1983 // The unqualified form of the pointee types must be compatible.
1984 ToPointee = ToPointee.getUnqualifiedType();
1985 bool IncompatibleObjC;
1986 if (Context.typesAreCompatible(FromPointee, ToPointee))
1987 FromPointee = ToPointee;
1988 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
1989 IncompatibleObjC))
1990 return false;
1991
1992 /// \brief Construct the type we're converting to, which is a pointer to
1993 /// __autoreleasing pointee.
1994 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
1995 ConvertedType = Context.getPointerType(FromPointee);
1996 return true;
1997}
1998
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00001999bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2000 QualType& ConvertedType) {
2001 QualType ToPointeeType;
2002 if (const BlockPointerType *ToBlockPtr =
2003 ToType->getAs<BlockPointerType>())
2004 ToPointeeType = ToBlockPtr->getPointeeType();
2005 else
2006 return false;
2007
2008 QualType FromPointeeType;
2009 if (const BlockPointerType *FromBlockPtr =
2010 FromType->getAs<BlockPointerType>())
2011 FromPointeeType = FromBlockPtr->getPointeeType();
2012 else
2013 return false;
2014 // We have pointer to blocks, check whether the only
2015 // differences in the argument and result types are in Objective-C
2016 // pointer conversions. If so, we permit the conversion.
2017
2018 const FunctionProtoType *FromFunctionType
2019 = FromPointeeType->getAs<FunctionProtoType>();
2020 const FunctionProtoType *ToFunctionType
2021 = ToPointeeType->getAs<FunctionProtoType>();
2022
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002023 if (!FromFunctionType || !ToFunctionType)
2024 return false;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002025
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002026 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002027 return true;
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002028
2029 // Perform the quick checks that will tell us whether these
2030 // function types are obviously different.
2031 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2032 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2033 return false;
2034
2035 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2036 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2037 if (FromEInfo != ToEInfo)
2038 return false;
2039
2040 bool IncompatibleObjC = false;
Fariborz Jahanian12834e12011-02-13 20:11:42 +00002041 if (Context.hasSameType(FromFunctionType->getResultType(),
2042 ToFunctionType->getResultType())) {
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002043 // Okay, the types match exactly. Nothing to do.
2044 } else {
2045 QualType RHS = FromFunctionType->getResultType();
2046 QualType LHS = ToFunctionType->getResultType();
2047 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2048 !RHS.hasQualifiers() && LHS.hasQualifiers())
2049 LHS = LHS.getUnqualifiedType();
2050
2051 if (Context.hasSameType(RHS,LHS)) {
2052 // OK exact match.
2053 } else if (isObjCPointerConversion(RHS, LHS,
2054 ConvertedType, IncompatibleObjC)) {
2055 if (IncompatibleObjC)
2056 return false;
2057 // Okay, we have an Objective-C pointer conversion.
2058 }
2059 else
2060 return false;
2061 }
2062
2063 // Check argument types.
2064 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2065 ArgIdx != NumArgs; ++ArgIdx) {
2066 IncompatibleObjC = false;
2067 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2068 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2069 if (Context.hasSameType(FromArgType, ToArgType)) {
2070 // Okay, the types match exactly. Nothing to do.
2071 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2072 ConvertedType, IncompatibleObjC)) {
2073 if (IncompatibleObjC)
2074 return false;
2075 // Okay, we have an Objective-C pointer conversion.
2076 } else
2077 // Argument types are too different. Abort.
2078 return false;
2079 }
Fariborz Jahanian97676972011-09-28 21:52:05 +00002080 if (LangOpts.ObjCAutoRefCount &&
2081 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2082 ToFunctionType))
2083 return false;
Fariborz Jahanian600ba202011-09-28 20:22:05 +00002084
Fariborz Jahanian4de45dc2011-02-13 20:01:48 +00002085 ConvertedType = ToType;
2086 return true;
Fariborz Jahanian42455ea2011-02-12 19:07:46 +00002087}
2088
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002089/// FunctionArgTypesAreEqual - This routine checks two function proto types
2090/// for equlity of their argument types. Caller has already checked that
2091/// they have same number of arguments. This routine assumes that Objective-C
2092/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002093bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCall424cec92011-01-19 06:33:43 +00002094 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002095 if (!getLangOptions().ObjC1)
2096 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2097 NewType->arg_type_begin());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002098
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002099 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2100 N = NewType->arg_type_begin(),
2101 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2102 QualType ToType = (*O);
2103 QualType FromType = (*N);
2104 if (ToType != FromType) {
2105 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2106 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00002107 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2108 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2109 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2110 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002111 continue;
2112 }
John McCall8b07ec22010-05-15 11:32:37 +00002113 else if (const ObjCObjectPointerType *PTTo =
2114 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002115 if (const ObjCObjectPointerType *PTFr =
John McCall8b07ec22010-05-15 11:32:37 +00002116 FromType->getAs<ObjCObjectPointerType>())
2117 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2118 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002119 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002120 return false;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00002121 }
2122 }
2123 return true;
2124}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002125
Douglas Gregor39c16d42008-10-24 04:54:22 +00002126/// CheckPointerConversion - Check the pointer conversion from the
2127/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00002128/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00002129/// conversions for which IsPointerConversion has already returned
2130/// true. It returns true and produces a diagnostic if there was an
2131/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002132bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002133 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002134 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002135 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002136 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00002137 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002138
John McCall8cb679e2010-11-15 09:13:47 +00002139 Kind = CK_BitCast;
2140
Chandler Carruthffab8732011-04-09 07:32:05 +00002141 if (!IsCStyleOrFunctionalCast &&
2142 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2143 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2144 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruth66a7b042011-04-09 07:48:17 +00002145 PDiag(diag::warn_impcast_bool_to_null_pointer)
2146 << ToType << From->getSourceRange());
Douglas Gregor4038cf42010-06-08 17:35:15 +00002147
John McCall9320b872011-09-09 05:25:32 +00002148 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2149 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002150 QualType FromPointeeType = FromPtrType->getPointeeType(),
2151 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00002152
Douglas Gregorcc3f3252010-03-03 23:55:11 +00002153 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2154 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00002155 // We must have a derived-to-base conversion. Check an
2156 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002157 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2158 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00002159 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002160 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002161 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002162
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00002163 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00002164 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00002165 }
2166 }
John McCall9320b872011-09-09 05:25:32 +00002167 } else if (const ObjCObjectPointerType *ToPtrType =
2168 ToType->getAs<ObjCObjectPointerType>()) {
2169 if (const ObjCObjectPointerType *FromPtrType =
2170 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00002171 // Objective-C++ conversions are always okay.
2172 // FIXME: We should have a different class of conversions for the
2173 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00002174 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00002175 return false;
John McCall9320b872011-09-09 05:25:32 +00002176 } else if (FromType->isBlockPointerType()) {
2177 Kind = CK_BlockPointerToObjCPointerCast;
2178 } else {
2179 Kind = CK_CPointerToObjCPointerCast;
John McCall8cb679e2010-11-15 09:13:47 +00002180 }
John McCall9320b872011-09-09 05:25:32 +00002181 } else if (ToType->isBlockPointerType()) {
2182 if (!FromType->isBlockPointerType())
2183 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff7cae42b2009-07-10 23:34:53 +00002184 }
John McCall8cb679e2010-11-15 09:13:47 +00002185
2186 // We shouldn't fall into this case unless it's valid for other
2187 // reasons.
2188 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2189 Kind = CK_NullToPointer;
2190
Douglas Gregor39c16d42008-10-24 04:54:22 +00002191 return false;
2192}
2193
Sebastian Redl72b597d2009-01-25 19:43:20 +00002194/// IsMemberPointerConversion - Determines whether the conversion of the
2195/// expression From, which has the (possibly adjusted) type FromType, can be
2196/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2197/// If so, returns true and places the converted type (that might differ from
2198/// ToType in its cv-qualifiers at some level) into ConvertedType.
2199bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002200 QualType ToType,
Douglas Gregor56751b52009-09-25 04:25:58 +00002201 bool InOverloadResolution,
2202 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002203 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002204 if (!ToTypePtr)
2205 return false;
2206
2207 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00002208 if (From->isNullPointerConstant(Context,
2209 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2210 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002211 ConvertedType = ToType;
2212 return true;
2213 }
2214
2215 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002216 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00002217 if (!FromTypePtr)
2218 return false;
2219
2220 // A pointer to member of B can be converted to a pointer to member of D,
2221 // where D is derived from B (C++ 4.11p2).
2222 QualType FromClass(FromTypePtr->getClass(), 0);
2223 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002224
Douglas Gregor7f6ae692010-12-21 21:40:41 +00002225 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2226 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2227 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002228 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2229 ToClass.getTypePtr());
2230 return true;
2231 }
2232
2233 return false;
2234}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002235
Sebastian Redl72b597d2009-01-25 19:43:20 +00002236/// CheckMemberPointerConversion - Check the member pointer conversion from the
2237/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00002238/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00002239/// for which IsMemberPointerConversion has already returned true. It returns
2240/// true and produces a diagnostic if there was an error, or returns false
2241/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00002242bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00002243 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00002244 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00002245 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00002246 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002247 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00002248 if (!FromPtrType) {
2249 // This must be a null pointer to member pointer conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002250 assert(From->isNullPointerConstant(Context,
Douglas Gregor56751b52009-09-25 04:25:58 +00002251 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00002252 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00002253 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00002254 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00002255 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00002256
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002257 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00002258 assert(ToPtrType && "No member pointer cast has a target type "
2259 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002260
Sebastian Redled8f2002009-01-28 18:33:18 +00002261 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2262 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00002263
Sebastian Redled8f2002009-01-28 18:33:18 +00002264 // FIXME: What about dependent types?
2265 assert(FromClass->isRecordType() && "Pointer into non-class.");
2266 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00002267
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002268 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00002269 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00002270 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2271 assert(DerivationOkay &&
2272 "Should not have been called if derivation isn't OK.");
2273 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002274
Sebastian Redled8f2002009-01-28 18:33:18 +00002275 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2276 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002277 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2278 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2279 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2280 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002281 }
Sebastian Redled8f2002009-01-28 18:33:18 +00002282
Douglas Gregor89ee6822009-02-28 01:32:25 +00002283 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00002284 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2285 << FromClass << ToClass << QualType(VBase, 0)
2286 << From->getSourceRange();
2287 return true;
2288 }
2289
John McCall5b0829a2010-02-10 09:31:12 +00002290 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00002291 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2292 Paths.front(),
2293 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00002294
Anders Carlssond7923c62009-08-22 23:33:40 +00002295 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00002296 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00002297 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00002298 return false;
2299}
2300
Douglas Gregor9a657932008-10-21 23:43:52 +00002301/// IsQualificationConversion - Determines whether the conversion from
2302/// an rvalue of type FromType to ToType is a qualification conversion
2303/// (C++ 4.4).
John McCall31168b02011-06-15 23:02:42 +00002304///
2305/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2306/// when the qualification conversion involves a change in the Objective-C
2307/// object lifetime.
Mike Stump11289f42009-09-09 15:08:12 +00002308bool
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002309Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCall31168b02011-06-15 23:02:42 +00002310 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002311 FromType = Context.getCanonicalType(FromType);
2312 ToType = Context.getCanonicalType(ToType);
John McCall31168b02011-06-15 23:02:42 +00002313 ObjCLifetimeConversion = false;
2314
Douglas Gregor9a657932008-10-21 23:43:52 +00002315 // If FromType and ToType are the same type, this is not a
2316 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00002317 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00002318 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00002319
Douglas Gregor9a657932008-10-21 23:43:52 +00002320 // (C++ 4.4p4):
2321 // A conversion can add cv-qualifiers at levels other than the first
2322 // in multi-level pointers, subject to the following rules: [...]
2323 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002324 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002325 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00002326 // Within each iteration of the loop, we check the qualifiers to
2327 // determine if this still looks like a qualification
2328 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002329 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00002330 // until there are no more pointers or pointers-to-members left to
2331 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002332 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00002333
Douglas Gregor90609aa2011-04-25 18:40:17 +00002334 Qualifiers FromQuals = FromType.getQualifiers();
2335 Qualifiers ToQuals = ToType.getQualifiers();
2336
John McCall31168b02011-06-15 23:02:42 +00002337 // Objective-C ARC:
2338 // Check Objective-C lifetime conversions.
2339 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2340 UnwrappedAnyPointer) {
2341 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2342 ObjCLifetimeConversion = true;
2343 FromQuals.removeObjCLifetime();
2344 ToQuals.removeObjCLifetime();
2345 } else {
2346 // Qualification conversions cannot cast between different
2347 // Objective-C lifetime qualifiers.
2348 return false;
2349 }
2350 }
2351
Douglas Gregorf30053d2011-05-08 06:09:53 +00002352 // Allow addition/removal of GC attributes but not changing GC attributes.
2353 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2354 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2355 FromQuals.removeObjCGCAttr();
2356 ToQuals.removeObjCGCAttr();
2357 }
2358
Douglas Gregor9a657932008-10-21 23:43:52 +00002359 // -- for every j > 0, if const is in cv 1,j then const is in cv
2360 // 2,j, and similarly for volatile.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002361 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor9a657932008-10-21 23:43:52 +00002362 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002363
Douglas Gregor9a657932008-10-21 23:43:52 +00002364 // -- if the cv 1,j and cv 2,j are different, then const is in
2365 // every cv for 0 < k < j.
Douglas Gregor90609aa2011-04-25 18:40:17 +00002366 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002367 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00002368 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002369
Douglas Gregor9a657932008-10-21 23:43:52 +00002370 // Keep track of whether all prior cv-qualifiers in the "to" type
2371 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002372 PreviousToQualsIncludeConst
Douglas Gregor90609aa2011-04-25 18:40:17 +00002373 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002374 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002375
2376 // We are left with FromType and ToType being the pointee types
2377 // after unwrapping the original FromType and ToType the same number
2378 // of types. If we unwrapped any pointers, and if FromType and
2379 // ToType have the same unqualified type (since we checked
2380 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002381 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002382}
2383
Douglas Gregor576e98c2009-01-30 23:27:23 +00002384/// Determines whether there is a user-defined conversion sequence
2385/// (C++ [over.ics.user]) that converts expression From to the type
2386/// ToType. If such a conversion exists, User will contain the
2387/// user-defined conversion sequence that performs such a conversion
2388/// and this routine will return true. Otherwise, this routine returns
2389/// false and User is unspecified.
2390///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002391/// \param AllowExplicit true if the conversion should consider C++0x
2392/// "explicit" conversion functions as well as non-explicit conversion
2393/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002394static OverloadingResult
2395IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2396 UserDefinedConversionSequence& User,
2397 OverloadCandidateSet& CandidateSet,
2398 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002399 // Whether we will only visit constructors.
2400 bool ConstructorsOnly = false;
2401
2402 // If the type we are conversion to is a class type, enumerate its
2403 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002404 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002405 // C++ [over.match.ctor]p1:
2406 // When objects of class type are direct-initialized (8.5), or
2407 // copy-initialized from an expression of the same or a
2408 // derived class type (8.5), overload resolution selects the
2409 // constructor. [...] For copy-initialization, the candidate
2410 // functions are all the converting constructors (12.3.1) of
2411 // that class. The argument list is the expression-list within
2412 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002413 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002414 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002415 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002416 ConstructorsOnly = true;
2417
Argyrios Kyrtzidis7a6f2a32011-04-22 17:45:37 +00002418 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2419 // RequireCompleteType may have returned true due to some invalid decl
2420 // during template instantiation, but ToType may be complete enough now
2421 // to try to recover.
2422 if (ToType->isIncompleteType()) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002423 // We're not going to find any constructors.
2424 } else if (CXXRecordDecl *ToRecordDecl
2425 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002426 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002427 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002428 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002429 NamedDecl *D = *Con;
2430 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2431
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002432 // Find the constructor (which may be a template).
2433 CXXConstructorDecl *Constructor = 0;
2434 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002435 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002436 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002437 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002438 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2439 else
John McCalla0296f72010-03-19 07:35:19 +00002440 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002441
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002442 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002443 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002444 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002445 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2446 /*ExplicitArgs*/ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002447 &From, 1, CandidateSet,
John McCall5c32be02010-08-24 20:38:10 +00002448 /*SuppressUserConversions=*/
2449 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002450 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002451 // Allow one user-defined conversion when user specifies a
2452 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002453 S.AddOverloadCandidate(Constructor, FoundDecl,
2454 &From, 1, CandidateSet,
2455 /*SuppressUserConversions=*/
2456 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002457 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002458 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002459 }
2460 }
2461
Douglas Gregor5ab11652010-04-17 22:01:05 +00002462 // Enumerate conversion functions, if we're allowed to.
2463 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002464 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2465 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002466 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002467 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002468 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002469 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002470 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2471 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002472 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002473 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002474 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002475 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002476 DeclAccessPair FoundDecl = I.getPair();
2477 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002478 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2479 if (isa<UsingShadowDecl>(D))
2480 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2481
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002482 CXXConversionDecl *Conv;
2483 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002484 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2485 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002486 else
John McCallda4458e2010-03-31 01:36:47 +00002487 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002488
2489 if (AllowExplicit || !Conv->isExplicit()) {
2490 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002491 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2492 ActingContext, From, ToType,
2493 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002494 else
John McCall5c32be02010-08-24 20:38:10 +00002495 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2496 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002497 }
2498 }
2499 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002500 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002501
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002502 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2503
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002504 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002505 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002506 case OR_Success:
2507 // Record the standard conversion we used and the conversion function.
2508 if (CXXConstructorDecl *Constructor
2509 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002510 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2511
John McCall5c32be02010-08-24 20:38:10 +00002512 // C++ [over.ics.user]p1:
2513 // If the user-defined conversion is specified by a
2514 // constructor (12.3.1), the initial standard conversion
2515 // sequence converts the source type to the type required by
2516 // the argument of the constructor.
2517 //
2518 QualType ThisType = Constructor->getThisType(S.Context);
2519 if (Best->Conversions[0].isEllipsis())
2520 User.EllipsisConversion = true;
2521 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002522 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002523 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002524 }
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002525 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002526 User.ConversionFunction = Constructor;
John McCall30909032011-09-21 08:36:56 +00002527 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002528 User.After.setAsIdentityConversion();
2529 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2530 User.After.setAllToTypes(ToType);
2531 return OR_Success;
2532 } else if (CXXConversionDecl *Conversion
2533 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth30141632011-02-25 19:41:05 +00002534 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2535
John McCall5c32be02010-08-24 20:38:10 +00002536 // C++ [over.ics.user]p1:
2537 //
2538 // [...] If the user-defined conversion is specified by a
2539 // conversion function (12.3.2), the initial standard
2540 // conversion sequence converts the source type to the
2541 // implicit object parameter of the conversion function.
2542 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00002543 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall5c32be02010-08-24 20:38:10 +00002544 User.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00002545 User.FoundConversionFunction = Best->FoundDecl;
John McCall5c32be02010-08-24 20:38:10 +00002546 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002547
John McCall5c32be02010-08-24 20:38:10 +00002548 // C++ [over.ics.user]p2:
2549 // The second standard conversion sequence converts the
2550 // result of the user-defined conversion to the target type
2551 // for the sequence. Since an implicit conversion sequence
2552 // is an initialization, the special rules for
2553 // initialization by user-defined conversion apply when
2554 // selecting the best user-defined conversion for a
2555 // user-defined conversion sequence (see 13.3.3 and
2556 // 13.3.3.1).
2557 User.After = Best->FinalConversion;
2558 return OR_Success;
2559 } else {
2560 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002561 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002562 }
2563
John McCall5c32be02010-08-24 20:38:10 +00002564 case OR_No_Viable_Function:
2565 return OR_No_Viable_Function;
2566 case OR_Deleted:
2567 // No conversion here! We're done.
2568 return OR_Deleted;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002569
John McCall5c32be02010-08-24 20:38:10 +00002570 case OR_Ambiguous:
2571 return OR_Ambiguous;
2572 }
2573
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002574 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002575}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002576
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002577bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002578Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002579 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002580 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002581 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002582 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002583 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002584 if (OvResult == OR_Ambiguous)
2585 Diag(From->getSourceRange().getBegin(),
2586 diag::err_typecheck_ambiguous_condition)
2587 << From->getType() << ToType << From->getSourceRange();
2588 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2589 Diag(From->getSourceRange().getBegin(),
2590 diag::err_typecheck_nonviable_condition)
2591 << From->getType() << ToType << From->getSourceRange();
2592 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002593 return false;
John McCall5c32be02010-08-24 20:38:10 +00002594 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002595 return true;
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002596}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002597
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002598/// CompareImplicitConversionSequences - Compare two implicit
2599/// conversion sequences to determine whether one is better than the
2600/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002601static ImplicitConversionSequence::CompareKind
2602CompareImplicitConversionSequences(Sema &S,
2603 const ImplicitConversionSequence& ICS1,
2604 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002605{
2606 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2607 // conversion sequences (as defined in 13.3.3.1)
2608 // -- a standard conversion sequence (13.3.3.1.1) is a better
2609 // conversion sequence than a user-defined conversion sequence or
2610 // an ellipsis conversion sequence, and
2611 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2612 // conversion sequence than an ellipsis conversion sequence
2613 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002614 //
John McCall0d1da222010-01-12 00:44:57 +00002615 // C++0x [over.best.ics]p10:
2616 // For the purpose of ranking implicit conversion sequences as
2617 // described in 13.3.3.2, the ambiguous conversion sequence is
2618 // treated as a user-defined sequence that is indistinguishable
2619 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002620 if (ICS1.getKindRank() < ICS2.getKindRank())
2621 return ImplicitConversionSequence::Better;
2622 else if (ICS2.getKindRank() < ICS1.getKindRank())
2623 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002624
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002625 // The following checks require both conversion sequences to be of
2626 // the same kind.
2627 if (ICS1.getKind() != ICS2.getKind())
2628 return ImplicitConversionSequence::Indistinguishable;
2629
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002630 // Two implicit conversion sequences of the same form are
2631 // indistinguishable conversion sequences unless one of the
2632 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002633 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002634 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002635 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002636 // User-defined conversion sequence U1 is a better conversion
2637 // sequence than another user-defined conversion sequence U2 if
2638 // they contain the same user-defined conversion function or
2639 // constructor and if the second standard conversion sequence of
2640 // U1 is better than the second standard conversion sequence of
2641 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002642 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002643 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002644 return CompareStandardConversionSequences(S,
2645 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002646 ICS2.UserDefined.After);
2647 }
2648
2649 return ImplicitConversionSequence::Indistinguishable;
2650}
2651
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002652static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2653 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2654 Qualifiers Quals;
2655 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002656 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002657 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002658
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002659 return Context.hasSameUnqualifiedType(T1, T2);
2660}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002661
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002662// Per 13.3.3.2p3, compare the given standard conversion sequences to
2663// determine if one is a proper subset of the other.
2664static ImplicitConversionSequence::CompareKind
2665compareStandardConversionSubsets(ASTContext &Context,
2666 const StandardConversionSequence& SCS1,
2667 const StandardConversionSequence& SCS2) {
2668 ImplicitConversionSequence::CompareKind Result
2669 = ImplicitConversionSequence::Indistinguishable;
2670
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002671 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregore87561a2010-05-23 22:10:15 +00002672 // any non-identity conversion sequence
Douglas Gregor377c1092011-06-05 06:15:20 +00002673 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2674 return ImplicitConversionSequence::Better;
2675 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2676 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002677
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002678 if (SCS1.Second != SCS2.Second) {
2679 if (SCS1.Second == ICK_Identity)
2680 Result = ImplicitConversionSequence::Better;
2681 else if (SCS2.Second == ICK_Identity)
2682 Result = ImplicitConversionSequence::Worse;
2683 else
2684 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002685 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002686 return ImplicitConversionSequence::Indistinguishable;
2687
2688 if (SCS1.Third == SCS2.Third) {
2689 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2690 : ImplicitConversionSequence::Indistinguishable;
2691 }
2692
2693 if (SCS1.Third == ICK_Identity)
2694 return Result == ImplicitConversionSequence::Worse
2695 ? ImplicitConversionSequence::Indistinguishable
2696 : ImplicitConversionSequence::Better;
2697
2698 if (SCS2.Third == ICK_Identity)
2699 return Result == ImplicitConversionSequence::Better
2700 ? ImplicitConversionSequence::Indistinguishable
2701 : ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002702
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002703 return ImplicitConversionSequence::Indistinguishable;
2704}
2705
Douglas Gregore696ebb2011-01-26 14:52:12 +00002706/// \brief Determine whether one of the given reference bindings is better
2707/// than the other based on what kind of bindings they are.
2708static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2709 const StandardConversionSequence &SCS2) {
2710 // C++0x [over.ics.rank]p3b4:
2711 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2712 // implicit object parameter of a non-static member function declared
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002713 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregore696ebb2011-01-26 14:52:12 +00002714 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002715 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregore696ebb2011-01-26 14:52:12 +00002716 // reference*.
2717 //
2718 // FIXME: Rvalue references. We're going rogue with the above edits,
2719 // because the semantics in the current C++0x working paper (N3225 at the
2720 // time of this writing) break the standard definition of std::forward
2721 // and std::reference_wrapper when dealing with references to functions.
2722 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregore1a47c12011-01-26 19:41:18 +00002723 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2724 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2725 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002726
Douglas Gregore696ebb2011-01-26 14:52:12 +00002727 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2728 SCS2.IsLvalueReference) ||
2729 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2730 !SCS2.IsLvalueReference);
2731}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002732
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002733/// CompareStandardConversionSequences - Compare two standard
2734/// conversion sequences to determine whether one is better than the
2735/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002736static ImplicitConversionSequence::CompareKind
2737CompareStandardConversionSequences(Sema &S,
2738 const StandardConversionSequence& SCS1,
2739 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002740{
2741 // Standard conversion sequence S1 is a better conversion sequence
2742 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2743
2744 // -- S1 is a proper subsequence of S2 (comparing the conversion
2745 // sequences in the canonical form defined by 13.3.3.1.1,
2746 // excluding any Lvalue Transformation; the identity conversion
2747 // sequence is considered to be a subsequence of any
2748 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002749 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002750 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002751 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002752
2753 // -- the rank of S1 is better than the rank of S2 (by the rules
2754 // defined below), or, if not that,
2755 ImplicitConversionRank Rank1 = SCS1.getRank();
2756 ImplicitConversionRank Rank2 = SCS2.getRank();
2757 if (Rank1 < Rank2)
2758 return ImplicitConversionSequence::Better;
2759 else if (Rank2 < Rank1)
2760 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002761
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002762 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2763 // are indistinguishable unless one of the following rules
2764 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002765
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002766 // A conversion that is not a conversion of a pointer, or
2767 // pointer to member, to bool is better than another conversion
2768 // that is such a conversion.
2769 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2770 return SCS2.isPointerConversionToBool()
2771 ? ImplicitConversionSequence::Better
2772 : ImplicitConversionSequence::Worse;
2773
Douglas Gregor5c407d92008-10-23 00:40:37 +00002774 // C++ [over.ics.rank]p4b2:
2775 //
2776 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002777 // conversion of B* to A* is better than conversion of B* to
2778 // void*, and conversion of A* to void* is better than conversion
2779 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002780 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002781 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002782 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002783 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002784 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2785 // Exactly one of the conversion sequences is a conversion to
2786 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002787 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2788 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002789 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2790 // Neither conversion sequence converts to a void pointer; compare
2791 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002792 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002793 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002794 return DerivedCK;
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002795 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2796 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002797 // Both conversion sequences are conversions to void
2798 // pointers. Compare the source types to determine if there's an
2799 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002800 QualType FromType1 = SCS1.getFromType();
2801 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002802
2803 // Adjust the types we're converting from via the array-to-pointer
2804 // conversion, if we need to.
2805 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002806 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002807 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002808 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002809
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002810 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2811 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002812
John McCall5c32be02010-08-24 20:38:10 +00002813 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002814 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002815 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002816 return ImplicitConversionSequence::Worse;
2817
2818 // Objective-C++: If one interface is more specific than the
2819 // other, it is the better one.
Douglas Gregor30ee16f2011-04-27 00:01:52 +00002820 const ObjCObjectPointerType* FromObjCPtr1
2821 = FromType1->getAs<ObjCObjectPointerType>();
2822 const ObjCObjectPointerType* FromObjCPtr2
2823 = FromType2->getAs<ObjCObjectPointerType>();
2824 if (FromObjCPtr1 && FromObjCPtr2) {
2825 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2826 FromObjCPtr2);
2827 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2828 FromObjCPtr1);
2829 if (AssignLeft != AssignRight) {
2830 return AssignLeft? ImplicitConversionSequence::Better
2831 : ImplicitConversionSequence::Worse;
2832 }
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002833 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002834 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002835
2836 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2837 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002838 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002839 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002840 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002841
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002842 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregore696ebb2011-01-26 14:52:12 +00002843 // Check for a better reference binding based on the kind of bindings.
2844 if (isBetterReferenceBindingKind(SCS1, SCS2))
2845 return ImplicitConversionSequence::Better;
2846 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2847 return ImplicitConversionSequence::Worse;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00002848
Sebastian Redlb28b4072009-03-22 23:49:27 +00002849 // C++ [over.ics.rank]p3b4:
2850 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2851 // which the references refer are the same type except for
2852 // top-level cv-qualifiers, and the type to which the reference
2853 // initialized by S2 refers is more cv-qualified than the type
2854 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002855 QualType T1 = SCS1.getToType(2);
2856 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002857 T1 = S.Context.getCanonicalType(T1);
2858 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002859 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002860 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2861 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002862 if (UnqualT1 == UnqualT2) {
John McCall31168b02011-06-15 23:02:42 +00002863 // Objective-C++ ARC: If the references refer to objects with different
2864 // lifetimes, prefer bindings that don't change lifetime.
2865 if (SCS1.ObjCLifetimeConversionBinding !=
2866 SCS2.ObjCLifetimeConversionBinding) {
2867 return SCS1.ObjCLifetimeConversionBinding
2868 ? ImplicitConversionSequence::Worse
2869 : ImplicitConversionSequence::Better;
2870 }
2871
Chandler Carruth8e543b32010-12-12 08:17:55 +00002872 // If the type is an array type, promote the element qualifiers to the
2873 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002874 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002875 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002876 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002877 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002878 if (T2.isMoreQualifiedThan(T1))
2879 return ImplicitConversionSequence::Better;
2880 else if (T1.isMoreQualifiedThan(T2))
John McCall31168b02011-06-15 23:02:42 +00002881 return ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002882 }
2883 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002884
Francois Pichet08d2fa02011-09-18 21:37:37 +00002885 // In Microsoft mode, prefer an integral conversion to a
2886 // floating-to-integral conversion if the integral conversion
2887 // is between types of the same size.
2888 // For example:
2889 // void f(float);
2890 // void f(int);
2891 // int main {
2892 // long a;
2893 // f(a);
2894 // }
2895 // Here, MSVC will call f(int) instead of generating a compile error
2896 // as clang will do in standard mode.
2897 if (S.getLangOptions().MicrosoftMode &&
2898 SCS1.Second == ICK_Integral_Conversion &&
2899 SCS2.Second == ICK_Floating_Integral &&
2900 S.Context.getTypeSize(SCS1.getFromType()) ==
2901 S.Context.getTypeSize(SCS1.getToType(2)))
2902 return ImplicitConversionSequence::Better;
2903
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002904 return ImplicitConversionSequence::Indistinguishable;
2905}
2906
2907/// CompareQualificationConversions - Compares two standard conversion
2908/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002909/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2910ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002911CompareQualificationConversions(Sema &S,
2912 const StandardConversionSequence& SCS1,
2913 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002914 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002915 // -- S1 and S2 differ only in their qualification conversion and
2916 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2917 // cv-qualification signature of type T1 is a proper subset of
2918 // the cv-qualification signature of type T2, and S1 is not the
2919 // deprecated string literal array-to-pointer conversion (4.2).
2920 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2921 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2922 return ImplicitConversionSequence::Indistinguishable;
2923
2924 // FIXME: the example in the standard doesn't use a qualification
2925 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002926 QualType T1 = SCS1.getToType(2);
2927 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002928 T1 = S.Context.getCanonicalType(T1);
2929 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002930 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002931 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2932 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002933
2934 // If the types are the same, we won't learn anything by unwrapped
2935 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002936 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002937 return ImplicitConversionSequence::Indistinguishable;
2938
Chandler Carruth607f38e2009-12-29 07:16:59 +00002939 // If the type is an array type, promote the element qualifiers to the type
2940 // for comparison.
2941 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002942 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002943 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002944 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002945
Mike Stump11289f42009-09-09 15:08:12 +00002946 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002947 = ImplicitConversionSequence::Indistinguishable;
John McCall31168b02011-06-15 23:02:42 +00002948
2949 // Objective-C++ ARC:
2950 // Prefer qualification conversions not involving a change in lifetime
2951 // to qualification conversions that do not change lifetime.
2952 if (SCS1.QualificationIncludesObjCLifetime !=
2953 SCS2.QualificationIncludesObjCLifetime) {
2954 Result = SCS1.QualificationIncludesObjCLifetime
2955 ? ImplicitConversionSequence::Worse
2956 : ImplicitConversionSequence::Better;
2957 }
2958
John McCall5c32be02010-08-24 20:38:10 +00002959 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002960 // Within each iteration of the loop, we check the qualifiers to
2961 // determine if this still looks like a qualification
2962 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002963 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002964 // until there are no more pointers or pointers-to-members left
2965 // to unwrap. This essentially mimics what
2966 // IsQualificationConversion does, but here we're checking for a
2967 // strict subset of qualifiers.
2968 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2969 // The qualifiers are the same, so this doesn't tell us anything
2970 // about how the sequences rank.
2971 ;
2972 else if (T2.isMoreQualifiedThan(T1)) {
2973 // T1 has fewer qualifiers, so it could be the better sequence.
2974 if (Result == ImplicitConversionSequence::Worse)
2975 // Neither has qualifiers that are a subset of the other's
2976 // qualifiers.
2977 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002978
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002979 Result = ImplicitConversionSequence::Better;
2980 } else if (T1.isMoreQualifiedThan(T2)) {
2981 // T2 has fewer qualifiers, so it could be the better sequence.
2982 if (Result == ImplicitConversionSequence::Better)
2983 // Neither has qualifiers that are a subset of the other's
2984 // qualifiers.
2985 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002986
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002987 Result = ImplicitConversionSequence::Worse;
2988 } else {
2989 // Qualifiers are disjoint.
2990 return ImplicitConversionSequence::Indistinguishable;
2991 }
2992
2993 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002994 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002995 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002996 }
2997
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002998 // Check that the winning standard conversion sequence isn't using
2999 // the deprecated string literal array to pointer conversion.
3000 switch (Result) {
3001 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003002 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003003 Result = ImplicitConversionSequence::Indistinguishable;
3004 break;
3005
3006 case ImplicitConversionSequence::Indistinguishable:
3007 break;
3008
3009 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00003010 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00003011 Result = ImplicitConversionSequence::Indistinguishable;
3012 break;
3013 }
3014
3015 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003016}
3017
Douglas Gregor5c407d92008-10-23 00:40:37 +00003018/// CompareDerivedToBaseConversions - Compares two standard conversion
3019/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00003020/// various kinds of derived-to-base conversions (C++
3021/// [over.ics.rank]p4b3). As part of these checks, we also look at
3022/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00003023ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00003024CompareDerivedToBaseConversions(Sema &S,
3025 const StandardConversionSequence& SCS1,
3026 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00003027 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003028 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00003029 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003030 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003031
3032 // Adjust the types we're converting from via the array-to-pointer
3033 // conversion, if we need to.
3034 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003035 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003036 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00003037 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003038
3039 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00003040 FromType1 = S.Context.getCanonicalType(FromType1);
3041 ToType1 = S.Context.getCanonicalType(ToType1);
3042 FromType2 = S.Context.getCanonicalType(FromType2);
3043 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00003044
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003045 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00003046 //
3047 // If class B is derived directly or indirectly from class A and
3048 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00003049 //
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003050 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00003051 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00003052 SCS2.Second == ICK_Pointer_Conversion &&
3053 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3054 FromType1->isPointerType() && FromType2->isPointerType() &&
3055 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00003056 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003057 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00003058 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003059 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003060 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003061 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00003062 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003063 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00003064
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003065 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00003066 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003067 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003068 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003069 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00003070 return ImplicitConversionSequence::Worse;
3071 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003072
3073 // -- conversion of B* to A* is better than conversion of C* to A*,
3074 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003075 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003076 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003077 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003078 return ImplicitConversionSequence::Worse;
Douglas Gregor058d3de2011-01-31 18:51:41 +00003079 }
3080 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3081 SCS2.Second == ICK_Pointer_Conversion) {
3082 const ObjCObjectPointerType *FromPtr1
3083 = FromType1->getAs<ObjCObjectPointerType>();
3084 const ObjCObjectPointerType *FromPtr2
3085 = FromType2->getAs<ObjCObjectPointerType>();
3086 const ObjCObjectPointerType *ToPtr1
3087 = ToType1->getAs<ObjCObjectPointerType>();
3088 const ObjCObjectPointerType *ToPtr2
3089 = ToType2->getAs<ObjCObjectPointerType>();
3090
3091 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3092 // Apply the same conversion ranking rules for Objective-C pointer types
3093 // that we do for C++ pointers to class types. However, we employ the
3094 // Objective-C pseudo-subtyping relationship used for assignment of
3095 // Objective-C pointer types.
3096 bool FromAssignLeft
3097 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3098 bool FromAssignRight
3099 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3100 bool ToAssignLeft
3101 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3102 bool ToAssignRight
3103 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3104
3105 // A conversion to an a non-id object pointer type or qualified 'id'
3106 // type is better than a conversion to 'id'.
3107 if (ToPtr1->isObjCIdType() &&
3108 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3109 return ImplicitConversionSequence::Worse;
3110 if (ToPtr2->isObjCIdType() &&
3111 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3112 return ImplicitConversionSequence::Better;
3113
3114 // A conversion to a non-id object pointer type is better than a
3115 // conversion to a qualified 'id' type
3116 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3117 return ImplicitConversionSequence::Worse;
3118 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3119 return ImplicitConversionSequence::Better;
3120
3121 // A conversion to an a non-Class object pointer type or qualified 'Class'
3122 // type is better than a conversion to 'Class'.
3123 if (ToPtr1->isObjCClassType() &&
3124 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3125 return ImplicitConversionSequence::Worse;
3126 if (ToPtr2->isObjCClassType() &&
3127 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3128 return ImplicitConversionSequence::Better;
3129
3130 // A conversion to a non-Class object pointer type is better than a
3131 // conversion to a qualified 'Class' type.
3132 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3133 return ImplicitConversionSequence::Worse;
3134 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3135 return ImplicitConversionSequence::Better;
Mike Stump11289f42009-09-09 15:08:12 +00003136
Douglas Gregor058d3de2011-01-31 18:51:41 +00003137 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3138 if (S.Context.hasSameType(FromType1, FromType2) &&
3139 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3140 (ToAssignLeft != ToAssignRight))
3141 return ToAssignLeft? ImplicitConversionSequence::Worse
3142 : ImplicitConversionSequence::Better;
3143
3144 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3145 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3146 (FromAssignLeft != FromAssignRight))
3147 return FromAssignLeft? ImplicitConversionSequence::Better
3148 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003149 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00003150 }
Douglas Gregor058d3de2011-01-31 18:51:41 +00003151
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003152 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003153 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3154 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3155 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003156 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003157 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003158 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003159 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003160 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003161 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003162 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003163 ToType2->getAs<MemberPointerType>();
3164 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3165 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3166 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3167 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3168 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3169 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3170 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3171 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00003172 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003173 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003174 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003175 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00003176 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003177 return ImplicitConversionSequence::Better;
3178 }
3179 // conversion of B::* to C::* is better than conversion of A::* to C::*
3180 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00003181 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003182 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003183 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00003184 return ImplicitConversionSequence::Worse;
3185 }
3186 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003187
Douglas Gregor5ab11652010-04-17 22:01:05 +00003188 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00003189 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00003190 // -- binding of an expression of type C to a reference of type
3191 // B& is better than binding an expression of type C to a
3192 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003193 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3194 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3195 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003196 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003197 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003198 return ImplicitConversionSequence::Worse;
3199 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003200
Douglas Gregor2fe98832008-11-03 19:09:14 +00003201 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00003202 // -- binding of an expression of type B to a reference of type
3203 // A& is better than binding an expression of type C to a
3204 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00003205 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3206 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3207 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003208 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00003209 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00003210 return ImplicitConversionSequence::Worse;
3211 }
3212 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00003213
Douglas Gregor5c407d92008-10-23 00:40:37 +00003214 return ImplicitConversionSequence::Indistinguishable;
3215}
3216
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003217/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3218/// determine whether they are reference-related,
3219/// reference-compatible, reference-compatible with added
3220/// qualification, or incompatible, for use in C++ initialization by
3221/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3222/// type, and the first type (T1) is the pointee type of the reference
3223/// type being initialized.
3224Sema::ReferenceCompareResult
3225Sema::CompareReferenceRelationship(SourceLocation Loc,
3226 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003227 bool &DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003228 bool &ObjCConversion,
3229 bool &ObjCLifetimeConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003230 assert(!OrigT1->isReferenceType() &&
3231 "T1 must be the pointee type of the reference type");
3232 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3233
3234 QualType T1 = Context.getCanonicalType(OrigT1);
3235 QualType T2 = Context.getCanonicalType(OrigT2);
3236 Qualifiers T1Quals, T2Quals;
3237 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3238 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3239
3240 // C++ [dcl.init.ref]p4:
3241 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3242 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3243 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003244 DerivedToBase = false;
3245 ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003246 ObjCLifetimeConversion = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003247 if (UnqualT1 == UnqualT2) {
3248 // Nothing to do.
3249 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003250 IsDerivedFrom(UnqualT2, UnqualT1))
3251 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003252 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3253 UnqualT2->isObjCObjectOrInterfaceType() &&
3254 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3255 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003256 else
3257 return Ref_Incompatible;
3258
3259 // At this point, we know that T1 and T2 are reference-related (at
3260 // least).
3261
3262 // If the type is an array type, promote the element qualifiers to the type
3263 // for comparison.
3264 if (isa<ArrayType>(T1) && T1Quals)
3265 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3266 if (isa<ArrayType>(T2) && T2Quals)
3267 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3268
3269 // C++ [dcl.init.ref]p4:
3270 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3271 // reference-related to T2 and cv1 is the same cv-qualification
3272 // as, or greater cv-qualification than, cv2. For purposes of
3273 // overload resolution, cases for which cv1 is greater
3274 // cv-qualification than cv2 are identified as
3275 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregord517d552011-04-28 17:56:11 +00003276 //
3277 // Note that we also require equivalence of Objective-C GC and address-space
3278 // qualifiers when performing these computations, so that e.g., an int in
3279 // address space 1 is not reference-compatible with an int in address
3280 // space 2.
John McCall31168b02011-06-15 23:02:42 +00003281 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3282 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3283 T1Quals.removeObjCLifetime();
3284 T2Quals.removeObjCLifetime();
3285 ObjCLifetimeConversion = true;
3286 }
3287
Douglas Gregord517d552011-04-28 17:56:11 +00003288 if (T1Quals == T2Quals)
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003289 return Ref_Compatible;
John McCall31168b02011-06-15 23:02:42 +00003290 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003291 return Ref_Compatible_With_Added_Qualification;
3292 else
3293 return Ref_Related;
3294}
3295
Douglas Gregor836a7e82010-08-11 02:15:33 +00003296/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00003297/// with DeclType. Return true if something definite is found.
3298static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00003299FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3300 QualType DeclType, SourceLocation DeclLoc,
3301 Expr *Init, QualType T2, bool AllowRvalues,
3302 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003303 assert(T2->isRecordType() && "Can only find conversions of record types.");
3304 CXXRecordDecl *T2RecordDecl
3305 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3306
3307 OverloadCandidateSet CandidateSet(DeclLoc);
3308 const UnresolvedSetImpl *Conversions
3309 = T2RecordDecl->getVisibleConversionFunctions();
3310 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3311 E = Conversions->end(); I != E; ++I) {
3312 NamedDecl *D = *I;
3313 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3314 if (isa<UsingShadowDecl>(D))
3315 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3316
3317 FunctionTemplateDecl *ConvTemplate
3318 = dyn_cast<FunctionTemplateDecl>(D);
3319 CXXConversionDecl *Conv;
3320 if (ConvTemplate)
3321 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3322 else
3323 Conv = cast<CXXConversionDecl>(D);
3324
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003325 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor836a7e82010-08-11 02:15:33 +00003326 // explicit conversions, skip it.
3327 if (!AllowExplicit && Conv->isExplicit())
3328 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003329
Douglas Gregor836a7e82010-08-11 02:15:33 +00003330 if (AllowRvalues) {
3331 bool DerivedToBase = false;
3332 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003333 bool ObjCLifetimeConversion = false;
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003334
3335 // If we are initializing an rvalue reference, don't permit conversion
3336 // functions that return lvalues.
3337 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3338 const ReferenceType *RefType
3339 = Conv->getConversionType()->getAs<LValueReferenceType>();
3340 if (RefType && !RefType->getPointeeType()->isFunctionType())
3341 continue;
3342 }
3343
Douglas Gregor836a7e82010-08-11 02:15:33 +00003344 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00003345 S.CompareReferenceRelationship(
3346 DeclLoc,
3347 Conv->getConversionType().getNonReferenceType()
3348 .getUnqualifiedType(),
3349 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCall31168b02011-06-15 23:02:42 +00003350 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth8e543b32010-12-12 08:17:55 +00003351 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00003352 continue;
3353 } else {
3354 // If the conversion function doesn't return a reference type,
3355 // it can't be considered for this conversion. An rvalue reference
3356 // is only acceptable if its referencee is a function type.
3357
3358 const ReferenceType *RefType =
3359 Conv->getConversionType()->getAs<ReferenceType>();
3360 if (!RefType ||
3361 (!RefType->isLValueReferenceType() &&
3362 !RefType->getPointeeType()->isFunctionType()))
3363 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00003364 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003365
Douglas Gregor836a7e82010-08-11 02:15:33 +00003366 if (ConvTemplate)
3367 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003368 Init, DeclType, CandidateSet);
Douglas Gregor836a7e82010-08-11 02:15:33 +00003369 else
3370 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregorf143cd52011-01-24 16:14:37 +00003371 DeclType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00003372 }
3373
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003374 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3375
Sebastian Redld92badf2010-06-30 18:13:39 +00003376 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00003377 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003378 case OR_Success:
3379 // C++ [over.ics.ref]p1:
3380 //
3381 // [...] If the parameter binds directly to the result of
3382 // applying a conversion function to the argument
3383 // expression, the implicit conversion sequence is a
3384 // user-defined conversion sequence (13.3.3.1.2), with the
3385 // second standard conversion sequence either an identity
3386 // conversion or, if the conversion function returns an
3387 // entity of a type that is a derived class of the parameter
3388 // type, a derived-to-base Conversion.
3389 if (!Best->FinalConversion.DirectBinding)
3390 return false;
3391
Chandler Carruth30141632011-02-25 19:41:05 +00003392 if (Best->Function)
3393 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redld92badf2010-06-30 18:13:39 +00003394 ICS.setUserDefined();
3395 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3396 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00003397 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redld92badf2010-06-30 18:13:39 +00003398 ICS.UserDefined.ConversionFunction = Best->Function;
John McCall30909032011-09-21 08:36:56 +00003399 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redld92badf2010-06-30 18:13:39 +00003400 ICS.UserDefined.EllipsisConversion = false;
3401 assert(ICS.UserDefined.After.ReferenceBinding &&
3402 ICS.UserDefined.After.DirectBinding &&
3403 "Expected a direct reference binding!");
3404 return true;
3405
3406 case OR_Ambiguous:
3407 ICS.setAmbiguous();
3408 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3409 Cand != CandidateSet.end(); ++Cand)
3410 if (Cand->Viable)
3411 ICS.Ambiguous.addConversion(Cand->Function);
3412 return true;
3413
3414 case OR_No_Viable_Function:
3415 case OR_Deleted:
3416 // There was no suitable conversion, or we found a deleted
3417 // conversion; continue with other checks.
3418 return false;
3419 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003420
Eric Christopheraba9fb22010-06-30 18:36:32 +00003421 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003422}
3423
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003424/// \brief Compute an implicit conversion sequence for reference
3425/// initialization.
3426static ImplicitConversionSequence
3427TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3428 SourceLocation DeclLoc,
3429 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003430 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003431 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3432
3433 // Most paths end in a failed conversion.
3434 ImplicitConversionSequence ICS;
3435 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3436
3437 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3438 QualType T2 = Init->getType();
3439
3440 // If the initializer is the address of an overloaded function, try
3441 // to resolve the overloaded function. If all goes well, T2 is the
3442 // type of the resulting function.
3443 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3444 DeclAccessPair Found;
3445 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3446 false, Found))
3447 T2 = Fn->getType();
3448 }
3449
3450 // Compute some basic properties of the types and the initializer.
3451 bool isRValRef = DeclType->isRValueReferenceType();
3452 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003453 bool ObjCConversion = false;
John McCall31168b02011-06-15 23:02:42 +00003454 bool ObjCLifetimeConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00003455 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003456 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003457 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCall31168b02011-06-15 23:02:42 +00003458 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003459
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003460
Sebastian Redld92badf2010-06-30 18:13:39 +00003461 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00003462 // A reference to type "cv1 T1" is initialized by an expression
3463 // of type "cv2 T2" as follows:
3464
Sebastian Redld92badf2010-06-30 18:13:39 +00003465 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregorf143cd52011-01-24 16:14:37 +00003466 if (!isRValRef) {
Sebastian Redld92badf2010-06-30 18:13:39 +00003467 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3468 // reference-compatible with "cv2 T2," or
3469 //
3470 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3471 if (InitCategory.isLValue() &&
3472 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003473 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00003474 // When a parameter of reference type binds directly (8.5.3)
3475 // to an argument expression, the implicit conversion sequence
3476 // is the identity conversion, unless the argument expression
3477 // has a type that is a derived class of the parameter type,
3478 // in which case the implicit conversion sequence is a
3479 // derived-to-base Conversion (13.3.3.1).
3480 ICS.setStandard();
3481 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00003482 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3483 : ObjCConversion? ICK_Compatible_Conversion
3484 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00003485 ICS.Standard.Third = ICK_Identity;
3486 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3487 ICS.Standard.setToType(0, T2);
3488 ICS.Standard.setToType(1, T1);
3489 ICS.Standard.setToType(2, T1);
3490 ICS.Standard.ReferenceBinding = true;
3491 ICS.Standard.DirectBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003492 ICS.Standard.IsLvalueReference = !isRValRef;
3493 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3494 ICS.Standard.BindsToRvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003495 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003496 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redld92badf2010-06-30 18:13:39 +00003497 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003498
Sebastian Redld92badf2010-06-30 18:13:39 +00003499 // Nothing more to do: the inaccessibility/ambiguity check for
3500 // derived-to-base conversions is suppressed when we're
3501 // computing the implicit conversion sequence (C++
3502 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003503 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00003504 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003505
Sebastian Redld92badf2010-06-30 18:13:39 +00003506 // -- has a class type (i.e., T2 is a class type), where T1 is
3507 // not reference-related to T2, and can be implicitly
3508 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3509 // is reference-compatible with "cv3 T3" 92) (this
3510 // conversion is selected by enumerating the applicable
3511 // conversion functions (13.3.1.6) and choosing the best
3512 // one through overload resolution (13.3)),
3513 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003514 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redld92badf2010-06-30 18:13:39 +00003515 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00003516 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3517 Init, T2, /*AllowRvalues=*/false,
3518 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00003519 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003520 }
3521 }
3522
Sebastian Redld92badf2010-06-30 18:13:39 +00003523 // -- Otherwise, the reference shall be an lvalue reference to a
3524 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregorf143cd52011-01-24 16:14:37 +00003525 // shall be an rvalue reference.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003526 //
Douglas Gregor870f3742010-04-18 09:22:00 +00003527 // We actually handle one oddity of C++ [over.ics.ref] at this
3528 // point, which is that, due to p2 (which short-circuits reference
3529 // binding by only attempting a simple conversion for non-direct
3530 // bindings) and p3's strange wording, we allow a const volatile
3531 // reference to bind to an rvalue. Hence the check for the presence
3532 // of "const" rather than checking for "const" being the only
3533 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003534 // This is also the point where rvalue references and lvalue inits no longer
3535 // go together.
Douglas Gregorcba72b12011-01-21 05:18:22 +00003536 if (!isRValRef && !T1.isConstQualified())
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003537 return ICS;
3538
Douglas Gregorf143cd52011-01-24 16:14:37 +00003539 // -- If the initializer expression
3540 //
3541 // -- is an xvalue, class prvalue, array prvalue or function
John McCall31168b02011-06-15 23:02:42 +00003542 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregorf143cd52011-01-24 16:14:37 +00003543 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3544 (InitCategory.isXValue() ||
3545 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3546 (InitCategory.isLValue() && T2->isFunctionType()))) {
3547 ICS.setStandard();
3548 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003549 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003550 : ObjCConversion? ICK_Compatible_Conversion
3551 : ICK_Identity;
3552 ICS.Standard.Third = ICK_Identity;
3553 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3554 ICS.Standard.setToType(0, T2);
3555 ICS.Standard.setToType(1, T1);
3556 ICS.Standard.setToType(2, T1);
3557 ICS.Standard.ReferenceBinding = true;
3558 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3559 // binding unless we're binding to a class prvalue.
3560 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3561 // allow the use of rvalue references in C++98/03 for the benefit of
3562 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003563 ICS.Standard.DirectBinding =
3564 S.getLangOptions().CPlusPlus0x ||
Douglas Gregorf143cd52011-01-24 16:14:37 +00003565 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregore696ebb2011-01-26 14:52:12 +00003566 ICS.Standard.IsLvalueReference = !isRValRef;
3567 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003568 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregore1a47c12011-01-26 19:41:18 +00003569 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003570 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003571 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003572 return ICS;
Douglas Gregorf143cd52011-01-24 16:14:37 +00003573 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003574
Douglas Gregorf143cd52011-01-24 16:14:37 +00003575 // -- has a class type (i.e., T2 is a class type), where T1 is not
3576 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003577 // an xvalue, class prvalue, or function lvalue of type
3578 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregorf143cd52011-01-24 16:14:37 +00003579 // "cv3 T3",
3580 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003581 // then the reference is bound to the value of the initializer
Douglas Gregorf143cd52011-01-24 16:14:37 +00003582 // expression in the first case and to the result of the conversion
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003583 // in the second case (or, in either case, to an appropriate base
Douglas Gregorf143cd52011-01-24 16:14:37 +00003584 // class subobject).
3585 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003586 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003587 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3588 Init, T2, /*AllowRvalues=*/true,
3589 AllowExplicit)) {
3590 // In the second case, if the reference is an rvalue reference
3591 // and the second standard conversion sequence of the
3592 // user-defined conversion sequence includes an lvalue-to-rvalue
3593 // conversion, the program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003594 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregorf143cd52011-01-24 16:14:37 +00003595 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3596 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3597
Douglas Gregor95273c32011-01-21 16:36:05 +00003598 return ICS;
Rafael Espindolabe468d92011-01-22 15:32:35 +00003599 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003600
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003601 // -- Otherwise, a temporary of type "cv1 T1" is created and
3602 // initialized from the initializer expression using the
3603 // rules for a non-reference copy initialization (8.5). The
3604 // reference is then bound to the temporary. If T1 is
3605 // reference-related to T2, cv1 must be the same
3606 // cv-qualification as, or greater cv-qualification than,
3607 // cv2; otherwise, the program is ill-formed.
3608 if (RefRelationship == Sema::Ref_Related) {
3609 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3610 // we would be reference-compatible or reference-compatible with
3611 // added qualification. But that wasn't the case, so the reference
3612 // initialization fails.
John McCall31168b02011-06-15 23:02:42 +00003613 //
3614 // Note that we only want to check address spaces and cvr-qualifiers here.
3615 // ObjC GC and lifetime qualifiers aren't important.
3616 Qualifiers T1Quals = T1.getQualifiers();
3617 Qualifiers T2Quals = T2.getQualifiers();
3618 T1Quals.removeObjCGCAttr();
3619 T1Quals.removeObjCLifetime();
3620 T2Quals.removeObjCGCAttr();
3621 T2Quals.removeObjCLifetime();
3622 if (!T1Quals.compatiblyIncludes(T2Quals))
3623 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003624 }
3625
3626 // If at least one of the types is a class type, the types are not
3627 // related, and we aren't allowed any user conversions, the
3628 // reference binding fails. This case is important for breaking
3629 // recursion, since TryImplicitConversion below will attempt to
3630 // create a temporary through the use of a copy constructor.
3631 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3632 (T1->isRecordType() || T2->isRecordType()))
3633 return ICS;
3634
Douglas Gregorcba72b12011-01-21 05:18:22 +00003635 // If T1 is reference-related to T2 and the reference is an rvalue
3636 // reference, the initializer expression shall not be an lvalue.
3637 if (RefRelationship >= Sema::Ref_Related &&
3638 isRValRef && Init->Classify(S.Context).isLValue())
3639 return ICS;
3640
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003641 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003642 // When a parameter of reference type is not bound directly to
3643 // an argument expression, the conversion sequence is the one
3644 // required to convert the argument expression to the
3645 // underlying type of the reference according to
3646 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3647 // to copy-initializing a temporary of the underlying type with
3648 // the argument expression. Any difference in top-level
3649 // cv-qualification is subsumed by the initialization itself
3650 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003651 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3652 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003653 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00003654 /*CStyle=*/false,
3655 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003656
3657 // Of course, that's still a reference binding.
3658 if (ICS.isStandard()) {
3659 ICS.Standard.ReferenceBinding = true;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003660 ICS.Standard.IsLvalueReference = !isRValRef;
3661 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3662 ICS.Standard.BindsToRvalue = true;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003663 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCall31168b02011-06-15 23:02:42 +00003664 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003665 } else if (ICS.isUserDefined()) {
Douglas Gregorb0e6c8a2011-10-04 23:59:32 +00003666 // Don't allow rvalue references to bind to lvalues.
3667 if (DeclType->isRValueReferenceType()) {
3668 if (const ReferenceType *RefType
3669 = ICS.UserDefined.ConversionFunction->getResultType()
3670 ->getAs<LValueReferenceType>()) {
3671 if (!RefType->getPointeeType()->isFunctionType()) {
3672 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
3673 DeclType);
3674 return ICS;
3675 }
3676 }
3677 }
3678
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003679 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregor3ec79102011-08-15 13:59:46 +00003680 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3681 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3682 ICS.UserDefined.After.BindsToRvalue = true;
3683 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3684 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003685 }
Douglas Gregorcba72b12011-01-21 05:18:22 +00003686
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003687 return ICS;
3688}
3689
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003690static ImplicitConversionSequence
3691TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
3692 bool SuppressUserConversions,
3693 bool InOverloadResolution,
3694 bool AllowObjCWritebackConversion);
3695
3696/// TryListConversion - Try to copy-initialize a value of type ToType from the
3697/// initializer list From.
3698static ImplicitConversionSequence
3699TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
3700 bool SuppressUserConversions,
3701 bool InOverloadResolution,
3702 bool AllowObjCWritebackConversion) {
3703 // C++11 [over.ics.list]p1:
3704 // When an argument is an initializer list, it is not an expression and
3705 // special rules apply for converting it to a parameter type.
3706
3707 ImplicitConversionSequence Result;
3708 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
3709
3710 // C++11 [over.ics.list]p2:
3711 // If the parameter type is std::initializer_list<X> or "array of X" and
3712 // all the elements can be implicitly converted to X, the implicit
3713 // conversion sequence is the worst conversion necessary to convert an
3714 // element of the list to X.
3715 // FIXME: Recognize std::initializer_list.
3716 // FIXME: Arrays don't make sense until we can deal with references.
3717 if (ToType->isArrayType())
3718 return Result;
3719
3720 // C++11 [over.ics.list]p3:
3721 // Otherwise, if the parameter is a non-aggregate class X and overload
3722 // resolution chooses a single best constructor [...] the implicit
3723 // conversion sequence is a user-defined conversion sequence. If multiple
3724 // constructors are viable but none is better than the others, the
3725 // implicit conversion sequence is a user-defined conversion sequence.
3726 // FIXME: Implement this.
3727 if (ToType->isRecordType() && !ToType->isAggregateType())
3728 return Result;
3729
3730 // C++11 [over.ics.list]p4:
3731 // Otherwise, if the parameter has an aggregate type which can be
3732 // initialized from the initializer list [...] the implicit conversion
3733 // sequence is a user-defined conversion sequence.
3734 // FIXME: Implement this.
3735 if (ToType->isAggregateType()) {
3736 return Result;
3737 }
3738
3739 // C++11 [over.ics.list]p5:
3740 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
3741 // FIXME: Implement this.
3742 if (ToType->isReferenceType())
3743 return Result;
3744
3745 // C++11 [over.ics.list]p6:
3746 // Otherwise, if the parameter type is not a class:
3747 if (!ToType->isRecordType()) {
3748 // - if the initializer list has one element, the implicit conversion
3749 // sequence is the one required to convert the element to the
3750 // parameter type.
3751 // FIXME: Catch narrowing here?
3752 unsigned NumInits = From->getNumInits();
3753 if (NumInits == 1)
3754 Result = TryCopyInitialization(S, From->getInit(0), ToType,
3755 SuppressUserConversions,
3756 InOverloadResolution,
3757 AllowObjCWritebackConversion);
3758 // - if the initializer list has no elements, the implicit conversion
3759 // sequence is the identity conversion.
3760 else if (NumInits == 0) {
3761 Result.setStandard();
3762 Result.Standard.setAsIdentityConversion();
3763 }
3764 return Result;
3765 }
3766
3767 // C++11 [over.ics.list]p7:
3768 // In all cases other than those enumerated above, no conversion is possible
3769 return Result;
3770}
3771
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003772/// TryCopyInitialization - Try to copy-initialize a value of type
3773/// ToType from the expression From. Return the implicit conversion
3774/// sequence required to pass this argument, which may be a bad
3775/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003776/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003777/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003778static ImplicitConversionSequence
3779TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003780 bool SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00003781 bool InOverloadResolution,
3782 bool AllowObjCWritebackConversion) {
Sebastian Redlb17be8d2011-10-16 18:19:34 +00003783 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
3784 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
3785 InOverloadResolution,AllowObjCWritebackConversion);
3786
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003787 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003788 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003789 /*FIXME:*/From->getLocStart(),
3790 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003791 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003792
John McCall5c32be02010-08-24 20:38:10 +00003793 return TryImplicitConversion(S, From, ToType,
3794 SuppressUserConversions,
3795 /*AllowExplicit=*/false,
Douglas Gregor58281352011-01-27 00:58:17 +00003796 InOverloadResolution,
John McCall31168b02011-06-15 23:02:42 +00003797 /*CStyle=*/false,
3798 AllowObjCWritebackConversion);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003799}
3800
Anna Zaks1b068122011-07-28 19:46:48 +00003801static bool TryCopyInitialization(const CanQualType FromQTy,
3802 const CanQualType ToQTy,
3803 Sema &S,
3804 SourceLocation Loc,
3805 ExprValueKind FromVK) {
3806 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
3807 ImplicitConversionSequence ICS =
3808 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
3809
3810 return !ICS.isBad();
3811}
3812
Douglas Gregor436424c2008-11-18 23:14:02 +00003813/// TryObjectArgumentInitialization - Try to initialize the object
3814/// parameter of the given member function (@c Method) from the
3815/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003816static ImplicitConversionSequence
3817TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003818 Expr::Classification FromClassification,
John McCall5c32be02010-08-24 20:38:10 +00003819 CXXMethodDecl *Method,
3820 CXXRecordDecl *ActingContext) {
3821 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003822 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3823 // const volatile object.
3824 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3825 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003826 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003827
3828 // Set up the conversion sequence as a "bad" conversion, to allow us
3829 // to exit early.
3830 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003831
3832 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003833 QualType FromType = OrigFromType;
Douglas Gregor02824322011-01-26 19:30:28 +00003834 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003835 FromType = PT->getPointeeType();
3836
Douglas Gregor02824322011-01-26 19:30:28 +00003837 // When we had a pointer, it's implicitly dereferenced, so we
3838 // better have an lvalue.
3839 assert(FromClassification.isLValue());
3840 }
3841
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003842 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003843
Douglas Gregor02824322011-01-26 19:30:28 +00003844 // C++0x [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003845 // For non-static member functions, the type of the implicit object
Douglas Gregor02824322011-01-26 19:30:28 +00003846 // parameter is
3847 //
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00003848 // - "lvalue reference to cv X" for functions declared without a
3849 // ref-qualifier or with the & ref-qualifier
3850 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor02824322011-01-26 19:30:28 +00003851 // ref-qualifier
3852 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003853 // where X is the class of which the function is a member and cv is the
Douglas Gregor02824322011-01-26 19:30:28 +00003854 // cv-qualification on the member function declaration.
3855 //
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003856 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor02824322011-01-26 19:30:28 +00003857 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003858 // (C++ [over.match.funcs]p5). We perform a simplified version of
3859 // reference binding here, that allows class rvalues to bind to
3860 // non-constant references.
3861
Douglas Gregor02824322011-01-26 19:30:28 +00003862 // First check the qualifiers.
John McCall5c32be02010-08-24 20:38:10 +00003863 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003864 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003865 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003866 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003867 ICS.setBad(BadConversionSequence::bad_qualifiers,
3868 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003869 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003870 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003871
3872 // Check that we have either the same type or a derived type. It
3873 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003874 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003875 ImplicitConversionKind SecondKind;
3876 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3877 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003878 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003879 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003880 else {
John McCall65eb8792010-02-25 01:37:24 +00003881 ICS.setBad(BadConversionSequence::unrelated_class,
3882 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003883 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003884 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003885
Douglas Gregor02824322011-01-26 19:30:28 +00003886 // Check the ref-qualifier.
3887 switch (Method->getRefQualifier()) {
3888 case RQ_None:
3889 // Do nothing; we don't care about lvalueness or rvalueness.
3890 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003891
Douglas Gregor02824322011-01-26 19:30:28 +00003892 case RQ_LValue:
3893 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
3894 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003895 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003896 ImplicitParamType);
3897 return ICS;
3898 }
3899 break;
3900
3901 case RQ_RValue:
3902 if (!FromClassification.isRValue()) {
3903 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003904 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor02824322011-01-26 19:30:28 +00003905 ImplicitParamType);
3906 return ICS;
3907 }
3908 break;
3909 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003910
Douglas Gregor436424c2008-11-18 23:14:02 +00003911 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003912 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003913 ICS.Standard.setAsIdentityConversion();
3914 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003915 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003916 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003917 ICS.Standard.ReferenceBinding = true;
3918 ICS.Standard.DirectBinding = true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003919 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregore696ebb2011-01-26 14:52:12 +00003920 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregore1a47c12011-01-26 19:41:18 +00003921 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
3922 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
3923 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor436424c2008-11-18 23:14:02 +00003924 return ICS;
3925}
3926
3927/// PerformObjectArgumentInitialization - Perform initialization of
3928/// the implicit object parameter for the given Method with the given
3929/// expression.
John Wiegley01296292011-04-08 18:41:53 +00003930ExprResult
3931Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00003932 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003933 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003934 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003935 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003936 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003937 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003938
Douglas Gregor02824322011-01-26 19:30:28 +00003939 Expr::Classification FromClassification;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003940 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003941 FromRecordType = PT->getPointeeType();
3942 DestType = Method->getThisType(Context);
Douglas Gregor02824322011-01-26 19:30:28 +00003943 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003944 } else {
3945 FromRecordType = From->getType();
3946 DestType = ImplicitParamRecordType;
Douglas Gregor02824322011-01-26 19:30:28 +00003947 FromClassification = From->Classify(Context);
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003948 }
3949
John McCall6e9f8f62009-12-03 04:06:58 +00003950 // Note that we always use the true parent context when performing
3951 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003952 ImplicitConversionSequence ICS
Douglas Gregor02824322011-01-26 19:30:28 +00003953 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
3954 Method, Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003955 if (ICS.isBad()) {
3956 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3957 Qualifiers FromQs = FromRecordType.getQualifiers();
3958 Qualifiers ToQs = DestType.getQualifiers();
3959 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3960 if (CVR) {
3961 Diag(From->getSourceRange().getBegin(),
3962 diag::err_member_function_call_bad_cvr)
3963 << Method->getDeclName() << FromRecordType << (CVR - 1)
3964 << From->getSourceRange();
3965 Diag(Method->getLocation(), diag::note_previous_decl)
3966 << Method->getDeclName();
John Wiegley01296292011-04-08 18:41:53 +00003967 return ExprError();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003968 }
3969 }
3970
Douglas Gregor436424c2008-11-18 23:14:02 +00003971 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003972 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003973 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003974 }
Mike Stump11289f42009-09-09 15:08:12 +00003975
John Wiegley01296292011-04-08 18:41:53 +00003976 if (ICS.Standard.Second == ICK_Derived_To_Base) {
3977 ExprResult FromRes =
3978 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
3979 if (FromRes.isInvalid())
3980 return ExprError();
3981 From = FromRes.take();
3982 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003983
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003984 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley01296292011-04-08 18:41:53 +00003985 From = ImpCastExprToType(From, DestType, CK_NoOp,
3986 From->getType()->isPointerType() ? VK_RValue : VK_LValue).take();
3987 return Owned(From);
Douglas Gregor436424c2008-11-18 23:14:02 +00003988}
3989
Douglas Gregor5fb53972009-01-14 15:45:31 +00003990/// TryContextuallyConvertToBool - Attempt to contextually convert the
3991/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003992static ImplicitConversionSequence
3993TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003994 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003995 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003996 // FIXME: Are these flags correct?
3997 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003998 /*AllowExplicit=*/true,
Douglas Gregor58281352011-01-27 00:58:17 +00003999 /*InOverloadResolution=*/false,
John McCall31168b02011-06-15 23:02:42 +00004000 /*CStyle=*/false,
4001 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004002}
4003
4004/// PerformContextuallyConvertToBool - Perform a contextual conversion
4005/// of the expression From to bool (C++0x [conv]p3).
John Wiegley01296292011-04-08 18:41:53 +00004006ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall5c32be02010-08-24 20:38:10 +00004007 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00004008 if (!ICS.isBad())
4009 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004010
Fariborz Jahanian76197412009-11-18 18:26:29 +00004011 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall0009fcc2011-04-26 20:42:42 +00004012 return Diag(From->getSourceRange().getBegin(),
4013 diag::err_typecheck_bool_condition)
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00004014 << From->getType() << From->getSourceRange();
John Wiegley01296292011-04-08 18:41:53 +00004015 return ExprError();
Douglas Gregor5fb53972009-01-14 15:45:31 +00004016}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004017
John McCallfec112d2011-09-09 06:11:02 +00004018/// dropPointerConversions - If the given standard conversion sequence
4019/// involves any pointer conversions, remove them. This may change
4020/// the result type of the conversion sequence.
4021static void dropPointerConversion(StandardConversionSequence &SCS) {
4022 if (SCS.Second == ICK_Pointer_Conversion) {
4023 SCS.Second = ICK_Identity;
4024 SCS.Third = ICK_Identity;
4025 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4026 }
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004027}
John McCall5c32be02010-08-24 20:38:10 +00004028
John McCallfec112d2011-09-09 06:11:02 +00004029/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4030/// convert the expression From to an Objective-C pointer type.
4031static ImplicitConversionSequence
4032TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4033 // Do an implicit conversion to 'id'.
4034 QualType Ty = S.Context.getObjCIdType();
4035 ImplicitConversionSequence ICS
4036 = TryImplicitConversion(S, From, Ty,
4037 // FIXME: Are these flags correct?
4038 /*SuppressUserConversions=*/false,
4039 /*AllowExplicit=*/true,
4040 /*InOverloadResolution=*/false,
4041 /*CStyle=*/false,
4042 /*AllowObjCWritebackConversion=*/false);
4043
4044 // Strip off any final conversions to 'id'.
4045 switch (ICS.getKind()) {
4046 case ImplicitConversionSequence::BadConversion:
4047 case ImplicitConversionSequence::AmbiguousConversion:
4048 case ImplicitConversionSequence::EllipsisConversion:
4049 break;
4050
4051 case ImplicitConversionSequence::UserDefinedConversion:
4052 dropPointerConversion(ICS.UserDefined.After);
4053 break;
4054
4055 case ImplicitConversionSequence::StandardConversion:
4056 dropPointerConversion(ICS.Standard);
4057 break;
4058 }
4059
4060 return ICS;
4061}
4062
4063/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4064/// conversion of the expression From to an Objective-C pointer type.
4065ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall8b07ec22010-05-15 11:32:37 +00004066 QualType Ty = Context.getObjCIdType();
John McCallfec112d2011-09-09 06:11:02 +00004067 ImplicitConversionSequence ICS =
4068 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004069 if (!ICS.isBad())
4070 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley01296292011-04-08 18:41:53 +00004071 return ExprError();
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00004072}
Douglas Gregor5fb53972009-01-14 15:45:31 +00004073
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004074/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004075/// enumeration type.
4076///
4077/// This routine will attempt to convert an expression of class type to an
4078/// integral or enumeration type, if that class type only has a single
4079/// conversion to an integral or enumeration type.
4080///
Douglas Gregor4799d032010-06-30 00:20:43 +00004081/// \param Loc The source location of the construct that requires the
4082/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004083///
Douglas Gregor4799d032010-06-30 00:20:43 +00004084/// \param FromE The expression we're converting from.
4085///
4086/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4087/// have integral or enumeration type.
4088///
4089/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4090/// incomplete class type.
4091///
4092/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4093/// explicit conversion function (because no implicit conversion functions
4094/// were available). This is a recovery mode.
4095///
4096/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4097/// showing which conversion was picked.
4098///
4099/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4100/// conversion function that could convert to integral or enumeration type.
4101///
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004102/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor4799d032010-06-30 00:20:43 +00004103/// usable conversion function.
4104///
4105/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4106/// function, which may be an extension in this case.
4107///
4108/// \returns The expression, converted to an integral or enumeration type if
4109/// successful.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004110ExprResult
John McCallb268a282010-08-23 23:25:46 +00004111Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004112 const PartialDiagnostic &NotIntDiag,
4113 const PartialDiagnostic &IncompleteDiag,
4114 const PartialDiagnostic &ExplicitConvDiag,
4115 const PartialDiagnostic &ExplicitConvNote,
4116 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00004117 const PartialDiagnostic &AmbigNote,
4118 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004119 // We can't perform any more checking for type-dependent expressions.
4120 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00004121 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004122
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004123 // If the expression already has integral or enumeration type, we're golden.
4124 QualType T = From->getType();
4125 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00004126 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004127
4128 // FIXME: Check for missing '()' if T is a function type?
4129
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004130 // 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 +00004131 // expression of integral or enumeration type.
4132 const RecordType *RecordTy = T->getAs<RecordType>();
4133 if (!RecordTy || !getLangOptions().CPlusPlus) {
4134 Diag(Loc, NotIntDiag)
4135 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00004136 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004137 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004138
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004139 // We must have a complete class type.
4140 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00004141 return Owned(From);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004142
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004143 // Look for a conversion to an integral or enumeration type.
4144 UnresolvedSet<4> ViableConversions;
4145 UnresolvedSet<4> ExplicitConversions;
4146 const UnresolvedSetImpl *Conversions
4147 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004148
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004149 bool HadMultipleCandidates = (Conversions->size() > 1);
4150
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004151 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004152 E = Conversions->end();
4153 I != E;
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004154 ++I) {
4155 if (CXXConversionDecl *Conversion
4156 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4157 if (Conversion->getConversionType().getNonReferenceType()
4158 ->isIntegralOrEnumerationType()) {
4159 if (Conversion->isExplicit())
4160 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4161 else
4162 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4163 }
4164 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004165
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004166 switch (ViableConversions.size()) {
4167 case 0:
4168 if (ExplicitConversions.size() == 1) {
4169 DeclAccessPair Found = ExplicitConversions[0];
4170 CXXConversionDecl *Conversion
4171 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004172
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004173 // The user probably meant to invoke the given explicit
4174 // conversion; use it.
4175 QualType ConvTy
4176 = Conversion->getConversionType().getNonReferenceType();
4177 std::string TypeStr;
Douglas Gregor75acd922011-09-27 23:30:47 +00004178 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004179
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004180 Diag(Loc, ExplicitConvDiag)
4181 << T << ConvTy
4182 << FixItHint::CreateInsertion(From->getLocStart(),
4183 "static_cast<" + TypeStr + ">(")
4184 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4185 ")");
4186 Diag(Conversion->getLocation(), ExplicitConvNote)
4187 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004188
4189 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004190 // explicit conversion function.
4191 if (isSFINAEContext())
4192 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004193
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004194 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004195 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4196 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004197 if (Result.isInvalid())
4198 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004199
Douglas Gregor668443e2011-01-20 00:18:04 +00004200 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004201 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004202
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004203 // We'll complain below about a non-integral condition type.
4204 break;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004205
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004206 case 1: {
4207 // Apply this conversion.
4208 DeclAccessPair Found = ViableConversions[0];
4209 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004210
Douglas Gregor4799d032010-06-30 00:20:43 +00004211 CXXConversionDecl *Conversion
4212 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4213 QualType ConvTy
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004214 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor4799d032010-06-30 00:20:43 +00004215 if (ConvDiag.getDiagID()) {
4216 if (isSFINAEContext())
4217 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004218
Douglas Gregor4799d032010-06-30 00:20:43 +00004219 Diag(Loc, ConvDiag)
4220 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4221 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004222
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004223 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4224 HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00004225 if (Result.isInvalid())
4226 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004227
Douglas Gregor668443e2011-01-20 00:18:04 +00004228 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004229 break;
4230 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004231
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004232 default:
4233 Diag(Loc, AmbigDiag)
4234 << T << From->getSourceRange();
4235 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4236 CXXConversionDecl *Conv
4237 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4238 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4239 Diag(Conv->getLocation(), AmbigNote)
4240 << ConvTy->isEnumeralType() << ConvTy;
4241 }
John McCallb268a282010-08-23 23:25:46 +00004242 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004243 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004244
Douglas Gregor5823da32010-06-29 23:25:20 +00004245 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004246 Diag(Loc, NotIntDiag)
4247 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004248
John McCallb268a282010-08-23 23:25:46 +00004249 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00004250}
4251
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004252/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00004253/// candidate functions, using the given function call arguments. If
4254/// @p SuppressUserConversions, then don't allow user-defined
4255/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00004256///
4257/// \para PartialOverloading true if we are performing "partial" overloading
4258/// based on an incomplete set of function arguments. This feature is used by
4259/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00004260void
4261Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00004262 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004263 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00004264 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00004265 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00004266 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00004267 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004268 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004269 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00004270 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi7c288862011-01-27 07:09:49 +00004271 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00004272
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004273 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00004274 if (!isa<CXXConstructorDecl>(Method)) {
4275 // If we get here, it's because we're calling a member function
4276 // that is named without a member access expression (e.g.,
4277 // "this->f") that was either written explicitly or created
4278 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00004279 // function, e.g., X::f(). We use an empty type for the implied
4280 // object argument (C++ [over.call.func]p3), and the acting context
4281 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00004282 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004283 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor02824322011-01-26 19:30:28 +00004284 Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004285 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00004286 return;
4287 }
4288 // We treat a constructor like a non-member function, since its object
4289 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004290 }
4291
Douglas Gregorff7028a2009-11-13 23:59:09 +00004292 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004293 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00004294
Douglas Gregor27381f32009-11-23 12:27:39 +00004295 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004296 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004297
Douglas Gregorffe14e32009-11-14 01:20:54 +00004298 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4299 // C++ [class.copy]p3:
4300 // A member function template is never instantiated to perform the copy
4301 // of a class object to an object of its class type.
4302 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004303 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00004304 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00004305 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4306 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00004307 return;
4308 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004309
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004310 // Add this candidate
4311 CandidateSet.push_back(OverloadCandidate());
4312 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004313 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004314 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004315 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004316 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004317 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004318 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004319
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004320 unsigned NumArgsInProto = Proto->getNumArgs();
4321
4322 // (C++ 13.3.2p2): A candidate function having fewer than m
4323 // parameters is viable only if it has an ellipsis in its parameter
4324 // list (8.3.5).
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004325 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor2a920012009-09-23 14:56:09 +00004326 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004327 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004328 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004329 return;
4330 }
4331
4332 // (C++ 13.3.2p2): A candidate function having more than m parameters
4333 // is viable only if the (m+1)st parameter has a default argument
4334 // (8.3.6). For the purposes of overload resolution, the
4335 // parameter list is truncated on the right, so that there are
4336 // exactly m parameters.
4337 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00004338 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004339 // Not enough arguments.
4340 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004341 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004342 return;
4343 }
4344
Peter Collingbourne7277fe82011-10-02 23:49:40 +00004345 // (CUDA B.1): Check for invalid calls between targets.
4346 if (getLangOptions().CUDA)
4347 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4348 if (CheckCUDATarget(Caller, Function)) {
4349 Candidate.Viable = false;
4350 Candidate.FailureKind = ovl_fail_bad_target;
4351 return;
4352 }
4353
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004354 // Determine the implicit conversion sequences for each of the
4355 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004356 Candidate.Conversions.resize(NumArgs);
4357 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4358 if (ArgIdx < NumArgsInProto) {
4359 // (C++ 13.3.2p3): for F to be a viable function, there shall
4360 // exist for each argument an implicit conversion sequence
4361 // (13.3.3.1) that converts that argument to the corresponding
4362 // parameter of F.
4363 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004364 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004365 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004366 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004367 /*InOverloadResolution=*/true,
4368 /*AllowObjCWritebackConversion=*/
4369 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004370 if (Candidate.Conversions[ArgIdx].isBad()) {
4371 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004372 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00004373 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00004374 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004375 } else {
4376 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4377 // argument for which there is no corresponding parameter is
4378 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004379 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00004380 }
4381 }
4382}
4383
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004384/// \brief Add all of the function declarations in the given function set to
4385/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00004386void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004387 Expr **Args, unsigned NumArgs,
4388 OverloadCandidateSet& CandidateSet,
4389 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00004390 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00004391 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4392 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004393 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004394 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004395 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor02824322011-01-26 19:30:28 +00004396 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004397 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004398 CandidateSet, SuppressUserConversions);
4399 else
John McCalla0296f72010-03-19 07:35:19 +00004400 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004401 SuppressUserConversions);
4402 } else {
John McCalla0296f72010-03-19 07:35:19 +00004403 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004404 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4405 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00004406 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00004407 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00004408 /*FIXME: explicit args */ 0,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004409 Args[0]->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004410 Args[0]->Classify(Context),
4411 Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004412 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00004413 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004414 else
John McCalla0296f72010-03-19 07:35:19 +00004415 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00004416 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004417 Args, NumArgs, CandidateSet,
4418 SuppressUserConversions);
4419 }
Douglas Gregor15448f82009-06-27 21:05:07 +00004420 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004421}
4422
John McCallf0f1cf02009-11-17 07:50:12 +00004423/// AddMethodCandidate - Adds a named decl (which is some kind of
4424/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00004425void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004426 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004427 Expr::Classification ObjectClassification,
John McCallf0f1cf02009-11-17 07:50:12 +00004428 Expr **Args, unsigned NumArgs,
4429 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004430 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00004431 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00004432 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00004433
4434 if (isa<UsingShadowDecl>(Decl))
4435 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004436
John McCallf0f1cf02009-11-17 07:50:12 +00004437 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4438 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4439 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00004440 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4441 /*ExplicitArgs*/ 0,
Douglas Gregor02824322011-01-26 19:30:28 +00004442 ObjectType, ObjectClassification, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00004443 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004444 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004445 } else {
John McCalla0296f72010-03-19 07:35:19 +00004446 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor02824322011-01-26 19:30:28 +00004447 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004448 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00004449 }
4450}
4451
Douglas Gregor436424c2008-11-18 23:14:02 +00004452/// AddMethodCandidate - Adds the given C++ member function to the set
4453/// of candidate functions, using the given function call arguments
4454/// and the object argument (@c Object). For example, in a call
4455/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4456/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4457/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00004458/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00004459void
John McCalla0296f72010-03-19 07:35:19 +00004460Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00004461 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004462 Expr::Classification ObjectClassification,
John McCallb89836b2010-01-26 01:37:31 +00004463 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00004464 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004465 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00004466 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00004467 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00004468 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00004469 assert(!isa<CXXConstructorDecl>(Method) &&
4470 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00004471
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004472 if (!CandidateSet.isNewCandidate(Method))
4473 return;
4474
Douglas Gregor27381f32009-11-23 12:27:39 +00004475 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004476 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004477
Douglas Gregor436424c2008-11-18 23:14:02 +00004478 // Add this candidate
4479 CandidateSet.push_back(OverloadCandidate());
4480 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004481 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00004482 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004483 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004484 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004485 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00004486
4487 unsigned NumArgsInProto = Proto->getNumArgs();
4488
4489 // (C++ 13.3.2p2): A candidate function having fewer than m
4490 // parameters is viable only if it has an ellipsis in its parameter
4491 // list (8.3.5).
4492 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4493 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004494 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004495 return;
4496 }
4497
4498 // (C++ 13.3.2p2): A candidate function having more than m parameters
4499 // is viable only if the (m+1)st parameter has a default argument
4500 // (8.3.6). For the purposes of overload resolution, the
4501 // parameter list is truncated on the right, so that there are
4502 // exactly m parameters.
4503 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4504 if (NumArgs < MinRequiredArgs) {
4505 // Not enough arguments.
4506 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004507 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00004508 return;
4509 }
4510
4511 Candidate.Viable = true;
4512 Candidate.Conversions.resize(NumArgs + 1);
4513
John McCall6e9f8f62009-12-03 04:06:58 +00004514 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004515 // The implicit object argument is ignored.
4516 Candidate.IgnoreObjectArgument = true;
4517 else {
4518 // Determine the implicit conversion sequence for the object
4519 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00004520 Candidate.Conversions[0]
Douglas Gregor02824322011-01-26 19:30:28 +00004521 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4522 Method, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004523 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004524 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004525 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004526 return;
4527 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004528 }
4529
4530 // Determine the implicit conversion sequences for each of the
4531 // arguments.
4532 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4533 if (ArgIdx < NumArgsInProto) {
4534 // (C++ 13.3.2p3): for F to be a viable function, there shall
4535 // exist for each argument an implicit conversion sequence
4536 // (13.3.3.1) that converts that argument to the corresponding
4537 // parameter of F.
4538 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004539 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004540 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004541 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00004542 /*InOverloadResolution=*/true,
4543 /*AllowObjCWritebackConversion=*/
4544 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004545 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004546 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004547 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004548 break;
4549 }
4550 } else {
4551 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4552 // argument for which there is no corresponding parameter is
4553 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004554 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00004555 }
4556 }
4557}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004558
Douglas Gregor97628d62009-08-21 00:16:32 +00004559/// \brief Add a C++ member function template as a candidate to the candidate
4560/// set, using template argument deduction to produce an appropriate member
4561/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004562void
Douglas Gregor97628d62009-08-21 00:16:32 +00004563Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00004564 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004565 CXXRecordDecl *ActingContext,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004566 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00004567 QualType ObjectType,
Douglas Gregor02824322011-01-26 19:30:28 +00004568 Expr::Classification ObjectClassification,
John McCall6e9f8f62009-12-03 04:06:58 +00004569 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004570 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004571 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004572 if (!CandidateSet.isNewCandidate(MethodTmpl))
4573 return;
4574
Douglas Gregor97628d62009-08-21 00:16:32 +00004575 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004576 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00004577 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004578 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00004579 // candidate functions in the usual way.113) A given name can refer to one
4580 // or more function templates and also to a set of overloaded non-template
4581 // functions. In such a case, the candidate functions generated from each
4582 // function template are combined with the set of non-template candidate
4583 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004584 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00004585 FunctionDecl *Specialization = 0;
4586 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004587 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00004588 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004589 CandidateSet.push_back(OverloadCandidate());
4590 OverloadCandidate &Candidate = CandidateSet.back();
4591 Candidate.FoundDecl = FoundDecl;
4592 Candidate.Function = MethodTmpl->getTemplatedDecl();
4593 Candidate.Viable = false;
4594 Candidate.FailureKind = ovl_fail_bad_deduction;
4595 Candidate.IsSurrogate = false;
4596 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004597 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004598 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004599 Info);
4600 return;
4601 }
Mike Stump11289f42009-09-09 15:08:12 +00004602
Douglas Gregor97628d62009-08-21 00:16:32 +00004603 // Add the function template specialization produced by template argument
4604 // deduction as a candidate.
4605 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00004606 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00004607 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00004608 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor02824322011-01-26 19:30:28 +00004609 ActingContext, ObjectType, ObjectClassification,
4610 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00004611}
4612
Douglas Gregor05155d82009-08-21 23:19:43 +00004613/// \brief Add a C++ function template specialization as a candidate
4614/// in the candidate set, using template argument deduction to produce
4615/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00004616void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004617Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004618 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00004619 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004620 Expr **Args, unsigned NumArgs,
4621 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004622 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004623 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4624 return;
4625
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004626 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00004627 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004628 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00004629 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004630 // candidate functions in the usual way.113) A given name can refer to one
4631 // or more function templates and also to a set of overloaded non-template
4632 // functions. In such a case, the candidate functions generated from each
4633 // function template are combined with the set of non-template candidate
4634 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00004635 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004636 FunctionDecl *Specialization = 0;
4637 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00004638 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00004639 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00004640 CandidateSet.push_back(OverloadCandidate());
4641 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004642 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00004643 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4644 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004645 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00004646 Candidate.IsSurrogate = false;
4647 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004648 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004649 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004650 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004651 return;
4652 }
Mike Stump11289f42009-09-09 15:08:12 +00004653
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004654 // Add the function template specialization produced by template argument
4655 // deduction as a candidate.
4656 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004657 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00004658 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00004659}
Mike Stump11289f42009-09-09 15:08:12 +00004660
Douglas Gregora1f013e2008-11-07 22:36:19 +00004661/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00004662/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00004663/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00004664/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00004665/// (which may or may not be the same type as the type that the
4666/// conversion function produces).
4667void
4668Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004669 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004670 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00004671 Expr *From, QualType ToType,
4672 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00004673 assert(!Conversion->getDescribedFunctionTemplate() &&
4674 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00004675 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004676 if (!CandidateSet.isNewCandidate(Conversion))
4677 return;
4678
Douglas Gregor27381f32009-11-23 12:27:39 +00004679 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004680 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004681
Douglas Gregora1f013e2008-11-07 22:36:19 +00004682 // Add this candidate
4683 CandidateSet.push_back(OverloadCandidate());
4684 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004685 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004686 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004687 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004688 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004689 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00004690 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00004691 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00004692 Candidate.Viable = true;
4693 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004694 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004695
Douglas Gregor6affc782010-08-19 15:37:02 +00004696 // C++ [over.match.funcs]p4:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004697 // For conversion functions, the function is considered to be a member of
4698 // the class of the implicit implied object argument for the purpose of
Douglas Gregor6affc782010-08-19 15:37:02 +00004699 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004700 //
4701 // Determine the implicit conversion sequence for the implicit
4702 // object parameter.
4703 QualType ImplicitParamType = From->getType();
4704 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4705 ImplicitParamType = FromPtrType->getPointeeType();
4706 CXXRecordDecl *ConversionContext
4707 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004708
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004709 Candidate.Conversions[0]
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004710 = TryObjectArgumentInitialization(*this, From->getType(),
4711 From->Classify(Context),
Douglas Gregor02824322011-01-26 19:30:28 +00004712 Conversion, ConversionContext);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004713
John McCall0d1da222010-01-12 00:44:57 +00004714 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004715 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004716 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004717 return;
4718 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00004719
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004720 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004721 // derived to base as such conversions are given Conversion Rank. They only
4722 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4723 QualType FromCanon
4724 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4725 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4726 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4727 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004728 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00004729 return;
4730 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004731
Douglas Gregora1f013e2008-11-07 22:36:19 +00004732 // To determine what the conversion from the result of calling the
4733 // conversion function to the type we're eventually trying to
4734 // convert to (ToType), we need to synthesize a call to the
4735 // conversion function and attempt copy initialization from it. This
4736 // makes sure that we get the right semantics with respect to
4737 // lvalues/rvalues and the type. Fortunately, we can allocate this
4738 // call on the stack and we don't need its arguments to be
4739 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00004740 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00004741 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00004742 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4743 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00004744 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00004745 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00004746
Richard Smith48d24642011-07-13 22:53:21 +00004747 QualType ConversionType = Conversion->getConversionType();
4748 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor72ebdab2010-11-13 19:36:57 +00004749 Candidate.Viable = false;
4750 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4751 return;
4752 }
4753
Richard Smith48d24642011-07-13 22:53:21 +00004754 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCall7decc9e2010-11-18 06:31:45 +00004755
Mike Stump11289f42009-09-09 15:08:12 +00004756 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004757 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4758 // allocator).
Richard Smith48d24642011-07-13 22:53:21 +00004759 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCall7decc9e2010-11-18 06:31:45 +00004760 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00004761 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00004762 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004763 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004764 /*SuppressUserConversions=*/true,
John McCall31168b02011-06-15 23:02:42 +00004765 /*InOverloadResolution=*/false,
4766 /*AllowObjCWritebackConversion=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00004767
John McCall0d1da222010-01-12 00:44:57 +00004768 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00004769 case ImplicitConversionSequence::StandardConversion:
4770 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004771
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004772 // C++ [over.ics.user]p3:
4773 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004774 // conversion function template, the second standard conversion sequence
Douglas Gregor2c326bc2010-04-12 23:42:09 +00004775 // shall have exact match rank.
4776 if (Conversion->getPrimaryTemplate() &&
4777 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4778 Candidate.Viable = false;
4779 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4780 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004781
Douglas Gregorcba72b12011-01-21 05:18:22 +00004782 // C++0x [dcl.init.ref]p5:
4783 // In the second case, if the reference is an rvalue reference and
4784 // the second standard conversion sequence of the user-defined
4785 // conversion sequence includes an lvalue-to-rvalue conversion, the
4786 // program is ill-formed.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004787 if (ToType->isRValueReferenceType() &&
Douglas Gregorcba72b12011-01-21 05:18:22 +00004788 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4789 Candidate.Viable = false;
4790 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4791 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00004792 break;
4793
4794 case ImplicitConversionSequence::BadConversion:
4795 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004796 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004797 break;
4798
4799 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004800 llvm_unreachable(
Douglas Gregora1f013e2008-11-07 22:36:19 +00004801 "Can only end up with a standard conversion sequence or failure");
4802 }
4803}
4804
Douglas Gregor05155d82009-08-21 23:19:43 +00004805/// \brief Adds a conversion function template specialization
4806/// candidate to the overload set, using template argument deduction
4807/// to deduce the template arguments of the conversion function
4808/// template from the type that we are converting to (C++
4809/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004810void
Douglas Gregor05155d82009-08-21 23:19:43 +00004811Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004812 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004813 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004814 Expr *From, QualType ToType,
4815 OverloadCandidateSet &CandidateSet) {
4816 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4817 "Only conversion function templates permitted here");
4818
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004819 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4820 return;
4821
John McCallbc077cf2010-02-08 23:07:23 +00004822 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004823 CXXConversionDecl *Specialization = 0;
4824 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004825 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004826 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004827 CandidateSet.push_back(OverloadCandidate());
4828 OverloadCandidate &Candidate = CandidateSet.back();
4829 Candidate.FoundDecl = FoundDecl;
4830 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4831 Candidate.Viable = false;
4832 Candidate.FailureKind = ovl_fail_bad_deduction;
4833 Candidate.IsSurrogate = false;
4834 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004835 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004836 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004837 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004838 return;
4839 }
Mike Stump11289f42009-09-09 15:08:12 +00004840
Douglas Gregor05155d82009-08-21 23:19:43 +00004841 // Add the conversion function template specialization produced by
4842 // template argument deduction as a candidate.
4843 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004844 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004845 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004846}
4847
Douglas Gregorab7897a2008-11-19 22:57:39 +00004848/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4849/// converts the given @c Object to a function pointer via the
4850/// conversion function @c Conversion, and then attempts to call it
4851/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4852/// the type of function that we'll eventually be calling.
4853void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004854 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004855 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004856 const FunctionProtoType *Proto,
Douglas Gregor02824322011-01-26 19:30:28 +00004857 Expr *Object,
John McCall6e9f8f62009-12-03 04:06:58 +00004858 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004859 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004860 if (!CandidateSet.isNewCandidate(Conversion))
4861 return;
4862
Douglas Gregor27381f32009-11-23 12:27:39 +00004863 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004864 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004865
Douglas Gregorab7897a2008-11-19 22:57:39 +00004866 CandidateSet.push_back(OverloadCandidate());
4867 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004868 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004869 Candidate.Function = 0;
4870 Candidate.Surrogate = Conversion;
4871 Candidate.Viable = true;
4872 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004873 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004874 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004875 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004876
4877 // Determine the implicit conversion sequence for the implicit
4878 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004879 ImplicitConversionSequence ObjectInit
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004880 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor02824322011-01-26 19:30:28 +00004881 Object->Classify(Context),
4882 Conversion, ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004883 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004884 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004885 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004886 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004887 return;
4888 }
4889
4890 // The first conversion is actually a user-defined conversion whose
4891 // first conversion is ObjectInit's standard conversion (which is
4892 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004893 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004894 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004895 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00004896 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004897 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCall30909032011-09-21 08:36:56 +00004898 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump11289f42009-09-09 15:08:12 +00004899 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004900 = Candidate.Conversions[0].UserDefined.Before;
4901 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4902
Mike Stump11289f42009-09-09 15:08:12 +00004903 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004904 unsigned NumArgsInProto = Proto->getNumArgs();
4905
4906 // (C++ 13.3.2p2): A candidate function having fewer than m
4907 // parameters is viable only if it has an ellipsis in its parameter
4908 // list (8.3.5).
4909 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4910 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004911 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004912 return;
4913 }
4914
4915 // Function types don't have any default arguments, so just check if
4916 // we have enough arguments.
4917 if (NumArgs < NumArgsInProto) {
4918 // Not enough arguments.
4919 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004920 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004921 return;
4922 }
4923
4924 // Determine the implicit conversion sequences for each of the
4925 // arguments.
4926 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4927 if (ArgIdx < NumArgsInProto) {
4928 // (C++ 13.3.2p3): for F to be a viable function, there shall
4929 // exist for each argument an implicit conversion sequence
4930 // (13.3.3.1) that converts that argument to the corresponding
4931 // parameter of F.
4932 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004933 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004934 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004935 /*SuppressUserConversions=*/false,
John McCall31168b02011-06-15 23:02:42 +00004936 /*InOverloadResolution=*/false,
4937 /*AllowObjCWritebackConversion=*/
4938 getLangOptions().ObjCAutoRefCount);
John McCall0d1da222010-01-12 00:44:57 +00004939 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004940 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004941 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004942 break;
4943 }
4944 } else {
4945 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4946 // argument for which there is no corresponding parameter is
4947 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004948 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004949 }
4950 }
4951}
4952
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004953/// \brief Add overload candidates for overloaded operators that are
4954/// member functions.
4955///
4956/// Add the overloaded operator candidates that are member functions
4957/// for the operator Op that was used in an operator expression such
4958/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4959/// CandidateSet will store the added overload candidates. (C++
4960/// [over.match.oper]).
4961void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4962 SourceLocation OpLoc,
4963 Expr **Args, unsigned NumArgs,
4964 OverloadCandidateSet& CandidateSet,
4965 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004966 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4967
4968 // C++ [over.match.oper]p3:
4969 // For a unary operator @ with an operand of a type whose
4970 // cv-unqualified version is T1, and for a binary operator @ with
4971 // a left operand of a type whose cv-unqualified version is T1 and
4972 // a right operand of a type whose cv-unqualified version is T2,
4973 // three sets of candidate functions, designated member
4974 // candidates, non-member candidates and built-in candidates, are
4975 // constructed as follows:
4976 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004977
4978 // -- If T1 is a class type, the set of member candidates is the
4979 // result of the qualified lookup of T1::operator@
4980 // (13.3.1.1.1); otherwise, the set of member candidates is
4981 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004982 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004983 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004984 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004985 return;
Mike Stump11289f42009-09-09 15:08:12 +00004986
John McCall27b18f82009-11-17 02:14:36 +00004987 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4988 LookupQualifiedName(Operators, T1Rec->getDecl());
4989 Operators.suppressDiagnostics();
4990
Mike Stump11289f42009-09-09 15:08:12 +00004991 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004992 OperEnd = Operators.end();
4993 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004994 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004995 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00004996 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor02824322011-01-26 19:30:28 +00004997 CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004998 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004999 }
Douglas Gregor436424c2008-11-18 23:14:02 +00005000}
5001
Douglas Gregora11693b2008-11-12 17:17:38 +00005002/// AddBuiltinCandidate - Add a candidate for a built-in
5003/// operator. ResultTy and ParamTys are the result and parameter types
5004/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00005005/// arguments being passed to the candidate. IsAssignmentOperator
5006/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00005007/// operator. NumContextualBoolArguments is the number of arguments
5008/// (at the beginning of the argument list) that will be contextually
5009/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00005010void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00005011 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00005012 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005013 bool IsAssignmentOperator,
5014 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00005015 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00005016 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00005017
Douglas Gregora11693b2008-11-12 17:17:38 +00005018 // Add this candidate
5019 CandidateSet.push_back(OverloadCandidate());
5020 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00005021 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00005022 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00005023 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005024 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00005025 Candidate.BuiltinTypes.ResultTy = ResultTy;
5026 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5027 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5028
5029 // Determine the implicit conversion sequences for each of the
5030 // arguments.
5031 Candidate.Viable = true;
5032 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00005033 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00005034 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00005035 // C++ [over.match.oper]p4:
5036 // For the built-in assignment operators, conversions of the
5037 // left operand are restricted as follows:
5038 // -- no temporaries are introduced to hold the left operand, and
5039 // -- no user-defined conversions are applied to the left
5040 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00005041 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00005042 //
5043 // We block these conversions by turning off user-defined
5044 // conversions, since that is the only way that initialization of
5045 // a reference to a non-class type can occur from something that
5046 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005047 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00005048 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00005049 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00005050 Candidate.Conversions[ArgIdx]
5051 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005052 } else {
Mike Stump11289f42009-09-09 15:08:12 +00005053 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00005054 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00005055 ArgIdx == 0 && IsAssignmentOperator,
John McCall31168b02011-06-15 23:02:42 +00005056 /*InOverloadResolution=*/false,
5057 /*AllowObjCWritebackConversion=*/
5058 getLangOptions().ObjCAutoRefCount);
Douglas Gregor5fb53972009-01-14 15:45:31 +00005059 }
John McCall0d1da222010-01-12 00:44:57 +00005060 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005061 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00005062 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00005063 break;
5064 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005065 }
5066}
5067
5068/// BuiltinCandidateTypeSet - A set of types that will be used for the
5069/// candidate operator functions for built-in operators (C++
5070/// [over.built]). The types are separated into pointer types and
5071/// enumeration types.
5072class BuiltinCandidateTypeSet {
5073 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005074 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00005075
5076 /// PointerTypes - The set of pointer types that will be used in the
5077 /// built-in candidates.
5078 TypeSet PointerTypes;
5079
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005080 /// MemberPointerTypes - The set of member pointer types that will be
5081 /// used in the built-in candidates.
5082 TypeSet MemberPointerTypes;
5083
Douglas Gregora11693b2008-11-12 17:17:38 +00005084 /// EnumerationTypes - The set of enumeration types that will be
5085 /// used in the built-in candidates.
5086 TypeSet EnumerationTypes;
5087
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005088 /// \brief The set of vector types that will be used in the built-in
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005089 /// candidates.
5090 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00005091
5092 /// \brief A flag indicating non-record types are viable candidates
5093 bool HasNonRecordTypes;
5094
5095 /// \brief A flag indicating whether either arithmetic or enumeration types
5096 /// were present in the candidate set.
5097 bool HasArithmeticOrEnumeralTypes;
5098
Douglas Gregor80af3132011-05-21 23:15:46 +00005099 /// \brief A flag indicating whether the nullptr type was present in the
5100 /// candidate set.
5101 bool HasNullPtrType;
5102
Douglas Gregor8a2e6012009-08-24 15:23:48 +00005103 /// Sema - The semantic analysis instance where we are building the
5104 /// candidate type set.
5105 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00005106
Douglas Gregora11693b2008-11-12 17:17:38 +00005107 /// Context - The AST context in which we will build the type sets.
5108 ASTContext &Context;
5109
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005110 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5111 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005112 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00005113
5114public:
5115 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005116 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00005117
Mike Stump11289f42009-09-09 15:08:12 +00005118 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00005119 : HasNonRecordTypes(false),
5120 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor80af3132011-05-21 23:15:46 +00005121 HasNullPtrType(false),
Chandler Carruth00a38332010-12-13 01:44:01 +00005122 SemaRef(SemaRef),
5123 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00005124
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005125 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005126 SourceLocation Loc,
5127 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005128 bool AllowExplicitConversions,
5129 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005130
5131 /// pointer_begin - First pointer type found;
5132 iterator pointer_begin() { return PointerTypes.begin(); }
5133
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005134 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005135 iterator pointer_end() { return PointerTypes.end(); }
5136
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005137 /// member_pointer_begin - First member pointer type found;
5138 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5139
5140 /// member_pointer_end - Past the last member pointer type found;
5141 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5142
Douglas Gregora11693b2008-11-12 17:17:38 +00005143 /// enumeration_begin - First enumeration type found;
5144 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5145
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005146 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00005147 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005148
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005149 iterator vector_begin() { return VectorTypes.begin(); }
5150 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00005151
5152 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5153 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor80af3132011-05-21 23:15:46 +00005154 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregora11693b2008-11-12 17:17:38 +00005155};
5156
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005157/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00005158/// the set of pointer types along with any more-qualified variants of
5159/// that type. For example, if @p Ty is "int const *", this routine
5160/// will add "int const *", "int const volatile *", "int const
5161/// restrict *", and "int const volatile restrict *" to the set of
5162/// pointer types. Returns true if the add of @p Ty itself succeeded,
5163/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005164///
5165/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005166bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005167BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5168 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00005169
Douglas Gregora11693b2008-11-12 17:17:38 +00005170 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00005171 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00005172 return false;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005173
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005174 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00005175 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005176 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005177 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005178 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005179 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005180 buildObjCPtr = true;
5181 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005182 else
David Blaikie83d382b2011-09-23 05:06:16 +00005183 llvm_unreachable("type was not a pointer type!");
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005184 }
5185 else
5186 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005187
Sebastian Redl4990a632009-11-18 20:39:26 +00005188 // Don't add qualified variants of arrays. For one, they're not allowed
5189 // (the qualifier would sink to the element type), and for another, the
5190 // only overload situation where it matters is subscript or pointer +- int,
5191 // and those shouldn't have qualifier variants anyway.
5192 if (PointeeTy->isArrayType())
5193 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005194 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00005195 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00005196 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005197 bool hasVolatile = VisibleQuals.hasVolatile();
5198 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005199
John McCall8ccfcb52009-09-24 19:53:00 +00005200 // Iterate through all strict supersets of BaseCVR.
5201 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5202 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005203 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5204 // in the types.
5205 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5206 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00005207 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00005208 if (!buildObjCPtr)
5209 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5210 else
5211 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00005212 }
5213
5214 return true;
5215}
5216
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005217/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5218/// to the set of pointer types along with any more-qualified variants of
5219/// that type. For example, if @p Ty is "int const *", this routine
5220/// will add "int const *", "int const volatile *", "int const
5221/// restrict *", and "int const volatile restrict *" to the set of
5222/// pointer types. Returns true if the add of @p Ty itself succeeded,
5223/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00005224///
5225/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005226bool
5227BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5228 QualType Ty) {
5229 // Insert this type.
5230 if (!MemberPointerTypes.insert(Ty))
5231 return false;
5232
John McCall8ccfcb52009-09-24 19:53:00 +00005233 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5234 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005235
John McCall8ccfcb52009-09-24 19:53:00 +00005236 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00005237 // Don't add qualified variants of arrays. For one, they're not allowed
5238 // (the qualifier would sink to the element type), and for another, the
5239 // only overload situation where it matters is subscript or pointer +- int,
5240 // and those shouldn't have qualifier variants anyway.
5241 if (PointeeTy->isArrayType())
5242 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00005243 const Type *ClassTy = PointerTy->getClass();
5244
5245 // Iterate through all strict supersets of the pointee type's CVR
5246 // qualifiers.
5247 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5248 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5249 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005250
John McCall8ccfcb52009-09-24 19:53:00 +00005251 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005252 MemberPointerTypes.insert(
5253 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005254 }
5255
5256 return true;
5257}
5258
Douglas Gregora11693b2008-11-12 17:17:38 +00005259/// AddTypesConvertedFrom - Add each of the types to which the type @p
5260/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005261/// primarily interested in pointer types and enumeration types. We also
5262/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00005263/// AllowUserConversions is true if we should look at the conversion
5264/// functions of a class type, and AllowExplicitConversions if we
5265/// should also include the explicit conversion functions of a class
5266/// type.
Mike Stump11289f42009-09-09 15:08:12 +00005267void
Douglas Gregor5fb53972009-01-14 15:45:31 +00005268BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00005269 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00005270 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005271 bool AllowExplicitConversions,
5272 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005273 // Only deal with canonical types.
5274 Ty = Context.getCanonicalType(Ty);
5275
5276 // Look through reference types; they aren't part of the type of an
5277 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00005278 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00005279 Ty = RefTy->getPointeeType();
5280
John McCall33ddac02011-01-19 10:06:00 +00005281 // If we're dealing with an array type, decay to the pointer.
5282 if (Ty->isArrayType())
5283 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5284
5285 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00005286 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00005287
Chandler Carruth00a38332010-12-13 01:44:01 +00005288 // Flag if we ever add a non-record type.
5289 const RecordType *TyRec = Ty->getAs<RecordType>();
5290 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5291
Chandler Carruth00a38332010-12-13 01:44:01 +00005292 // Flag if we encounter an arithmetic type.
5293 HasArithmeticOrEnumeralTypes =
5294 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5295
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00005296 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5297 PointerTypes.insert(Ty);
5298 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005299 // Insert our type, and its more-qualified variants, into the set
5300 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005301 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00005302 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00005303 } else if (Ty->isMemberPointerType()) {
5304 // Member pointers are far easier, since the pointee can't be converted.
5305 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5306 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00005307 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005308 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00005309 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005310 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005311 // We treat vector types as arithmetic types in many contexts as an
5312 // extension.
5313 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005314 VectorTypes.insert(Ty);
Douglas Gregor80af3132011-05-21 23:15:46 +00005315 } else if (Ty->isNullPtrType()) {
5316 HasNullPtrType = true;
Chandler Carruth00a38332010-12-13 01:44:01 +00005317 } else if (AllowUserConversions && TyRec) {
5318 // No conversion functions in incomplete types.
5319 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5320 return;
Mike Stump11289f42009-09-09 15:08:12 +00005321
Chandler Carruth00a38332010-12-13 01:44:01 +00005322 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5323 const UnresolvedSetImpl *Conversions
5324 = ClassDecl->getVisibleConversionFunctions();
5325 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5326 E = Conversions->end(); I != E; ++I) {
5327 NamedDecl *D = I.getDecl();
5328 if (isa<UsingShadowDecl>(D))
5329 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00005330
Chandler Carruth00a38332010-12-13 01:44:01 +00005331 // Skip conversion function templates; they don't tell us anything
5332 // about which builtin types we can convert to.
5333 if (isa<FunctionTemplateDecl>(D))
5334 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00005335
Chandler Carruth00a38332010-12-13 01:44:01 +00005336 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5337 if (AllowExplicitConversions || !Conv->isExplicit()) {
5338 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5339 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00005340 }
5341 }
5342 }
5343}
5344
Douglas Gregor84605ae2009-08-24 13:43:27 +00005345/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5346/// the volatile- and non-volatile-qualified assignment operators for the
5347/// given type to the candidate set.
5348static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5349 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00005350 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00005351 unsigned NumArgs,
5352 OverloadCandidateSet &CandidateSet) {
5353 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00005354
Douglas Gregor84605ae2009-08-24 13:43:27 +00005355 // T& operator=(T&, T)
5356 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5357 ParamTypes[1] = T;
5358 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5359 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00005360
Douglas Gregor84605ae2009-08-24 13:43:27 +00005361 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5362 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00005363 ParamTypes[0]
5364 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00005365 ParamTypes[1] = T;
5366 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00005367 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00005368 }
5369}
Mike Stump11289f42009-09-09 15:08:12 +00005370
Sebastian Redl1054fae2009-10-25 17:03:50 +00005371/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5372/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005373static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5374 Qualifiers VRQuals;
5375 const RecordType *TyRec;
5376 if (const MemberPointerType *RHSMPType =
5377 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00005378 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005379 else
5380 TyRec = ArgExpr->getType()->getAs<RecordType>();
5381 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00005382 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005383 VRQuals.addVolatile();
5384 VRQuals.addRestrict();
5385 return VRQuals;
5386 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005387
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005388 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00005389 if (!ClassDecl->hasDefinition())
5390 return VRQuals;
5391
John McCallad371252010-01-20 00:46:10 +00005392 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00005393 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005394
John McCallad371252010-01-20 00:46:10 +00005395 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00005396 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00005397 NamedDecl *D = I.getDecl();
5398 if (isa<UsingShadowDecl>(D))
5399 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5400 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005401 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5402 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5403 CanTy = ResTypeRef->getPointeeType();
5404 // Need to go down the pointer/mempointer chain and add qualifiers
5405 // as see them.
5406 bool done = false;
5407 while (!done) {
5408 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5409 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005410 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005411 CanTy->getAs<MemberPointerType>())
5412 CanTy = ResTypeMPtr->getPointeeType();
5413 else
5414 done = true;
5415 if (CanTy.isVolatileQualified())
5416 VRQuals.addVolatile();
5417 if (CanTy.isRestrictQualified())
5418 VRQuals.addRestrict();
5419 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5420 return VRQuals;
5421 }
5422 }
5423 }
5424 return VRQuals;
5425}
John McCall52872982010-11-13 05:51:15 +00005426
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005427namespace {
John McCall52872982010-11-13 05:51:15 +00005428
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005429/// \brief Helper class to manage the addition of builtin operator overload
5430/// candidates. It provides shared state and utility methods used throughout
5431/// the process, as well as a helper method to add each group of builtin
5432/// operator overloads from the standard to a candidate set.
5433class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005434 // Common instance state available to all overload candidate addition methods.
5435 Sema &S;
5436 Expr **Args;
5437 unsigned NumArgs;
5438 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00005439 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005440 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruthc6586e52010-12-12 10:35:00 +00005441 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005442
Chandler Carruthc6586e52010-12-12 10:35:00 +00005443 // Define some constants used to index and iterate over the arithemetic types
5444 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00005445 // The "promoted arithmetic types" are the arithmetic
5446 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00005447 static const unsigned FirstIntegralType = 3;
5448 static const unsigned LastIntegralType = 18;
5449 static const unsigned FirstPromotedIntegralType = 3,
5450 LastPromotedIntegralType = 9;
5451 static const unsigned FirstPromotedArithmeticType = 0,
5452 LastPromotedArithmeticType = 9;
5453 static const unsigned NumArithmeticTypes = 18;
5454
Chandler Carruthc6586e52010-12-12 10:35:00 +00005455 /// \brief Get the canonical type for a given arithmetic type index.
5456 CanQualType getArithmeticType(unsigned index) {
5457 assert(index < NumArithmeticTypes);
5458 static CanQualType ASTContext::* const
5459 ArithmeticTypes[NumArithmeticTypes] = {
5460 // Start of promoted types.
5461 &ASTContext::FloatTy,
5462 &ASTContext::DoubleTy,
5463 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00005464
Chandler Carruthc6586e52010-12-12 10:35:00 +00005465 // Start of integral types.
5466 &ASTContext::IntTy,
5467 &ASTContext::LongTy,
5468 &ASTContext::LongLongTy,
5469 &ASTContext::UnsignedIntTy,
5470 &ASTContext::UnsignedLongTy,
5471 &ASTContext::UnsignedLongLongTy,
5472 // End of promoted types.
5473
5474 &ASTContext::BoolTy,
5475 &ASTContext::CharTy,
5476 &ASTContext::WCharTy,
5477 &ASTContext::Char16Ty,
5478 &ASTContext::Char32Ty,
5479 &ASTContext::SignedCharTy,
5480 &ASTContext::ShortTy,
5481 &ASTContext::UnsignedCharTy,
5482 &ASTContext::UnsignedShortTy,
5483 // End of integral types.
5484 // FIXME: What about complex?
5485 };
5486 return S.Context.*ArithmeticTypes[index];
5487 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005488
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005489 /// \brief Gets the canonical type resulting from the usual arithemetic
5490 /// converions for the given arithmetic types.
5491 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5492 // Accelerator table for performing the usual arithmetic conversions.
5493 // The rules are basically:
5494 // - if either is floating-point, use the wider floating-point
5495 // - if same signedness, use the higher rank
5496 // - if same size, use unsigned of the higher rank
5497 // - use the larger type
5498 // These rules, together with the axiom that higher ranks are
5499 // never smaller, are sufficient to precompute all of these results
5500 // *except* when dealing with signed types of higher rank.
5501 // (we could precompute SLL x UI for all known platforms, but it's
5502 // better not to make any assumptions).
5503 enum PromotedType {
5504 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5505 };
5506 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5507 [LastPromotedArithmeticType] = {
5508 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5509 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5510 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5511 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5512 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5513 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5514 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5515 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5516 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5517 };
5518
5519 assert(L < LastPromotedArithmeticType);
5520 assert(R < LastPromotedArithmeticType);
5521 int Idx = ConversionsTable[L][R];
5522
5523 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005524 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005525
5526 // Slow path: we need to compare widths.
5527 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005528 CanQualType LT = getArithmeticType(L),
5529 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005530 unsigned LW = S.Context.getIntWidth(LT),
5531 RW = S.Context.getIntWidth(RT);
5532
5533 // If they're different widths, use the signed type.
5534 if (LW > RW) return LT;
5535 else if (LW < RW) return RT;
5536
5537 // Otherwise, use the unsigned type of the signed type's rank.
5538 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5539 assert(L == SLL || R == SLL);
5540 return S.Context.UnsignedLongLongTy;
5541 }
5542
Chandler Carruth5659c0c2010-12-12 09:22:45 +00005543 /// \brief Helper method to factor out the common pattern of adding overloads
5544 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005545 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5546 bool HasVolatile) {
5547 QualType ParamTypes[2] = {
5548 S.Context.getLValueReferenceType(CandidateTy),
5549 S.Context.IntTy
5550 };
5551
5552 // Non-volatile version.
5553 if (NumArgs == 1)
5554 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5555 else
5556 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5557
5558 // Use a heuristic to reduce number of builtin candidates in the set:
5559 // add volatile version only if there are conversions to a volatile type.
5560 if (HasVolatile) {
5561 ParamTypes[0] =
5562 S.Context.getLValueReferenceType(
5563 S.Context.getVolatileType(CandidateTy));
5564 if (NumArgs == 1)
5565 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5566 else
5567 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5568 }
5569 }
5570
5571public:
5572 BuiltinOperatorOverloadBuilder(
5573 Sema &S, Expr **Args, unsigned NumArgs,
5574 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005575 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005576 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005577 OverloadCandidateSet &CandidateSet)
5578 : S(S), Args(Args), NumArgs(NumArgs),
5579 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00005580 HasArithmeticOrEnumeralCandidateType(
5581 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005582 CandidateTypes(CandidateTypes),
5583 CandidateSet(CandidateSet) {
5584 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00005585 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005586 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005587 assert(getArithmeticType(LastPromotedIntegralType - 1)
5588 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005589 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005590 assert(getArithmeticType(FirstPromotedArithmeticType)
5591 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005592 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00005593 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5594 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005595 "Invalid last promoted arithmetic type");
5596 }
5597
5598 // C++ [over.built]p3:
5599 //
5600 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5601 // is either volatile or empty, there exist candidate operator
5602 // functions of the form
5603 //
5604 // VQ T& operator++(VQ T&);
5605 // T operator++(VQ T&, int);
5606 //
5607 // C++ [over.built]p4:
5608 //
5609 // For every pair (T, VQ), where T is an arithmetic type other
5610 // than bool, and VQ is either volatile or empty, there exist
5611 // candidate operator functions of the form
5612 //
5613 // VQ T& operator--(VQ T&);
5614 // T operator--(VQ T&, int);
5615 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005616 if (!HasArithmeticOrEnumeralCandidateType)
5617 return;
5618
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005619 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5620 Arith < NumArithmeticTypes; ++Arith) {
5621 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00005622 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005623 VisibleTypeConversionsQuals.hasVolatile());
5624 }
5625 }
5626
5627 // C++ [over.built]p5:
5628 //
5629 // For every pair (T, VQ), where T is a cv-qualified or
5630 // cv-unqualified object type, and VQ is either volatile or
5631 // empty, there exist candidate operator functions of the form
5632 //
5633 // T*VQ& operator++(T*VQ&);
5634 // T*VQ& operator--(T*VQ&);
5635 // T* operator++(T*VQ&, int);
5636 // T* operator--(T*VQ&, int);
5637 void addPlusPlusMinusMinusPointerOverloads() {
5638 for (BuiltinCandidateTypeSet::iterator
5639 Ptr = CandidateTypes[0].pointer_begin(),
5640 PtrEnd = CandidateTypes[0].pointer_end();
5641 Ptr != PtrEnd; ++Ptr) {
5642 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00005643 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005644 continue;
5645
5646 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5647 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5648 VisibleTypeConversionsQuals.hasVolatile()));
5649 }
5650 }
5651
5652 // C++ [over.built]p6:
5653 // For every cv-qualified or cv-unqualified object type T, there
5654 // exist candidate operator functions of the form
5655 //
5656 // T& operator*(T*);
5657 //
5658 // C++ [over.built]p7:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005659 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor02824322011-01-26 19:30:28 +00005660 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005661 // T& operator*(T*);
5662 void addUnaryStarPointerOverloads() {
5663 for (BuiltinCandidateTypeSet::iterator
5664 Ptr = CandidateTypes[0].pointer_begin(),
5665 PtrEnd = CandidateTypes[0].pointer_end();
5666 Ptr != PtrEnd; ++Ptr) {
5667 QualType ParamTy = *Ptr;
5668 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005669 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5670 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005671
Douglas Gregor02824322011-01-26 19:30:28 +00005672 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5673 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5674 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00005675
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005676 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5677 &ParamTy, Args, 1, CandidateSet);
5678 }
5679 }
5680
5681 // C++ [over.built]p9:
5682 // For every promoted arithmetic type T, there exist candidate
5683 // operator functions of the form
5684 //
5685 // T operator+(T);
5686 // T operator-(T);
5687 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005688 if (!HasArithmeticOrEnumeralCandidateType)
5689 return;
5690
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005691 for (unsigned Arith = FirstPromotedArithmeticType;
5692 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005693 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005694 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5695 }
5696
5697 // Extension: We also add these operators for vector types.
5698 for (BuiltinCandidateTypeSet::iterator
5699 Vec = CandidateTypes[0].vector_begin(),
5700 VecEnd = CandidateTypes[0].vector_end();
5701 Vec != VecEnd; ++Vec) {
5702 QualType VecTy = *Vec;
5703 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5704 }
5705 }
5706
5707 // C++ [over.built]p8:
5708 // For every type T, there exist candidate operator functions of
5709 // the form
5710 //
5711 // T* operator+(T*);
5712 void addUnaryPlusPointerOverloads() {
5713 for (BuiltinCandidateTypeSet::iterator
5714 Ptr = CandidateTypes[0].pointer_begin(),
5715 PtrEnd = CandidateTypes[0].pointer_end();
5716 Ptr != PtrEnd; ++Ptr) {
5717 QualType ParamTy = *Ptr;
5718 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5719 }
5720 }
5721
5722 // C++ [over.built]p10:
5723 // For every promoted integral type T, there exist candidate
5724 // operator functions of the form
5725 //
5726 // T operator~(T);
5727 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005728 if (!HasArithmeticOrEnumeralCandidateType)
5729 return;
5730
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005731 for (unsigned Int = FirstPromotedIntegralType;
5732 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005733 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005734 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5735 }
5736
5737 // Extension: We also add this operator for vector types.
5738 for (BuiltinCandidateTypeSet::iterator
5739 Vec = CandidateTypes[0].vector_begin(),
5740 VecEnd = CandidateTypes[0].vector_end();
5741 Vec != VecEnd; ++Vec) {
5742 QualType VecTy = *Vec;
5743 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5744 }
5745 }
5746
5747 // C++ [over.match.oper]p16:
5748 // For every pointer to member type T, there exist candidate operator
5749 // functions of the form
5750 //
5751 // bool operator==(T,T);
5752 // bool operator!=(T,T);
5753 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5754 /// Set of (canonical) types that we've already handled.
5755 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5756
5757 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5758 for (BuiltinCandidateTypeSet::iterator
5759 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5760 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5761 MemPtr != MemPtrEnd;
5762 ++MemPtr) {
5763 // Don't add the same builtin candidate twice.
5764 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5765 continue;
5766
5767 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5768 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5769 CandidateSet);
5770 }
5771 }
5772 }
5773
5774 // C++ [over.built]p15:
5775 //
Douglas Gregor80af3132011-05-21 23:15:46 +00005776 // For every T, where T is an enumeration type, a pointer type, or
5777 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005778 //
5779 // bool operator<(T, T);
5780 // bool operator>(T, T);
5781 // bool operator<=(T, T);
5782 // bool operator>=(T, T);
5783 // bool operator==(T, T);
5784 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005785 void addRelationalPointerOrEnumeralOverloads() {
5786 // C++ [over.built]p1:
5787 // If there is a user-written candidate with the same name and parameter
5788 // types as a built-in candidate operator function, the built-in operator
5789 // function is hidden and is not included in the set of candidate
5790 // functions.
5791 //
5792 // The text is actually in a note, but if we don't implement it then we end
5793 // up with ambiguities when the user provides an overloaded operator for
5794 // an enumeration type. Note that only enumeration types have this problem,
5795 // so we track which enumeration types we've seen operators for. Also, the
5796 // only other overloaded operator with enumeration argumenst, operator=,
5797 // cannot be overloaded for enumeration types, so this is the only place
5798 // where we must suppress candidates like this.
5799 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5800 UserDefinedBinaryOperators;
5801
5802 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5803 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5804 CandidateTypes[ArgIdx].enumeration_end()) {
5805 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5806 CEnd = CandidateSet.end();
5807 C != CEnd; ++C) {
5808 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5809 continue;
5810
5811 QualType FirstParamType =
5812 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5813 QualType SecondParamType =
5814 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5815
5816 // Skip if either parameter isn't of enumeral type.
5817 if (!FirstParamType->isEnumeralType() ||
5818 !SecondParamType->isEnumeralType())
5819 continue;
5820
5821 // Add this operator to the set of known user-defined operators.
5822 UserDefinedBinaryOperators.insert(
5823 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5824 S.Context.getCanonicalType(SecondParamType)));
5825 }
5826 }
5827 }
5828
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005829 /// Set of (canonical) types that we've already handled.
5830 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5831
5832 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5833 for (BuiltinCandidateTypeSet::iterator
5834 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5835 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5836 Ptr != PtrEnd; ++Ptr) {
5837 // Don't add the same builtin candidate twice.
5838 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5839 continue;
5840
5841 QualType ParamTypes[2] = { *Ptr, *Ptr };
5842 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5843 CandidateSet);
5844 }
5845 for (BuiltinCandidateTypeSet::iterator
5846 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5847 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5848 Enum != EnumEnd; ++Enum) {
5849 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5850
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005851 // Don't add the same builtin candidate twice, or if a user defined
5852 // candidate exists.
5853 if (!AddedTypes.insert(CanonType) ||
5854 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5855 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005856 continue;
5857
5858 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005859 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5860 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005861 }
Douglas Gregor80af3132011-05-21 23:15:46 +00005862
5863 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5864 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5865 if (AddedTypes.insert(NullPtrTy) &&
5866 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5867 NullPtrTy))) {
5868 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5869 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5870 CandidateSet);
5871 }
5872 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005873 }
5874 }
5875
5876 // C++ [over.built]p13:
5877 //
5878 // For every cv-qualified or cv-unqualified object type T
5879 // there exist candidate operator functions of the form
5880 //
5881 // T* operator+(T*, ptrdiff_t);
5882 // T& operator[](T*, ptrdiff_t); [BELOW]
5883 // T* operator-(T*, ptrdiff_t);
5884 // T* operator+(ptrdiff_t, T*);
5885 // T& operator[](ptrdiff_t, T*); [BELOW]
5886 //
5887 // C++ [over.built]p14:
5888 //
5889 // For every T, where T is a pointer to object type, there
5890 // exist candidate operator functions of the form
5891 //
5892 // ptrdiff_t operator-(T, T);
5893 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5894 /// Set of (canonical) types that we've already handled.
5895 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5896
5897 for (int Arg = 0; Arg < 2; ++Arg) {
5898 QualType AsymetricParamTypes[2] = {
5899 S.Context.getPointerDiffType(),
5900 S.Context.getPointerDiffType(),
5901 };
5902 for (BuiltinCandidateTypeSet::iterator
5903 Ptr = CandidateTypes[Arg].pointer_begin(),
5904 PtrEnd = CandidateTypes[Arg].pointer_end();
5905 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005906 QualType PointeeTy = (*Ptr)->getPointeeType();
5907 if (!PointeeTy->isObjectType())
5908 continue;
5909
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005910 AsymetricParamTypes[Arg] = *Ptr;
5911 if (Arg == 0 || Op == OO_Plus) {
5912 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5913 // T* operator+(ptrdiff_t, T*);
5914 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5915 CandidateSet);
5916 }
5917 if (Op == OO_Minus) {
5918 // ptrdiff_t operator-(T, T);
5919 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5920 continue;
5921
5922 QualType ParamTypes[2] = { *Ptr, *Ptr };
5923 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5924 Args, 2, CandidateSet);
5925 }
5926 }
5927 }
5928 }
5929
5930 // C++ [over.built]p12:
5931 //
5932 // For every pair of promoted arithmetic types L and R, there
5933 // exist candidate operator functions of the form
5934 //
5935 // LR operator*(L, R);
5936 // LR operator/(L, R);
5937 // LR operator+(L, R);
5938 // LR operator-(L, R);
5939 // bool operator<(L, R);
5940 // bool operator>(L, R);
5941 // bool operator<=(L, R);
5942 // bool operator>=(L, R);
5943 // bool operator==(L, R);
5944 // bool operator!=(L, R);
5945 //
5946 // where LR is the result of the usual arithmetic conversions
5947 // between types L and R.
5948 //
5949 // C++ [over.built]p24:
5950 //
5951 // For every pair of promoted arithmetic types L and R, there exist
5952 // candidate operator functions of the form
5953 //
5954 // LR operator?(bool, L, R);
5955 //
5956 // where LR is the result of the usual arithmetic conversions
5957 // between types L and R.
5958 // Our candidates ignore the first parameter.
5959 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005960 if (!HasArithmeticOrEnumeralCandidateType)
5961 return;
5962
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005963 for (unsigned Left = FirstPromotedArithmeticType;
5964 Left < LastPromotedArithmeticType; ++Left) {
5965 for (unsigned Right = FirstPromotedArithmeticType;
5966 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005967 QualType LandR[2] = { getArithmeticType(Left),
5968 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005969 QualType Result =
5970 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005971 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005972 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5973 }
5974 }
5975
5976 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5977 // conditional operator for vector types.
5978 for (BuiltinCandidateTypeSet::iterator
5979 Vec1 = CandidateTypes[0].vector_begin(),
5980 Vec1End = CandidateTypes[0].vector_end();
5981 Vec1 != Vec1End; ++Vec1) {
5982 for (BuiltinCandidateTypeSet::iterator
5983 Vec2 = CandidateTypes[1].vector_begin(),
5984 Vec2End = CandidateTypes[1].vector_end();
5985 Vec2 != Vec2End; ++Vec2) {
5986 QualType LandR[2] = { *Vec1, *Vec2 };
5987 QualType Result = S.Context.BoolTy;
5988 if (!isComparison) {
5989 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5990 Result = *Vec1;
5991 else
5992 Result = *Vec2;
5993 }
5994
5995 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5996 }
5997 }
5998 }
5999
6000 // C++ [over.built]p17:
6001 //
6002 // For every pair of promoted integral types L and R, there
6003 // exist candidate operator functions of the form
6004 //
6005 // LR operator%(L, R);
6006 // LR operator&(L, R);
6007 // LR operator^(L, R);
6008 // LR operator|(L, R);
6009 // L operator<<(L, R);
6010 // L operator>>(L, R);
6011 //
6012 // where LR is the result of the usual arithmetic conversions
6013 // between types L and R.
6014 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006015 if (!HasArithmeticOrEnumeralCandidateType)
6016 return;
6017
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006018 for (unsigned Left = FirstPromotedIntegralType;
6019 Left < LastPromotedIntegralType; ++Left) {
6020 for (unsigned Right = FirstPromotedIntegralType;
6021 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00006022 QualType LandR[2] = { getArithmeticType(Left),
6023 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006024 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6025 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00006026 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006027 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6028 }
6029 }
6030 }
6031
6032 // C++ [over.built]p20:
6033 //
6034 // For every pair (T, VQ), where T is an enumeration or
6035 // pointer to member type and VQ is either volatile or
6036 // empty, there exist candidate operator functions of the form
6037 //
6038 // VQ T& operator=(VQ T&, T);
6039 void addAssignmentMemberPointerOrEnumeralOverloads() {
6040 /// Set of (canonical) types that we've already handled.
6041 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6042
6043 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6044 for (BuiltinCandidateTypeSet::iterator
6045 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6046 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6047 Enum != EnumEnd; ++Enum) {
6048 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6049 continue;
6050
6051 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6052 CandidateSet);
6053 }
6054
6055 for (BuiltinCandidateTypeSet::iterator
6056 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6057 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6058 MemPtr != MemPtrEnd; ++MemPtr) {
6059 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6060 continue;
6061
6062 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6063 CandidateSet);
6064 }
6065 }
6066 }
6067
6068 // C++ [over.built]p19:
6069 //
6070 // For every pair (T, VQ), where T is any type and VQ is either
6071 // volatile or empty, there exist candidate operator functions
6072 // of the form
6073 //
6074 // T*VQ& operator=(T*VQ&, T*);
6075 //
6076 // C++ [over.built]p21:
6077 //
6078 // For every pair (T, VQ), where T is a cv-qualified or
6079 // cv-unqualified object type and VQ is either volatile or
6080 // empty, there exist candidate operator functions of the form
6081 //
6082 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6083 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6084 void addAssignmentPointerOverloads(bool isEqualOp) {
6085 /// Set of (canonical) types that we've already handled.
6086 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6087
6088 for (BuiltinCandidateTypeSet::iterator
6089 Ptr = CandidateTypes[0].pointer_begin(),
6090 PtrEnd = CandidateTypes[0].pointer_end();
6091 Ptr != PtrEnd; ++Ptr) {
6092 // If this is operator=, keep track of the builtin candidates we added.
6093 if (isEqualOp)
6094 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00006095 else if (!(*Ptr)->getPointeeType()->isObjectType())
6096 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006097
6098 // non-volatile version
6099 QualType ParamTypes[2] = {
6100 S.Context.getLValueReferenceType(*Ptr),
6101 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6102 };
6103 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6104 /*IsAssigmentOperator=*/ isEqualOp);
6105
6106 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6107 VisibleTypeConversionsQuals.hasVolatile()) {
6108 // volatile version
6109 ParamTypes[0] =
6110 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6111 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6112 /*IsAssigmentOperator=*/isEqualOp);
6113 }
6114 }
6115
6116 if (isEqualOp) {
6117 for (BuiltinCandidateTypeSet::iterator
6118 Ptr = CandidateTypes[1].pointer_begin(),
6119 PtrEnd = CandidateTypes[1].pointer_end();
6120 Ptr != PtrEnd; ++Ptr) {
6121 // Make sure we don't add the same candidate twice.
6122 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6123 continue;
6124
Chandler Carruth8e543b32010-12-12 08:17:55 +00006125 QualType ParamTypes[2] = {
6126 S.Context.getLValueReferenceType(*Ptr),
6127 *Ptr,
6128 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006129
6130 // non-volatile version
6131 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6132 /*IsAssigmentOperator=*/true);
6133
6134 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6135 VisibleTypeConversionsQuals.hasVolatile()) {
6136 // volatile version
6137 ParamTypes[0] =
6138 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00006139 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6140 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006141 }
6142 }
6143 }
6144 }
6145
6146 // C++ [over.built]p18:
6147 //
6148 // For every triple (L, VQ, R), where L is an arithmetic type,
6149 // VQ is either volatile or empty, and R is a promoted
6150 // arithmetic type, there exist candidate operator functions of
6151 // the form
6152 //
6153 // VQ L& operator=(VQ L&, R);
6154 // VQ L& operator*=(VQ L&, R);
6155 // VQ L& operator/=(VQ L&, R);
6156 // VQ L& operator+=(VQ L&, R);
6157 // VQ L& operator-=(VQ L&, R);
6158 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00006159 if (!HasArithmeticOrEnumeralCandidateType)
6160 return;
6161
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006162 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6163 for (unsigned Right = FirstPromotedArithmeticType;
6164 Right < LastPromotedArithmeticType; ++Right) {
6165 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006166 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006167
6168 // Add this built-in operator as a candidate (VQ is empty).
6169 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006170 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006171 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6172 /*IsAssigmentOperator=*/isEqualOp);
6173
6174 // Add this built-in operator as a candidate (VQ is 'volatile').
6175 if (VisibleTypeConversionsQuals.hasVolatile()) {
6176 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006177 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006178 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006179 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6180 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006181 /*IsAssigmentOperator=*/isEqualOp);
6182 }
6183 }
6184 }
6185
6186 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6187 for (BuiltinCandidateTypeSet::iterator
6188 Vec1 = CandidateTypes[0].vector_begin(),
6189 Vec1End = CandidateTypes[0].vector_end();
6190 Vec1 != Vec1End; ++Vec1) {
6191 for (BuiltinCandidateTypeSet::iterator
6192 Vec2 = CandidateTypes[1].vector_begin(),
6193 Vec2End = CandidateTypes[1].vector_end();
6194 Vec2 != Vec2End; ++Vec2) {
6195 QualType ParamTypes[2];
6196 ParamTypes[1] = *Vec2;
6197 // Add this built-in operator as a candidate (VQ is empty).
6198 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6199 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6200 /*IsAssigmentOperator=*/isEqualOp);
6201
6202 // Add this built-in operator as a candidate (VQ is 'volatile').
6203 if (VisibleTypeConversionsQuals.hasVolatile()) {
6204 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6205 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00006206 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6207 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006208 /*IsAssigmentOperator=*/isEqualOp);
6209 }
6210 }
6211 }
6212 }
6213
6214 // C++ [over.built]p22:
6215 //
6216 // For every triple (L, VQ, R), where L is an integral type, VQ
6217 // is either volatile or empty, and R is a promoted integral
6218 // type, there exist candidate operator functions of the form
6219 //
6220 // VQ L& operator%=(VQ L&, R);
6221 // VQ L& operator<<=(VQ L&, R);
6222 // VQ L& operator>>=(VQ L&, R);
6223 // VQ L& operator&=(VQ L&, R);
6224 // VQ L& operator^=(VQ L&, R);
6225 // VQ L& operator|=(VQ L&, R);
6226 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00006227 if (!HasArithmeticOrEnumeralCandidateType)
6228 return;
6229
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006230 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6231 for (unsigned Right = FirstPromotedIntegralType;
6232 Right < LastPromotedIntegralType; ++Right) {
6233 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00006234 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006235
6236 // Add this built-in operator as a candidate (VQ is empty).
6237 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00006238 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006239 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6240 if (VisibleTypeConversionsQuals.hasVolatile()) {
6241 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00006242 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006243 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6244 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6245 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6246 CandidateSet);
6247 }
6248 }
6249 }
6250 }
6251
6252 // C++ [over.operator]p23:
6253 //
6254 // There also exist candidate operator functions of the form
6255 //
6256 // bool operator!(bool);
6257 // bool operator&&(bool, bool);
6258 // bool operator||(bool, bool);
6259 void addExclaimOverload() {
6260 QualType ParamTy = S.Context.BoolTy;
6261 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6262 /*IsAssignmentOperator=*/false,
6263 /*NumContextualBoolArguments=*/1);
6264 }
6265 void addAmpAmpOrPipePipeOverload() {
6266 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6267 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6268 /*IsAssignmentOperator=*/false,
6269 /*NumContextualBoolArguments=*/2);
6270 }
6271
6272 // C++ [over.built]p13:
6273 //
6274 // For every cv-qualified or cv-unqualified object type T there
6275 // exist candidate operator functions of the form
6276 //
6277 // T* operator+(T*, ptrdiff_t); [ABOVE]
6278 // T& operator[](T*, ptrdiff_t);
6279 // T* operator-(T*, ptrdiff_t); [ABOVE]
6280 // T* operator+(ptrdiff_t, T*); [ABOVE]
6281 // T& operator[](ptrdiff_t, T*);
6282 void addSubscriptOverloads() {
6283 for (BuiltinCandidateTypeSet::iterator
6284 Ptr = CandidateTypes[0].pointer_begin(),
6285 PtrEnd = CandidateTypes[0].pointer_end();
6286 Ptr != PtrEnd; ++Ptr) {
6287 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6288 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006289 if (!PointeeType->isObjectType())
6290 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006291
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006292 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6293
6294 // T& operator[](T*, ptrdiff_t)
6295 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6296 }
6297
6298 for (BuiltinCandidateTypeSet::iterator
6299 Ptr = CandidateTypes[1].pointer_begin(),
6300 PtrEnd = CandidateTypes[1].pointer_end();
6301 Ptr != PtrEnd; ++Ptr) {
6302 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6303 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00006304 if (!PointeeType->isObjectType())
6305 continue;
6306
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006307 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6308
6309 // T& operator[](ptrdiff_t, T*)
6310 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6311 }
6312 }
6313
6314 // C++ [over.built]p11:
6315 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6316 // C1 is the same type as C2 or is a derived class of C2, T is an object
6317 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6318 // there exist candidate operator functions of the form
6319 //
6320 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6321 //
6322 // where CV12 is the union of CV1 and CV2.
6323 void addArrowStarOverloads() {
6324 for (BuiltinCandidateTypeSet::iterator
6325 Ptr = CandidateTypes[0].pointer_begin(),
6326 PtrEnd = CandidateTypes[0].pointer_end();
6327 Ptr != PtrEnd; ++Ptr) {
6328 QualType C1Ty = (*Ptr);
6329 QualType C1;
6330 QualifierCollector Q1;
6331 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6332 if (!isa<RecordType>(C1))
6333 continue;
6334 // heuristic to reduce number of builtin candidates in the set.
6335 // Add volatile/restrict version only if there are conversions to a
6336 // volatile/restrict type.
6337 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6338 continue;
6339 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6340 continue;
6341 for (BuiltinCandidateTypeSet::iterator
6342 MemPtr = CandidateTypes[1].member_pointer_begin(),
6343 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6344 MemPtr != MemPtrEnd; ++MemPtr) {
6345 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6346 QualType C2 = QualType(mptr->getClass(), 0);
6347 C2 = C2.getUnqualifiedType();
6348 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6349 break;
6350 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6351 // build CV12 T&
6352 QualType T = mptr->getPointeeType();
6353 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6354 T.isVolatileQualified())
6355 continue;
6356 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6357 T.isRestrictQualified())
6358 continue;
6359 T = Q1.apply(S.Context, T);
6360 QualType ResultTy = S.Context.getLValueReferenceType(T);
6361 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6362 }
6363 }
6364 }
6365
6366 // Note that we don't consider the first argument, since it has been
6367 // contextually converted to bool long ago. The candidates below are
6368 // therefore added as binary.
6369 //
6370 // C++ [over.built]p25:
6371 // For every type T, where T is a pointer, pointer-to-member, or scoped
6372 // enumeration type, there exist candidate operator functions of the form
6373 //
6374 // T operator?(bool, T, T);
6375 //
6376 void addConditionalOperatorOverloads() {
6377 /// Set of (canonical) types that we've already handled.
6378 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6379
6380 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6381 for (BuiltinCandidateTypeSet::iterator
6382 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6383 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6384 Ptr != PtrEnd; ++Ptr) {
6385 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6386 continue;
6387
6388 QualType ParamTypes[2] = { *Ptr, *Ptr };
6389 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6390 }
6391
6392 for (BuiltinCandidateTypeSet::iterator
6393 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6394 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6395 MemPtr != MemPtrEnd; ++MemPtr) {
6396 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6397 continue;
6398
6399 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6400 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6401 }
6402
6403 if (S.getLangOptions().CPlusPlus0x) {
6404 for (BuiltinCandidateTypeSet::iterator
6405 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6406 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6407 Enum != EnumEnd; ++Enum) {
6408 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6409 continue;
6410
6411 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6412 continue;
6413
6414 QualType ParamTypes[2] = { *Enum, *Enum };
6415 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6416 }
6417 }
6418 }
6419 }
6420};
6421
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006422} // end anonymous namespace
6423
6424/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6425/// operator overloads to the candidate set (C++ [over.built]), based
6426/// on the operator @p Op and the arguments given. For example, if the
6427/// operator is a binary '+', this routine might add "int
6428/// operator+(int, int)" to cover integer addition.
6429void
6430Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6431 SourceLocation OpLoc,
6432 Expr **Args, unsigned NumArgs,
6433 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00006434 // Find all of the types that the arguments can convert to, but only
6435 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00006436 // that make use of these types. Also record whether we encounter non-record
6437 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00006438 Qualifiers VisibleTypeConversionsQuals;
6439 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00006440 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6441 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00006442
6443 bool HasNonRecordCandidateType = false;
6444 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006445 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006446 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6447 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6448 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6449 OpLoc,
6450 true,
6451 (Op == OO_Exclaim ||
6452 Op == OO_AmpAmp ||
6453 Op == OO_PipePipe),
6454 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00006455 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6456 CandidateTypes[ArgIdx].hasNonRecordTypes();
6457 HasArithmeticOrEnumeralCandidateType =
6458 HasArithmeticOrEnumeralCandidateType ||
6459 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00006460 }
Douglas Gregora11693b2008-11-12 17:17:38 +00006461
Chandler Carruth00a38332010-12-13 01:44:01 +00006462 // Exit early when no non-record types have been added to the candidate set
6463 // for any of the arguments to the operator.
Douglas Gregor877d4eb2011-10-10 14:05:31 +00006464 //
6465 // We can't exit early for !, ||, or &&, since there we have always have
6466 // 'bool' overloads.
6467 if (!HasNonRecordCandidateType &&
6468 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth00a38332010-12-13 01:44:01 +00006469 return;
6470
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006471 // Setup an object to manage the common state for building overloads.
6472 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6473 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00006474 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006475 CandidateTypes, CandidateSet);
6476
6477 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00006478 switch (Op) {
6479 case OO_None:
6480 case NUM_OVERLOADED_OPERATORS:
David Blaikie83d382b2011-09-23 05:06:16 +00006481 llvm_unreachable("Expected an overloaded operator");
Douglas Gregora11693b2008-11-12 17:17:38 +00006482
Chandler Carruth5184de02010-12-12 08:51:33 +00006483 case OO_New:
6484 case OO_Delete:
6485 case OO_Array_New:
6486 case OO_Array_Delete:
6487 case OO_Call:
David Blaikie83d382b2011-09-23 05:06:16 +00006488 llvm_unreachable(
6489 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruth5184de02010-12-12 08:51:33 +00006490
6491 case OO_Comma:
6492 case OO_Arrow:
6493 // C++ [over.match.oper]p3:
6494 // -- For the operator ',', the unary operator '&', or the
6495 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00006496 break;
6497
6498 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006499 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006500 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00006501 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00006502
6503 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00006504 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006505 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006506 } else {
6507 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6508 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6509 }
Douglas Gregord08452f2008-11-19 15:42:04 +00006510 break;
6511
Chandler Carruth5184de02010-12-12 08:51:33 +00006512 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00006513 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00006514 OpBuilder.addUnaryStarPointerOverloads();
6515 else
6516 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6517 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006518
Chandler Carruth5184de02010-12-12 08:51:33 +00006519 case OO_Slash:
6520 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006521 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006522
6523 case OO_PlusPlus:
6524 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006525 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6526 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00006527 break;
6528
Douglas Gregor84605ae2009-08-24 13:43:27 +00006529 case OO_EqualEqual:
6530 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006531 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006532 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00006533
Douglas Gregora11693b2008-11-12 17:17:38 +00006534 case OO_Less:
6535 case OO_Greater:
6536 case OO_LessEqual:
6537 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00006538 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00006539 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6540 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006541
Douglas Gregora11693b2008-11-12 17:17:38 +00006542 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00006543 case OO_Caret:
6544 case OO_Pipe:
6545 case OO_LessLess:
6546 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006547 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00006548 break;
6549
Chandler Carruth5184de02010-12-12 08:51:33 +00006550 case OO_Amp: // '&' is either unary or binary
6551 if (NumArgs == 1)
6552 // C++ [over.match.oper]p3:
6553 // -- For the operator ',', the unary operator '&', or the
6554 // operator '->', the built-in candidates set is empty.
6555 break;
6556
6557 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6558 break;
6559
6560 case OO_Tilde:
6561 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6562 break;
6563
Douglas Gregora11693b2008-11-12 17:17:38 +00006564 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006565 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00006566 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00006567
6568 case OO_PlusEqual:
6569 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006570 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006571 // Fall through.
6572
6573 case OO_StarEqual:
6574 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006575 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00006576 break;
6577
6578 case OO_PercentEqual:
6579 case OO_LessLessEqual:
6580 case OO_GreaterGreaterEqual:
6581 case OO_AmpEqual:
6582 case OO_CaretEqual:
6583 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006584 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006585 break;
6586
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006587 case OO_Exclaim:
6588 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00006589 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00006590
Douglas Gregora11693b2008-11-12 17:17:38 +00006591 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006592 case OO_PipePipe:
6593 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00006594 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006595
6596 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006597 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006598 break;
6599
6600 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006601 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00006602 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00006603
6604 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00006605 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00006606 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6607 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00006608 }
6609}
6610
Douglas Gregore254f902009-02-04 00:32:51 +00006611/// \brief Add function candidates found via argument-dependent lookup
6612/// to the set of overloading candidates.
6613///
6614/// This routine performs argument-dependent name lookup based on the
6615/// given function name (which may also be an operator name) and adds
6616/// all of the overload candidates found by ADL to the overload
6617/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00006618void
Douglas Gregore254f902009-02-04 00:32:51 +00006619Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00006620 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00006621 Expr **Args, unsigned NumArgs,
Douglas Gregor739b107a2011-03-03 02:41:12 +00006622 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00006623 OverloadCandidateSet& CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00006624 bool PartialOverloading,
6625 bool StdNamespaceIsAssociated) {
John McCall8fe68082010-01-26 07:16:45 +00006626 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00006627
John McCall91f61fc2010-01-26 06:04:06 +00006628 // FIXME: This approach for uniquing ADL results (and removing
6629 // redundant candidates from the set) relies on pointer-equality,
6630 // which means we need to key off the canonical decl. However,
6631 // always going back to the canonical decl might not get us the
6632 // right set of default arguments. What default arguments are
6633 // we supposed to consider on ADL candidates, anyway?
6634
Douglas Gregorcabea402009-09-22 15:41:20 +00006635 // FIXME: Pass in the explicit template arguments?
Richard Smith02e85f32011-04-14 22:09:26 +00006636 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6637 StdNamespaceIsAssociated);
Douglas Gregore254f902009-02-04 00:32:51 +00006638
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006639 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006640 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6641 CandEnd = CandidateSet.end();
6642 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00006643 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00006644 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00006645 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00006646 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00006647 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00006648
6649 // For each of the ADL candidates we found, add it to the overload
6650 // set.
John McCall8fe68082010-01-26 07:16:45 +00006651 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00006652 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00006653 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00006654 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00006655 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006656
John McCalla0296f72010-03-19 07:35:19 +00006657 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00006658 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00006659 } else
John McCall4c4c1df2010-01-26 03:27:55 +00006660 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00006661 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00006662 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00006663 }
Douglas Gregore254f902009-02-04 00:32:51 +00006664}
6665
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006666/// isBetterOverloadCandidate - Determines whether the first overload
6667/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00006668bool
John McCall5c32be02010-08-24 20:38:10 +00006669isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006670 const OverloadCandidate &Cand1,
6671 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006672 SourceLocation Loc,
6673 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006674 // Define viable functions to be better candidates than non-viable
6675 // functions.
6676 if (!Cand2.Viable)
6677 return Cand1.Viable;
6678 else if (!Cand1.Viable)
6679 return false;
6680
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006681 // C++ [over.match.best]p1:
6682 //
6683 // -- if F is a static member function, ICS1(F) is defined such
6684 // that ICS1(F) is neither better nor worse than ICS1(G) for
6685 // any function G, and, symmetrically, ICS1(G) is neither
6686 // better nor worse than ICS1(F).
6687 unsigned StartArg = 0;
6688 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6689 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006690
Douglas Gregord3cb3562009-07-07 23:38:56 +00006691 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00006692 // A viable function F1 is defined to be a better function than another
6693 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00006694 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006695 unsigned NumArgs = Cand1.Conversions.size();
6696 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6697 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00006698 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00006699 switch (CompareImplicitConversionSequences(S,
6700 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006701 Cand2.Conversions[ArgIdx])) {
6702 case ImplicitConversionSequence::Better:
6703 // Cand1 has a better conversion sequence.
6704 HasBetterConversion = true;
6705 break;
6706
6707 case ImplicitConversionSequence::Worse:
6708 // Cand1 can't be better than Cand2.
6709 return false;
6710
6711 case ImplicitConversionSequence::Indistinguishable:
6712 // Do nothing.
6713 break;
6714 }
6715 }
6716
Mike Stump11289f42009-09-09 15:08:12 +00006717 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00006718 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006719 if (HasBetterConversion)
6720 return true;
6721
Mike Stump11289f42009-09-09 15:08:12 +00006722 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00006723 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00006724 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00006725 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6726 return true;
Mike Stump11289f42009-09-09 15:08:12 +00006727
6728 // -- F1 and F2 are function template specializations, and the function
6729 // template for F1 is more specialized than the template for F2
6730 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00006731 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00006732 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00006733 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006734 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00006735 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6736 Cand2.Function->getPrimaryTemplate(),
6737 Loc,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006738 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00006739 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00006740 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00006741 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00006742 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006743
Douglas Gregora1f013e2008-11-07 22:36:19 +00006744 // -- the context is an initialization by user-defined conversion
6745 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6746 // from the return type of F1 to the destination type (i.e.,
6747 // the type of the entity being initialized) is a better
6748 // conversion sequence than the standard conversion sequence
6749 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00006750 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00006751 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00006752 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00006753 switch (CompareStandardConversionSequences(S,
6754 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00006755 Cand2.FinalConversion)) {
6756 case ImplicitConversionSequence::Better:
6757 // Cand1 has a better conversion sequence.
6758 return true;
6759
6760 case ImplicitConversionSequence::Worse:
6761 // Cand1 can't be better than Cand2.
6762 return false;
6763
6764 case ImplicitConversionSequence::Indistinguishable:
6765 // Do nothing
6766 break;
6767 }
6768 }
6769
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006770 return false;
6771}
6772
Mike Stump11289f42009-09-09 15:08:12 +00006773/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006774/// within an overload candidate set.
6775///
6776/// \param CandidateSet the set of candidate functions.
6777///
6778/// \param Loc the location of the function name (or operator symbol) for
6779/// which overload resolution occurs.
6780///
Mike Stump11289f42009-09-09 15:08:12 +00006781/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006782/// function, Best points to the candidate function found.
6783///
6784/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00006785OverloadingResult
6786OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00006787 iterator &Best,
Chandler Carruth30141632011-02-25 19:41:05 +00006788 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006789 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00006790 Best = end();
6791 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6792 if (Cand->Viable)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006793 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006794 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006795 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006796 }
6797
6798 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00006799 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006800 return OR_No_Viable_Function;
6801
6802 // Make sure that this function is better than every other viable
6803 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00006804 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00006805 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006806 Cand != Best &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00006807 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregord5b730c92010-09-12 08:07:23 +00006808 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00006809 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006810 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00006811 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006812 }
Mike Stump11289f42009-09-09 15:08:12 +00006813
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006814 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00006815 if (Best->Function &&
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00006816 (Best->Function->isDeleted() ||
6817 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006818 return OR_Deleted;
6819
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006820 return OR_Success;
6821}
6822
John McCall53262c92010-01-12 02:15:36 +00006823namespace {
6824
6825enum OverloadCandidateKind {
6826 oc_function,
6827 oc_method,
6828 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006829 oc_function_template,
6830 oc_method_template,
6831 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006832 oc_implicit_default_constructor,
6833 oc_implicit_copy_constructor,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006834 oc_implicit_move_constructor,
Sebastian Redl08905022011-02-05 19:23:19 +00006835 oc_implicit_copy_assignment,
Alexis Hunt119c10e2011-05-25 23:16:36 +00006836 oc_implicit_move_assignment,
Sebastian Redl08905022011-02-05 19:23:19 +00006837 oc_implicit_inherited_constructor
John McCall53262c92010-01-12 02:15:36 +00006838};
6839
John McCalle1ac8d12010-01-13 00:25:19 +00006840OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6841 FunctionDecl *Fn,
6842 std::string &Description) {
6843 bool isTemplate = false;
6844
6845 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6846 isTemplate = true;
6847 Description = S.getTemplateArgumentBindingsText(
6848 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6849 }
John McCallfd0b2f82010-01-06 09:43:14 +00006850
6851 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006852 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006853 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006854
Sebastian Redl08905022011-02-05 19:23:19 +00006855 if (Ctor->getInheritedConstructor())
6856 return oc_implicit_inherited_constructor;
6857
Alexis Hunt119c10e2011-05-25 23:16:36 +00006858 if (Ctor->isDefaultConstructor())
6859 return oc_implicit_default_constructor;
6860
6861 if (Ctor->isMoveConstructor())
6862 return oc_implicit_move_constructor;
6863
6864 assert(Ctor->isCopyConstructor() &&
6865 "unexpected sort of implicit constructor");
6866 return oc_implicit_copy_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006867 }
6868
6869 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6870 // This actually gets spelled 'candidate function' for now, but
6871 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006872 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006873 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006874
Alexis Hunt119c10e2011-05-25 23:16:36 +00006875 if (Meth->isMoveAssignmentOperator())
6876 return oc_implicit_move_assignment;
6877
Douglas Gregorec3bec02010-09-27 22:37:28 +00006878 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006879 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006880 return oc_implicit_copy_assignment;
6881 }
6882
John McCalle1ac8d12010-01-13 00:25:19 +00006883 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006884}
6885
Sebastian Redl08905022011-02-05 19:23:19 +00006886void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
6887 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
6888 if (!Ctor) return;
6889
6890 Ctor = Ctor->getInheritedConstructor();
6891 if (!Ctor) return;
6892
6893 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
6894}
6895
John McCall53262c92010-01-12 02:15:36 +00006896} // end anonymous namespace
6897
6898// Notes the location of an overload candidate.
6899void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006900 std::string FnDesc;
6901 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6902 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6903 << (unsigned) K << FnDesc;
Sebastian Redl08905022011-02-05 19:23:19 +00006904 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallfd0b2f82010-01-06 09:43:14 +00006905}
6906
Douglas Gregorb491ed32011-02-19 21:32:49 +00006907//Notes the location of all overload candidates designated through
6908// OverloadedExpr
6909void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
6910 assert(OverloadedExpr->getType() == Context.OverloadTy);
6911
6912 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
6913 OverloadExpr *OvlExpr = Ovl.Expression;
6914
6915 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6916 IEnd = OvlExpr->decls_end();
6917 I != IEnd; ++I) {
6918 if (FunctionTemplateDecl *FunTmpl =
6919 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
6920 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
6921 } else if (FunctionDecl *Fun
6922 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
6923 NoteOverloadCandidate(Fun);
6924 }
6925 }
6926}
6927
John McCall0d1da222010-01-12 00:44:57 +00006928/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6929/// "lead" diagnostic; it will be given two arguments, the source and
6930/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006931void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6932 Sema &S,
6933 SourceLocation CaretLoc,
6934 const PartialDiagnostic &PDiag) const {
6935 S.Diag(CaretLoc, PDiag)
6936 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006937 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006938 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6939 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006940 }
John McCall12f97bc2010-01-08 04:41:39 +00006941}
6942
John McCall0d1da222010-01-12 00:44:57 +00006943namespace {
6944
John McCall6a61b522010-01-13 09:16:55 +00006945void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6946 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6947 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006948 assert(Cand->Function && "for now, candidate must be a function");
6949 FunctionDecl *Fn = Cand->Function;
6950
6951 // There's a conversion slot for the object argument if this is a
6952 // non-constructor method. Note that 'I' corresponds the
6953 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006954 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006955 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006956 if (I == 0)
6957 isObjectArgument = true;
6958 else
6959 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006960 }
6961
John McCalle1ac8d12010-01-13 00:25:19 +00006962 std::string FnDesc;
6963 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6964
John McCall6a61b522010-01-13 09:16:55 +00006965 Expr *FromExpr = Conv.Bad.FromExpr;
6966 QualType FromTy = Conv.Bad.getFromType();
6967 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006968
John McCallfb7ad0f2010-02-02 02:42:52 +00006969 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006970 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006971 Expr *E = FromExpr->IgnoreParens();
6972 if (isa<UnaryOperator>(E))
6973 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006974 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006975
6976 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6977 << (unsigned) FnKind << FnDesc
6978 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6979 << ToTy << Name << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00006980 MaybeEmitInheritedConstructorNote(S, Fn);
John McCallfb7ad0f2010-02-02 02:42:52 +00006981 return;
6982 }
6983
John McCall6d174642010-01-23 08:10:49 +00006984 // Do some hand-waving analysis to see if the non-viability is due
6985 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006986 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6987 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6988 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6989 CToTy = RT->getPointeeType();
6990 else {
6991 // TODO: detect and diagnose the full richness of const mismatches.
6992 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6993 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6994 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6995 }
6996
6997 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6998 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6999 // It is dumb that we have to do this here.
7000 while (isa<ArrayType>(CFromTy))
7001 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7002 while (isa<ArrayType>(CToTy))
7003 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7004
7005 Qualifiers FromQs = CFromTy.getQualifiers();
7006 Qualifiers ToQs = CToTy.getQualifiers();
7007
7008 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7009 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7010 << (unsigned) FnKind << FnDesc
7011 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7012 << FromTy
7013 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7014 << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007015 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007016 return;
7017 }
7018
John McCall31168b02011-06-15 23:02:42 +00007019 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidiscff00d92011-06-24 00:08:59 +00007020 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCall31168b02011-06-15 23:02:42 +00007021 << (unsigned) FnKind << FnDesc
7022 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7023 << FromTy
7024 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7025 << (unsigned) isObjectArgument << I+1;
7026 MaybeEmitInheritedConstructorNote(S, Fn);
7027 return;
7028 }
7029
Douglas Gregoraec25842011-04-26 23:16:46 +00007030 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7031 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7032 << (unsigned) FnKind << FnDesc
7033 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7034 << FromTy
7035 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7036 << (unsigned) isObjectArgument << I+1;
7037 MaybeEmitInheritedConstructorNote(S, Fn);
7038 return;
7039 }
7040
John McCall47000992010-01-14 03:28:57 +00007041 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7042 assert(CVR && "unexpected qualifiers mismatch");
7043
7044 if (isObjectArgument) {
7045 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7046 << (unsigned) FnKind << FnDesc
7047 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7048 << FromTy << (CVR - 1);
7049 } else {
7050 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7051 << (unsigned) FnKind << FnDesc
7052 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7053 << FromTy << (CVR - 1) << I+1;
7054 }
Sebastian Redl08905022011-02-05 19:23:19 +00007055 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall47000992010-01-14 03:28:57 +00007056 return;
7057 }
7058
Sebastian Redla72462c2011-09-24 17:48:32 +00007059 // Special diagnostic for failure to convert an initializer list, since
7060 // telling the user that it has type void is not useful.
7061 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7062 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7063 << (unsigned) FnKind << FnDesc
7064 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7065 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7066 MaybeEmitInheritedConstructorNote(S, Fn);
7067 return;
7068 }
7069
John McCall6d174642010-01-23 08:10:49 +00007070 // Diagnose references or pointers to incomplete types differently,
7071 // since it's far from impossible that the incompleteness triggered
7072 // the failure.
7073 QualType TempFromTy = FromTy.getNonReferenceType();
7074 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7075 TempFromTy = PTy->getPointeeType();
7076 if (TempFromTy->isIncompleteType()) {
7077 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7078 << (unsigned) FnKind << FnDesc
7079 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7080 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007081 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6d174642010-01-23 08:10:49 +00007082 return;
7083 }
7084
Douglas Gregor56f2e342010-06-30 23:01:39 +00007085 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007086 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007087 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7088 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7089 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7090 FromPtrTy->getPointeeType()) &&
7091 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7092 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007093 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor56f2e342010-06-30 23:01:39 +00007094 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007095 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00007096 }
7097 } else if (const ObjCObjectPointerType *FromPtrTy
7098 = FromTy->getAs<ObjCObjectPointerType>()) {
7099 if (const ObjCObjectPointerType *ToPtrTy
7100 = ToTy->getAs<ObjCObjectPointerType>())
7101 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7102 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7103 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7104 FromPtrTy->getPointeeType()) &&
7105 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007106 BaseToDerivedConversion = 2;
7107 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7108 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7109 !FromTy->isIncompleteType() &&
7110 !ToRefTy->getPointeeType()->isIncompleteType() &&
7111 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7112 BaseToDerivedConversion = 3;
7113 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007114
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007115 if (BaseToDerivedConversion) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007116 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007117 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00007118 << (unsigned) FnKind << FnDesc
7119 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00007120 << (BaseToDerivedConversion - 1)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007121 << FromTy << ToTy << I+1;
Sebastian Redl08905022011-02-05 19:23:19 +00007122 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor56f2e342010-06-30 23:01:39 +00007123 return;
7124 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007125
Fariborz Jahaniana644f9c2011-07-20 17:14:09 +00007126 if (isa<ObjCObjectPointerType>(CFromTy) &&
7127 isa<PointerType>(CToTy)) {
7128 Qualifiers FromQs = CFromTy.getQualifiers();
7129 Qualifiers ToQs = CToTy.getQualifiers();
7130 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7131 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7132 << (unsigned) FnKind << FnDesc
7133 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7134 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7135 MaybeEmitInheritedConstructorNote(S, Fn);
7136 return;
7137 }
7138 }
7139
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007140 // Emit the generic diagnostic and, optionally, add the hints to it.
7141 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7142 FDiag << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00007143 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007144 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7145 << (unsigned) (Cand->Fix.Kind);
7146
7147 // If we can fix the conversion, suggest the FixIts.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007148 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007149 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7150 HI != HE; ++HI)
7151 FDiag << *HI;
7152 S.Diag(Fn->getLocation(), FDiag);
7153
Sebastian Redl08905022011-02-05 19:23:19 +00007154 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall6a61b522010-01-13 09:16:55 +00007155}
7156
7157void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7158 unsigned NumFormalArgs) {
7159 // TODO: treat calls to a missing default constructor as a special case
7160
7161 FunctionDecl *Fn = Cand->Function;
7162 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7163
7164 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007165
Douglas Gregor1d33f8d2011-05-05 00:13:13 +00007166 // With invalid overloaded operators, it's possible that we think we
7167 // have an arity mismatch when it fact it looks like we have the
7168 // right number of arguments, because only overloaded operators have
7169 // the weird behavior of overloading member and non-member functions.
7170 // Just don't report anything.
7171 if (Fn->isInvalidDecl() &&
7172 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7173 return;
7174
John McCall6a61b522010-01-13 09:16:55 +00007175 // at least / at most / exactly
7176 unsigned mode, modeCount;
7177 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007178 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7179 (Cand->FailureKind == ovl_fail_bad_deduction &&
7180 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007181 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregor7825bf32011-01-06 22:09:01 +00007182 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00007183 mode = 0; // "at least"
7184 else
7185 mode = 2; // "exactly"
7186 modeCount = MinParams;
7187 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00007188 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7189 (Cand->FailureKind == ovl_fail_bad_deduction &&
7190 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00007191 if (MinParams != FnTy->getNumArgs())
7192 mode = 1; // "at most"
7193 else
7194 mode = 2; // "exactly"
7195 modeCount = FnTy->getNumArgs();
7196 }
7197
7198 std::string Description;
7199 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7200
7201 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007202 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregor02eb4832010-05-08 18:13:28 +00007203 << modeCount << NumFormalArgs;
Sebastian Redl08905022011-02-05 19:23:19 +00007204 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007205}
7206
John McCall8b9ed552010-02-01 18:53:26 +00007207/// Diagnose a failed template-argument deduction.
7208void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7209 Expr **Args, unsigned NumArgs) {
7210 FunctionDecl *Fn = Cand->Function; // pattern
7211
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007212 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007213 NamedDecl *ParamD;
7214 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7215 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7216 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00007217 switch (Cand->DeductionFailure.Result) {
7218 case Sema::TDK_Success:
7219 llvm_unreachable("TDK_success while diagnosing bad deduction");
7220
7221 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00007222 assert(ParamD && "no parameter found for incomplete deduction result");
7223 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7224 << ParamD->getDeclName();
Sebastian Redl08905022011-02-05 19:23:19 +00007225 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007226 return;
7227 }
7228
John McCall42d7d192010-08-05 09:05:08 +00007229 case Sema::TDK_Underqualified: {
7230 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7231 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7232
7233 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7234
7235 // Param will have been canonicalized, but it should just be a
7236 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00007237 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00007238 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00007239 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00007240 assert(S.Context.hasSameType(Param, NonCanonParam));
7241
7242 // Arg has also been canonicalized, but there's nothing we can do
7243 // about that. It also doesn't matter as much, because it won't
7244 // have any template parameters in it (because deduction isn't
7245 // done on dependent types).
7246 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7247
7248 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7249 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redl08905022011-02-05 19:23:19 +00007250 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall42d7d192010-08-05 09:05:08 +00007251 return;
7252 }
7253
7254 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00007255 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007256 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007257 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007258 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007259 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007260 which = 1;
7261 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007262 which = 2;
7263 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007264
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007265 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007266 << which << ParamD->getDeclName()
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007267 << *Cand->DeductionFailure.getFirstArg()
7268 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redl08905022011-02-05 19:23:19 +00007269 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor3626a5c2010-05-08 17:41:32 +00007270 return;
7271 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00007272
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007273 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007274 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007275 if (ParamD->getDeclName())
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007276 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007277 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7278 << ParamD->getDeclName();
7279 else {
7280 int index = 0;
7281 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7282 index = TTP->getIndex();
7283 else if (NonTypeTemplateParmDecl *NTTP
7284 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7285 index = NTTP->getIndex();
7286 else
7287 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007288 S.Diag(Fn->getLocation(),
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007289 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7290 << (index + 1);
7291 }
Sebastian Redl08905022011-02-05 19:23:19 +00007292 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor1d72edd2010-05-08 19:15:54 +00007293 return;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007294
Douglas Gregor02eb4832010-05-08 18:13:28 +00007295 case Sema::TDK_TooManyArguments:
7296 case Sema::TDK_TooFewArguments:
7297 DiagnoseArityMismatch(S, Cand, NumArgs);
7298 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00007299
7300 case Sema::TDK_InstantiationDepth:
7301 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redl08905022011-02-05 19:23:19 +00007302 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007303 return;
7304
7305 case Sema::TDK_SubstitutionFailure: {
7306 std::string ArgString;
7307 if (TemplateArgumentList *Args
7308 = Cand->DeductionFailure.getTemplateArgumentList())
7309 ArgString = S.getTemplateArgumentBindingsText(
7310 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7311 *Args);
7312 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7313 << ArgString;
Sebastian Redl08905022011-02-05 19:23:19 +00007314 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregord09efd42010-05-08 20:07:26 +00007315 return;
7316 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007317
John McCall8b9ed552010-02-01 18:53:26 +00007318 // TODO: diagnose these individually, then kill off
7319 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00007320 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00007321 case Sema::TDK_FailedOverloadResolution:
7322 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redl08905022011-02-05 19:23:19 +00007323 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall8b9ed552010-02-01 18:53:26 +00007324 return;
7325 }
7326}
7327
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007328/// CUDA: diagnose an invalid call across targets.
7329void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7330 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7331 FunctionDecl *Callee = Cand->Function;
7332
7333 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7334 CalleeTarget = S.IdentifyCUDATarget(Callee);
7335
7336 std::string FnDesc;
7337 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7338
7339 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7340 << (unsigned) FnKind << CalleeTarget << CallerTarget;
7341}
7342
John McCall8b9ed552010-02-01 18:53:26 +00007343/// Generates a 'note' diagnostic for an overload candidate. We've
7344/// already generated a primary error at the call site.
7345///
7346/// It really does need to be a single diagnostic with its caret
7347/// pointed at the candidate declaration. Yes, this creates some
7348/// major challenges of technical writing. Yes, this makes pointing
7349/// out problems with specific arguments quite awkward. It's still
7350/// better than generating twenty screens of text for every failed
7351/// overload.
7352///
7353/// It would be great to be able to express per-candidate problems
7354/// more richly for those diagnostic clients that cared, but we'd
7355/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00007356void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7357 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00007358 FunctionDecl *Fn = Cand->Function;
7359
John McCall12f97bc2010-01-08 04:41:39 +00007360 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidisab72b672011-06-23 00:41:50 +00007361 if (Cand->Viable && (Fn->isDeleted() ||
7362 S.isFunctionConsideredUnavailable(Fn))) {
John McCalle1ac8d12010-01-13 00:25:19 +00007363 std::string FnDesc;
7364 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00007365
7366 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00007367 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redl08905022011-02-05 19:23:19 +00007368 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalld3224162010-01-08 00:58:21 +00007369 return;
John McCall12f97bc2010-01-08 04:41:39 +00007370 }
7371
John McCalle1ac8d12010-01-13 00:25:19 +00007372 // We don't really have anything else to say about viable candidates.
7373 if (Cand->Viable) {
7374 S.NoteOverloadCandidate(Fn);
7375 return;
7376 }
John McCall0d1da222010-01-12 00:44:57 +00007377
John McCall6a61b522010-01-13 09:16:55 +00007378 switch (Cand->FailureKind) {
7379 case ovl_fail_too_many_arguments:
7380 case ovl_fail_too_few_arguments:
7381 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00007382
John McCall6a61b522010-01-13 09:16:55 +00007383 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00007384 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7385
John McCallfe796dd2010-01-23 05:17:32 +00007386 case ovl_fail_trivial_conversion:
7387 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00007388 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00007389 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007390
John McCall65eb8792010-02-25 01:37:24 +00007391 case ovl_fail_bad_conversion: {
7392 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7393 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00007394 if (Cand->Conversions[I].isBad())
7395 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007396
John McCall6a61b522010-01-13 09:16:55 +00007397 // FIXME: this currently happens when we're called from SemaInit
7398 // when user-conversion overload fails. Figure out how to handle
7399 // those conditions and diagnose them well.
7400 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00007401 }
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007402
7403 case ovl_fail_bad_target:
7404 return DiagnoseBadTarget(S, Cand);
John McCall65eb8792010-02-25 01:37:24 +00007405 }
John McCalld3224162010-01-08 00:58:21 +00007406}
7407
7408void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7409 // Desugar the type of the surrogate down to a function type,
7410 // retaining as many typedefs as possible while still showing
7411 // the function type (and, therefore, its parameter types).
7412 QualType FnType = Cand->Surrogate->getConversionType();
7413 bool isLValueReference = false;
7414 bool isRValueReference = false;
7415 bool isPointer = false;
7416 if (const LValueReferenceType *FnTypeRef =
7417 FnType->getAs<LValueReferenceType>()) {
7418 FnType = FnTypeRef->getPointeeType();
7419 isLValueReference = true;
7420 } else if (const RValueReferenceType *FnTypeRef =
7421 FnType->getAs<RValueReferenceType>()) {
7422 FnType = FnTypeRef->getPointeeType();
7423 isRValueReference = true;
7424 }
7425 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7426 FnType = FnTypePtr->getPointeeType();
7427 isPointer = true;
7428 }
7429 // Desugar down to a function type.
7430 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7431 // Reconstruct the pointer/reference as appropriate.
7432 if (isPointer) FnType = S.Context.getPointerType(FnType);
7433 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7434 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7435
7436 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7437 << FnType;
Sebastian Redl08905022011-02-05 19:23:19 +00007438 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalld3224162010-01-08 00:58:21 +00007439}
7440
7441void NoteBuiltinOperatorCandidate(Sema &S,
7442 const char *Opc,
7443 SourceLocation OpLoc,
7444 OverloadCandidate *Cand) {
7445 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7446 std::string TypeStr("operator");
7447 TypeStr += Opc;
7448 TypeStr += "(";
7449 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7450 if (Cand->Conversions.size() == 1) {
7451 TypeStr += ")";
7452 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7453 } else {
7454 TypeStr += ", ";
7455 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7456 TypeStr += ")";
7457 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7458 }
7459}
7460
7461void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7462 OverloadCandidate *Cand) {
7463 unsigned NoOperands = Cand->Conversions.size();
7464 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7465 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00007466 if (ICS.isBad()) break; // all meaningless after first invalid
7467 if (!ICS.isAmbiguous()) continue;
7468
John McCall5c32be02010-08-24 20:38:10 +00007469 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00007470 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00007471 }
7472}
7473
John McCall3712d9e2010-01-15 23:32:50 +00007474SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7475 if (Cand->Function)
7476 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00007477 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00007478 return Cand->Surrogate->getLocation();
7479 return SourceLocation();
7480}
7481
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007482static unsigned
7483RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth73fddfe2011-09-10 00:51:24 +00007484 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007485 case Sema::TDK_Success:
David Blaikie83d382b2011-09-23 05:06:16 +00007486 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007487
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007488 case Sema::TDK_Incomplete:
7489 return 1;
7490
7491 case Sema::TDK_Underqualified:
7492 case Sema::TDK_Inconsistent:
7493 return 2;
7494
7495 case Sema::TDK_SubstitutionFailure:
7496 case Sema::TDK_NonDeducedMismatch:
7497 return 3;
7498
7499 case Sema::TDK_InstantiationDepth:
7500 case Sema::TDK_FailedOverloadResolution:
7501 return 4;
7502
7503 case Sema::TDK_InvalidExplicitArguments:
7504 return 5;
7505
7506 case Sema::TDK_TooManyArguments:
7507 case Sema::TDK_TooFewArguments:
7508 return 6;
7509 }
Benjamin Kramer8a8051f2011-09-10 21:52:04 +00007510 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007511}
7512
John McCallad2587a2010-01-12 00:48:53 +00007513struct CompareOverloadCandidatesForDisplay {
7514 Sema &S;
7515 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00007516
7517 bool operator()(const OverloadCandidate *L,
7518 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00007519 // Fast-path this check.
7520 if (L == R) return false;
7521
John McCall12f97bc2010-01-08 04:41:39 +00007522 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00007523 if (L->Viable) {
7524 if (!R->Viable) return true;
7525
7526 // TODO: introduce a tri-valued comparison for overload
7527 // candidates. Would be more worthwhile if we had a sort
7528 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00007529 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7530 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00007531 } else if (R->Viable)
7532 return false;
John McCall12f97bc2010-01-08 04:41:39 +00007533
John McCall3712d9e2010-01-15 23:32:50 +00007534 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00007535
John McCall3712d9e2010-01-15 23:32:50 +00007536 // Criteria by which we can sort non-viable candidates:
7537 if (!L->Viable) {
7538 // 1. Arity mismatches come after other candidates.
7539 if (L->FailureKind == ovl_fail_too_many_arguments ||
7540 L->FailureKind == ovl_fail_too_few_arguments)
7541 return false;
7542 if (R->FailureKind == ovl_fail_too_many_arguments ||
7543 R->FailureKind == ovl_fail_too_few_arguments)
7544 return true;
John McCall12f97bc2010-01-08 04:41:39 +00007545
John McCallfe796dd2010-01-23 05:17:32 +00007546 // 2. Bad conversions come first and are ordered by the number
7547 // of bad conversions and quality of good conversions.
7548 if (L->FailureKind == ovl_fail_bad_conversion) {
7549 if (R->FailureKind != ovl_fail_bad_conversion)
7550 return true;
7551
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007552 // The conversion that can be fixed with a smaller number of changes,
7553 // comes first.
7554 unsigned numLFixes = L->Fix.NumConversionsFixed;
7555 unsigned numRFixes = R->Fix.NumConversionsFixed;
7556 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7557 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007558 if (numLFixes != numRFixes) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007559 if (numLFixes < numRFixes)
7560 return true;
7561 else
7562 return false;
Anna Zaks9ccf84e2011-07-21 00:34:39 +00007563 }
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007564
John McCallfe796dd2010-01-23 05:17:32 +00007565 // If there's any ordering between the defined conversions...
7566 // FIXME: this might not be transitive.
7567 assert(L->Conversions.size() == R->Conversions.size());
7568
7569 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00007570 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7571 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00007572 switch (CompareImplicitConversionSequences(S,
7573 L->Conversions[I],
7574 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00007575 case ImplicitConversionSequence::Better:
7576 leftBetter++;
7577 break;
7578
7579 case ImplicitConversionSequence::Worse:
7580 leftBetter--;
7581 break;
7582
7583 case ImplicitConversionSequence::Indistinguishable:
7584 break;
7585 }
7586 }
7587 if (leftBetter > 0) return true;
7588 if (leftBetter < 0) return false;
7589
7590 } else if (R->FailureKind == ovl_fail_bad_conversion)
7591 return false;
7592
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007593 if (L->FailureKind == ovl_fail_bad_deduction) {
7594 if (R->FailureKind != ovl_fail_bad_deduction)
7595 return true;
7596
7597 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7598 return RankDeductionFailure(L->DeductionFailure)
Eli Friedman1e7a0c62011-10-14 23:10:30 +00007599 < RankDeductionFailure(R->DeductionFailure);
Eli Friedmane2c600c2011-10-14 21:52:24 +00007600 } else if (R->FailureKind == ovl_fail_bad_deduction)
7601 return false;
Kaelyn Uhrain45e93702011-09-09 21:58:49 +00007602
John McCall3712d9e2010-01-15 23:32:50 +00007603 // TODO: others?
7604 }
7605
7606 // Sort everything else by location.
7607 SourceLocation LLoc = GetLocationForCandidate(L);
7608 SourceLocation RLoc = GetLocationForCandidate(R);
7609
7610 // Put candidates without locations (e.g. builtins) at the end.
7611 if (LLoc.isInvalid()) return false;
7612 if (RLoc.isInvalid()) return true;
7613
7614 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00007615 }
7616};
7617
John McCallfe796dd2010-01-23 05:17:32 +00007618/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007619/// computes up to the first. Produces the FixIt set if possible.
John McCallfe796dd2010-01-23 05:17:32 +00007620void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7621 Expr **Args, unsigned NumArgs) {
7622 assert(!Cand->Viable);
7623
7624 // Don't do anything on failures other than bad conversion.
7625 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7626
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007627 // We only want the FixIts if all the arguments can be corrected.
7628 bool Unfixable = false;
Anna Zaks1b068122011-07-28 19:46:48 +00007629 // Use a implicit copy initialization to check conversion fixes.
7630 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007631
John McCallfe796dd2010-01-23 05:17:32 +00007632 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00007633 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00007634 unsigned ConvCount = Cand->Conversions.size();
7635 while (true) {
7636 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7637 ConvIdx++;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007638 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaks1b068122011-07-28 19:46:48 +00007639 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCallfe796dd2010-01-23 05:17:32 +00007640 break;
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007641 }
John McCallfe796dd2010-01-23 05:17:32 +00007642 }
7643
7644 if (ConvIdx == ConvCount)
7645 return;
7646
John McCall65eb8792010-02-25 01:37:24 +00007647 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7648 "remaining conversion is initialized?");
7649
Douglas Gregoradc7a702010-04-16 17:45:54 +00007650 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00007651 // operation somehow.
7652 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00007653
7654 const FunctionProtoType* Proto;
7655 unsigned ArgIdx = ConvIdx;
7656
7657 if (Cand->IsSurrogate) {
7658 QualType ConvType
7659 = Cand->Surrogate->getConversionType().getNonReferenceType();
7660 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7661 ConvType = ConvPtrType->getPointeeType();
7662 Proto = ConvType->getAs<FunctionProtoType>();
7663 ArgIdx--;
7664 } else if (Cand->Function) {
7665 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7666 if (isa<CXXMethodDecl>(Cand->Function) &&
7667 !isa<CXXConstructorDecl>(Cand->Function))
7668 ArgIdx--;
7669 } else {
7670 // Builtin binary operator with a bad first conversion.
7671 assert(ConvCount <= 3);
7672 for (; ConvIdx != ConvCount; ++ConvIdx)
7673 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007674 = TryCopyInitialization(S, Args[ConvIdx],
7675 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007676 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007677 /*InOverloadResolution*/ true,
7678 /*AllowObjCWritebackConversion=*/
7679 S.getLangOptions().ObjCAutoRefCount);
John McCallfe796dd2010-01-23 05:17:32 +00007680 return;
7681 }
7682
7683 // Fill in the rest of the conversions.
7684 unsigned NumArgsInProto = Proto->getNumArgs();
7685 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007686 if (ArgIdx < NumArgsInProto) {
John McCallfe796dd2010-01-23 05:17:32 +00007687 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00007688 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007689 SuppressUserConversions,
John McCall31168b02011-06-15 23:02:42 +00007690 /*InOverloadResolution=*/true,
7691 /*AllowObjCWritebackConversion=*/
7692 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007693 // Store the FixIt in the candidate if it exists.
7694 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaks1b068122011-07-28 19:46:48 +00007695 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksdf92ddf2011-07-19 19:49:12 +00007696 }
John McCallfe796dd2010-01-23 05:17:32 +00007697 else
7698 Cand->Conversions[ConvIdx].setEllipsis();
7699 }
7700}
7701
John McCalld3224162010-01-08 00:58:21 +00007702} // end anonymous namespace
7703
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007704/// PrintOverloadCandidates - When overload resolution fails, prints
7705/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00007706/// set.
John McCall5c32be02010-08-24 20:38:10 +00007707void OverloadCandidateSet::NoteCandidates(Sema &S,
7708 OverloadCandidateDisplayKind OCD,
7709 Expr **Args, unsigned NumArgs,
7710 const char *Opc,
7711 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00007712 // Sort the candidates by viability and position. Sorting directly would
7713 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007714 SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00007715 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7716 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00007717 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00007718 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00007719 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00007720 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007721 if (Cand->Function || Cand->IsSurrogate)
7722 Cands.push_back(Cand);
7723 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7724 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00007725 }
7726 }
7727
John McCallad2587a2010-01-12 00:48:53 +00007728 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00007729 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007730
John McCall0d1da222010-01-12 00:44:57 +00007731 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00007732
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007733 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikie9c902b52011-09-25 23:23:43 +00007734 const DiagnosticsEngine::OverloadsShown ShowOverloads =
7735 S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007736 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00007737 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7738 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00007739
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007740 // Set an arbitrary limit on the number of candidate functions we'll spam
7741 // the user with. FIXME: This limit should depend on details of the
7742 // candidate list.
David Blaikie9c902b52011-09-25 23:23:43 +00007743 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007744 break;
7745 }
7746 ++CandsShown;
7747
John McCalld3224162010-01-08 00:58:21 +00007748 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00007749 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00007750 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00007751 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007752 else {
7753 assert(Cand->Viable &&
7754 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00007755 // Generally we only see ambiguities including viable builtin
7756 // operators if overload resolution got screwed up by an
7757 // ambiguous user-defined conversion.
7758 //
7759 // FIXME: It's quite possible for different conversions to see
7760 // different ambiguities, though.
7761 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00007762 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00007763 ReportedAmbiguousConversions = true;
7764 }
John McCalld3224162010-01-08 00:58:21 +00007765
John McCall0d1da222010-01-12 00:44:57 +00007766 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00007767 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00007768 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007769 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00007770
7771 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00007772 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00007773}
7774
Douglas Gregorb491ed32011-02-19 21:32:49 +00007775// [PossiblyAFunctionType] --> [Return]
7776// NonFunctionType --> NonFunctionType
7777// R (A) --> R(A)
7778// R (*)(A) --> R (A)
7779// R (&)(A) --> R (A)
7780// R (S::*)(A) --> R (A)
7781QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7782 QualType Ret = PossiblyAFunctionType;
7783 if (const PointerType *ToTypePtr =
7784 PossiblyAFunctionType->getAs<PointerType>())
7785 Ret = ToTypePtr->getPointeeType();
7786 else if (const ReferenceType *ToTypeRef =
7787 PossiblyAFunctionType->getAs<ReferenceType>())
7788 Ret = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007789 else if (const MemberPointerType *MemTypePtr =
Douglas Gregorb491ed32011-02-19 21:32:49 +00007790 PossiblyAFunctionType->getAs<MemberPointerType>())
7791 Ret = MemTypePtr->getPointeeType();
7792 Ret =
7793 Context.getCanonicalType(Ret).getUnqualifiedType();
7794 return Ret;
7795}
Douglas Gregorcd695e52008-11-10 20:40:00 +00007796
Douglas Gregorb491ed32011-02-19 21:32:49 +00007797// A helper class to help with address of function resolution
7798// - allows us to avoid passing around all those ugly parameters
7799class AddressOfFunctionResolver
7800{
7801 Sema& S;
7802 Expr* SourceExpr;
7803 const QualType& TargetType;
7804 QualType TargetFunctionType; // Extracted function type from target type
7805
7806 bool Complain;
7807 //DeclAccessPair& ResultFunctionAccessPair;
7808 ASTContext& Context;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007809
Douglas Gregorb491ed32011-02-19 21:32:49 +00007810 bool TargetTypeIsNonStaticMemberFunction;
7811 bool FoundNonTemplateFunction;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007812
Douglas Gregorb491ed32011-02-19 21:32:49 +00007813 OverloadExpr::FindResult OvlExprInfo;
7814 OverloadExpr *OvlExpr;
7815 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner0e62c1c2011-07-23 10:55:15 +00007816 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00007817
Douglas Gregorb491ed32011-02-19 21:32:49 +00007818public:
7819 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7820 const QualType& TargetType, bool Complain)
7821 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7822 Complain(Complain), Context(S.getASTContext()),
7823 TargetTypeIsNonStaticMemberFunction(
7824 !!TargetType->getAs<MemberPointerType>()),
7825 FoundNonTemplateFunction(false),
7826 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7827 OvlExpr(OvlExprInfo.Expression)
7828 {
7829 ExtractUnqualifiedFunctionTypeFromTargetType();
7830
7831 if (!TargetFunctionType->isFunctionType()) {
7832 if (OvlExpr->hasExplicitTemplateArgs()) {
7833 DeclAccessPair dap;
John McCall0009fcc2011-04-26 20:42:42 +00007834 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregorb491ed32011-02-19 21:32:49 +00007835 OvlExpr, false, &dap) ) {
Chandler Carruthffce2452011-03-29 08:08:18 +00007836
7837 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7838 if (!Method->isStatic()) {
7839 // If the target type is a non-function type and the function
7840 // found is a non-static member function, pretend as if that was
7841 // the target, it's the only possible type to end up with.
7842 TargetTypeIsNonStaticMemberFunction = true;
7843
7844 // And skip adding the function if its not in the proper form.
7845 // We'll diagnose this due to an empty set of functions.
7846 if (!OvlExprInfo.HasFormOfMemberPointer)
7847 return;
7848 }
7849 }
7850
Douglas Gregorb491ed32011-02-19 21:32:49 +00007851 Matches.push_back(std::make_pair(dap,Fn));
7852 }
Douglas Gregor9b146582009-07-08 20:55:45 +00007853 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007854 return;
Douglas Gregor9b146582009-07-08 20:55:45 +00007855 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007856
7857 if (OvlExpr->hasExplicitTemplateArgs())
7858 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump11289f42009-09-09 15:08:12 +00007859
Douglas Gregorb491ed32011-02-19 21:32:49 +00007860 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7861 // C++ [over.over]p4:
7862 // If more than one function is selected, [...]
7863 if (Matches.size() > 1) {
7864 if (FoundNonTemplateFunction)
7865 EliminateAllTemplateMatches();
7866 else
7867 EliminateAllExceptMostSpecializedTemplate();
7868 }
7869 }
7870 }
7871
7872private:
7873 bool isTargetTypeAFunction() const {
7874 return TargetFunctionType->isFunctionType();
7875 }
7876
7877 // [ToType] [Return]
7878
7879 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7880 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7881 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7882 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7883 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7884 }
7885
7886 // return true if any matching specializations were found
7887 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
7888 const DeclAccessPair& CurAccessFunPair) {
7889 if (CXXMethodDecl *Method
7890 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
7891 // Skip non-static function templates when converting to pointer, and
7892 // static when converting to member pointer.
7893 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7894 return false;
7895 }
7896 else if (TargetTypeIsNonStaticMemberFunction)
7897 return false;
7898
7899 // C++ [over.over]p2:
7900 // If the name is a function template, template argument deduction is
7901 // done (14.8.2.2), and if the argument deduction succeeds, the
7902 // resulting template argument list is used to generate a single
7903 // function template specialization, which is added to the set of
7904 // overloaded functions considered.
7905 FunctionDecl *Specialization = 0;
7906 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
7907 if (Sema::TemplateDeductionResult Result
7908 = S.DeduceTemplateArguments(FunctionTemplate,
7909 &OvlExplicitTemplateArgs,
7910 TargetFunctionType, Specialization,
7911 Info)) {
7912 // FIXME: make a note of the failed deduction for diagnostics.
7913 (void)Result;
7914 return false;
7915 }
7916
7917 // Template argument deduction ensures that we have an exact match.
7918 // This function template specicalization works.
7919 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
7920 assert(TargetFunctionType
7921 == Context.getCanonicalType(Specialization->getType()));
7922 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
7923 return true;
7924 }
7925
7926 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
7927 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007928 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00007929 // Skip non-static functions when converting to pointer, and static
7930 // when converting to member pointer.
Douglas Gregorb491ed32011-02-19 21:32:49 +00007931 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
7932 return false;
7933 }
7934 else if (TargetTypeIsNonStaticMemberFunction)
7935 return false;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007936
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00007937 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne7277fe82011-10-02 23:49:40 +00007938 if (S.getLangOptions().CUDA)
7939 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
7940 if (S.CheckCUDATarget(Caller, FunDecl))
7941 return false;
7942
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00007943 QualType ResultTy;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007944 if (Context.hasSameUnqualifiedType(TargetFunctionType,
7945 FunDecl->getType()) ||
Chandler Carruth53e61b02011-06-18 01:19:03 +00007946 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
7947 ResultTy)) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00007948 Matches.push_back(std::make_pair(CurAccessFunPair,
7949 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007950 FoundNonTemplateFunction = true;
Douglas Gregorb491ed32011-02-19 21:32:49 +00007951 return true;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00007952 }
Mike Stump11289f42009-09-09 15:08:12 +00007953 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00007954
7955 return false;
7956 }
7957
7958 bool FindAllFunctionsThatMatchTargetTypeExactly() {
7959 bool Ret = false;
7960
7961 // If the overload expression doesn't have the form of a pointer to
7962 // member, don't try to convert it to a pointer-to-member type.
7963 if (IsInvalidFormOfPointerToMemberFunction())
7964 return false;
7965
7966 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7967 E = OvlExpr->decls_end();
7968 I != E; ++I) {
7969 // Look through any using declarations to find the underlying function.
7970 NamedDecl *Fn = (*I)->getUnderlyingDecl();
7971
7972 // C++ [over.over]p3:
7973 // Non-member functions and static member functions match
7974 // targets of type "pointer-to-function" or "reference-to-function."
7975 // Nonstatic member functions match targets of
7976 // type "pointer-to-member-function."
7977 // Note that according to DR 247, the containing class does not matter.
7978 if (FunctionTemplateDecl *FunctionTemplate
7979 = dyn_cast<FunctionTemplateDecl>(Fn)) {
7980 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
7981 Ret = true;
7982 }
7983 // If we have explicit template arguments supplied, skip non-templates.
7984 else if (!OvlExpr->hasExplicitTemplateArgs() &&
7985 AddMatchingNonTemplateFunction(Fn, I.getPair()))
7986 Ret = true;
7987 }
7988 assert(Ret || Matches.empty());
7989 return Ret;
Douglas Gregorcd695e52008-11-10 20:40:00 +00007990 }
7991
Douglas Gregorb491ed32011-02-19 21:32:49 +00007992 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor05155d82009-08-21 23:19:43 +00007993 // [...] and any given function template specialization F1 is
7994 // eliminated if the set contains a second function template
7995 // specialization whose function template is more specialized
7996 // than the function template of F1 according to the partial
7997 // ordering rules of 14.5.5.2.
7998
7999 // The algorithm specified above is quadratic. We instead use a
8000 // two-pass algorithm (similar to the one used to identify the
8001 // best viable function in an overload set) that identifies the
8002 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00008003
8004 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8005 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8006 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008007
John McCall58cc69d2010-01-27 01:50:18 +00008008 UnresolvedSetIterator Result =
Douglas Gregorb491ed32011-02-19 21:32:49 +00008009 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8010 TPOC_Other, 0, SourceExpr->getLocStart(),
8011 S.PDiag(),
8012 S.PDiag(diag::err_addr_ovl_ambiguous)
8013 << Matches[0].second->getDeclName(),
8014 S.PDiag(diag::note_ovl_candidate)
8015 << (unsigned) oc_function_template,
8016 Complain);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008017
Douglas Gregorb491ed32011-02-19 21:32:49 +00008018 if (Result != MatchesCopy.end()) {
8019 // Make it the first and only element
8020 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8021 Matches[0].second = cast<FunctionDecl>(*Result);
8022 Matches.resize(1);
John McCall58cc69d2010-01-27 01:50:18 +00008023 }
8024 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008025
Douglas Gregorb491ed32011-02-19 21:32:49 +00008026 void EliminateAllTemplateMatches() {
8027 // [...] any function template specializations in the set are
8028 // eliminated if the set also contains a non-template function, [...]
8029 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8030 if (Matches[I].second->getPrimaryTemplate() == 0)
8031 ++I;
8032 else {
8033 Matches[I] = Matches[--N];
8034 Matches.set_size(N);
8035 }
8036 }
8037 }
8038
8039public:
8040 void ComplainNoMatchesFound() const {
8041 assert(Matches.empty());
8042 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8043 << OvlExpr->getName() << TargetFunctionType
8044 << OvlExpr->getSourceRange();
8045 S.NoteAllOverloadCandidates(OvlExpr);
8046 }
8047
8048 bool IsInvalidFormOfPointerToMemberFunction() const {
8049 return TargetTypeIsNonStaticMemberFunction &&
8050 !OvlExprInfo.HasFormOfMemberPointer;
8051 }
8052
8053 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8054 // TODO: Should we condition this on whether any functions might
8055 // have matched, or is it more appropriate to do that in callers?
8056 // TODO: a fixit wouldn't hurt.
8057 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8058 << TargetType << OvlExpr->getSourceRange();
8059 }
8060
8061 void ComplainOfInvalidConversion() const {
8062 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8063 << OvlExpr->getName() << TargetType;
8064 }
8065
8066 void ComplainMultipleMatchesFound() const {
8067 assert(Matches.size() > 1);
8068 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8069 << OvlExpr->getName()
8070 << OvlExpr->getSourceRange();
8071 S.NoteAllOverloadCandidates(OvlExpr);
8072 }
8073
8074 int getNumMatches() const { return Matches.size(); }
8075
8076 FunctionDecl* getMatchingFunctionDecl() const {
8077 if (Matches.size() != 1) return 0;
8078 return Matches[0].second;
8079 }
8080
8081 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8082 if (Matches.size() != 1) return 0;
8083 return &Matches[0].first;
8084 }
8085};
8086
8087/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8088/// an overloaded function (C++ [over.over]), where @p From is an
8089/// expression with overloaded function type and @p ToType is the type
8090/// we're trying to resolve to. For example:
8091///
8092/// @code
8093/// int f(double);
8094/// int f(int);
8095///
8096/// int (*pfd)(double) = f; // selects f(double)
8097/// @endcode
8098///
8099/// This routine returns the resulting FunctionDecl if it could be
8100/// resolved, and NULL otherwise. When @p Complain is true, this
8101/// routine will emit diagnostics if there is an error.
8102FunctionDecl *
8103Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
8104 bool Complain,
8105 DeclAccessPair &FoundResult) {
8106
8107 assert(AddressOfExpr->getType() == Context.OverloadTy);
8108
8109 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
8110 int NumMatches = Resolver.getNumMatches();
8111 FunctionDecl* Fn = 0;
8112 if ( NumMatches == 0 && Complain) {
8113 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8114 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8115 else
8116 Resolver.ComplainNoMatchesFound();
8117 }
8118 else if (NumMatches > 1 && Complain)
8119 Resolver.ComplainMultipleMatchesFound();
8120 else if (NumMatches == 1) {
8121 Fn = Resolver.getMatchingFunctionDecl();
8122 assert(Fn);
8123 FoundResult = *Resolver.getMatchingFunctionAccessPair();
8124 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00008125 if (Complain)
Douglas Gregorb491ed32011-02-19 21:32:49 +00008126 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00008127 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008128
8129 return Fn;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008130}
8131
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008132/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008133/// resolve that overloaded function expression down to a single function.
8134///
8135/// This routine can only resolve template-ids that refer to a single function
8136/// template, where that template-id refers to a single template whose template
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008137/// arguments are either provided by the template-id or have defaults,
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008138/// as described in C++0x [temp.arg.explicit]p3.
John McCall0009fcc2011-04-26 20:42:42 +00008139FunctionDecl *
8140Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8141 bool Complain,
8142 DeclAccessPair *FoundResult) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008143 // C++ [over.over]p1:
8144 // [...] [Note: any redundant set of parentheses surrounding the
8145 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008146 // C++ [over.over]p1:
8147 // [...] The overloaded function name can be preceded by the &
8148 // operator.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008149
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008150 // If we didn't actually find any template-ids, we're done.
John McCall0009fcc2011-04-26 20:42:42 +00008151 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008152 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00008153
8154 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall0009fcc2011-04-26 20:42:42 +00008155 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008156
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008157 // Look through all of the overloaded functions, searching for one
8158 // whose type matches exactly.
8159 FunctionDecl *Matched = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008160 for (UnresolvedSetIterator I = ovl->decls_begin(),
8161 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008162 // C++0x [temp.arg.explicit]p3:
8163 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008164 // where deduction is not done, if a template argument list is
8165 // specified and it, along with any default template arguments,
8166 // identifies a single function template specialization, then the
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008167 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00008168 FunctionTemplateDecl *FunctionTemplate
8169 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008170
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008171 // C++ [over.over]p2:
8172 // If the name is a function template, template argument deduction is
8173 // done (14.8.2.2), and if the argument deduction succeeds, the
8174 // resulting template argument list is used to generate a single
8175 // function template specialization, which is added to the set of
8176 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008177 FunctionDecl *Specialization = 0;
John McCall0009fcc2011-04-26 20:42:42 +00008178 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008179 if (TemplateDeductionResult Result
8180 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8181 Specialization, Info)) {
8182 // FIXME: make a note of the failed deduction for diagnostics.
8183 (void)Result;
8184 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008185 }
8186
John McCall0009fcc2011-04-26 20:42:42 +00008187 assert(Specialization && "no specialization and no error?");
8188
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008189 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregorb491ed32011-02-19 21:32:49 +00008190 if (Matched) {
Douglas Gregorb491ed32011-02-19 21:32:49 +00008191 if (Complain) {
John McCall0009fcc2011-04-26 20:42:42 +00008192 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8193 << ovl->getName();
8194 NoteAllOverloadCandidates(ovl);
Douglas Gregorb491ed32011-02-19 21:32:49 +00008195 }
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008196 return 0;
John McCall0009fcc2011-04-26 20:42:42 +00008197 }
Douglas Gregorb491ed32011-02-19 21:32:49 +00008198
John McCall0009fcc2011-04-26 20:42:42 +00008199 Matched = Specialization;
8200 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008201 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008202
Douglas Gregor8364e6b2009-12-21 23:17:24 +00008203 return Matched;
8204}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008205
Douglas Gregor1beec452011-03-12 01:48:56 +00008206
8207
8208
John McCall50a2c2c2011-10-11 23:14:30 +00008209// Resolve and fix an overloaded expression that can be resolved
8210// because it identifies a single function template specialization.
8211//
Douglas Gregor1beec452011-03-12 01:48:56 +00008212// Last three arguments should only be supplied if Complain = true
John McCall50a2c2c2011-10-11 23:14:30 +00008213//
8214// Return true if it was logically possible to so resolve the
8215// expression, regardless of whether or not it succeeded. Always
8216// returns true if 'complain' is set.
8217bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8218 ExprResult &SrcExpr, bool doFunctionPointerConverion,
8219 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregor1beec452011-03-12 01:48:56 +00008220 QualType DestTypeForComplaining,
John McCall0009fcc2011-04-26 20:42:42 +00008221 unsigned DiagIDForComplaining) {
John McCall50a2c2c2011-10-11 23:14:30 +00008222 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregor1beec452011-03-12 01:48:56 +00008223
John McCall50a2c2c2011-10-11 23:14:30 +00008224 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregor1beec452011-03-12 01:48:56 +00008225
John McCall0009fcc2011-04-26 20:42:42 +00008226 DeclAccessPair found;
8227 ExprResult SingleFunctionExpression;
8228 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8229 ovl.Expression, /*complain*/ false, &found)) {
John McCall50a2c2c2011-10-11 23:14:30 +00008230 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8231 SrcExpr = ExprError();
8232 return true;
8233 }
John McCall0009fcc2011-04-26 20:42:42 +00008234
8235 // It is only correct to resolve to an instance method if we're
8236 // resolving a form that's permitted to be a pointer to member.
8237 // Otherwise we'll end up making a bound member expression, which
8238 // is illegal in all the contexts we resolve like this.
8239 if (!ovl.HasFormOfMemberPointer &&
8240 isa<CXXMethodDecl>(fn) &&
8241 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall50a2c2c2011-10-11 23:14:30 +00008242 if (!complain) return false;
8243
8244 Diag(ovl.Expression->getExprLoc(),
8245 diag::err_bound_member_function)
8246 << 0 << ovl.Expression->getSourceRange();
8247
8248 // TODO: I believe we only end up here if there's a mix of
8249 // static and non-static candidates (otherwise the expression
8250 // would have 'bound member' type, not 'overload' type).
8251 // Ideally we would note which candidate was chosen and why
8252 // the static candidates were rejected.
8253 SrcExpr = ExprError();
8254 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008255 }
Douglas Gregor89f3cd52011-03-16 19:16:25 +00008256
John McCall0009fcc2011-04-26 20:42:42 +00008257 // Fix the expresion to refer to 'fn'.
8258 SingleFunctionExpression =
John McCall50a2c2c2011-10-11 23:14:30 +00008259 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall0009fcc2011-04-26 20:42:42 +00008260
8261 // If desired, do function-to-pointer decay.
John McCall50a2c2c2011-10-11 23:14:30 +00008262 if (doFunctionPointerConverion) {
John McCall0009fcc2011-04-26 20:42:42 +00008263 SingleFunctionExpression =
8264 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall50a2c2c2011-10-11 23:14:30 +00008265 if (SingleFunctionExpression.isInvalid()) {
8266 SrcExpr = ExprError();
8267 return true;
8268 }
8269 }
John McCall0009fcc2011-04-26 20:42:42 +00008270 }
8271
8272 if (!SingleFunctionExpression.isUsable()) {
8273 if (complain) {
8274 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8275 << ovl.Expression->getName()
8276 << DestTypeForComplaining
8277 << OpRangeForComplaining
8278 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall50a2c2c2011-10-11 23:14:30 +00008279 NoteAllOverloadCandidates(SrcExpr.get());
8280
8281 SrcExpr = ExprError();
8282 return true;
8283 }
8284
8285 return false;
John McCall0009fcc2011-04-26 20:42:42 +00008286 }
8287
John McCall50a2c2c2011-10-11 23:14:30 +00008288 SrcExpr = SingleFunctionExpression;
8289 return true;
Douglas Gregor1beec452011-03-12 01:48:56 +00008290}
8291
Douglas Gregorcabea402009-09-22 15:41:20 +00008292/// \brief Add a single candidate to the overload set.
8293static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00008294 DeclAccessPair FoundDecl,
Douglas Gregor739b107a2011-03-03 02:41:12 +00008295 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008296 Expr **Args, unsigned NumArgs,
8297 OverloadCandidateSet &CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008298 bool PartialOverloading,
8299 bool KnownValid) {
John McCalla0296f72010-03-19 07:35:19 +00008300 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00008301 if (isa<UsingShadowDecl>(Callee))
8302 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8303
Douglas Gregorcabea402009-09-22 15:41:20 +00008304 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith95ce4f62011-06-26 22:19:54 +00008305 if (ExplicitTemplateArgs) {
8306 assert(!KnownValid && "Explicit template arguments?");
8307 return;
8308 }
John McCalla0296f72010-03-19 07:35:19 +00008309 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00008310 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00008311 return;
John McCalld14a8642009-11-21 08:51:07 +00008312 }
8313
8314 if (FunctionTemplateDecl *FuncTemplate
8315 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00008316 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8317 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00008318 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00008319 return;
8320 }
8321
Richard Smith95ce4f62011-06-26 22:19:54 +00008322 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregorcabea402009-09-22 15:41:20 +00008323}
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008324
Douglas Gregorcabea402009-09-22 15:41:20 +00008325/// \brief Add the overload candidates named by callee and/or found by argument
8326/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00008327void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00008328 Expr **Args, unsigned NumArgs,
8329 OverloadCandidateSet &CandidateSet,
8330 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00008331
8332#ifndef NDEBUG
8333 // Verify that ArgumentDependentLookup is consistent with the rules
8334 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00008335 //
Douglas Gregorcabea402009-09-22 15:41:20 +00008336 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8337 // and let Y be the lookup set produced by argument dependent
8338 // lookup (defined as follows). If X contains
8339 //
8340 // -- a declaration of a class member, or
8341 //
8342 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00008343 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00008344 //
8345 // -- a declaration that is neither a function or a function
8346 // template
8347 //
8348 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00008349
John McCall57500772009-12-16 12:17:52 +00008350 if (ULE->requiresADL()) {
8351 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8352 E = ULE->decls_end(); I != E; ++I) {
8353 assert(!(*I)->getDeclContext()->isRecord());
8354 assert(isa<UsingShadowDecl>(*I) ||
8355 !(*I)->getDeclContext()->isFunctionOrMethod());
8356 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00008357 }
8358 }
8359#endif
8360
John McCall57500772009-12-16 12:17:52 +00008361 // It would be nice to avoid this copy.
8362 TemplateArgumentListInfo TABuffer;
Douglas Gregor739b107a2011-03-03 02:41:12 +00008363 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008364 if (ULE->hasExplicitTemplateArgs()) {
8365 ULE->copyTemplateArgumentsInto(TABuffer);
8366 ExplicitTemplateArgs = &TABuffer;
8367 }
8368
8369 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8370 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00008371 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008372 Args, NumArgs, CandidateSet,
Richard Smith95ce4f62011-06-26 22:19:54 +00008373 PartialOverloading, /*KnownValid*/ true);
John McCalld14a8642009-11-21 08:51:07 +00008374
John McCall57500772009-12-16 12:17:52 +00008375 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00008376 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8377 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008378 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00008379 CandidateSet,
Richard Smith02e85f32011-04-14 22:09:26 +00008380 PartialOverloading,
8381 ULE->isStdAssociatedNamespace());
Douglas Gregorcabea402009-09-22 15:41:20 +00008382}
John McCalld681c392009-12-16 08:11:27 +00008383
Richard Smith998a5912011-06-05 22:42:48 +00008384/// Attempt to recover from an ill-formed use of a non-dependent name in a
8385/// template, where the non-dependent name was declared after the template
8386/// was defined. This is common in code written for a compilers which do not
8387/// correctly implement two-stage name lookup.
8388///
8389/// Returns true if a viable candidate was found and a diagnostic was issued.
8390static bool
8391DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8392 const CXXScopeSpec &SS, LookupResult &R,
8393 TemplateArgumentListInfo *ExplicitTemplateArgs,
8394 Expr **Args, unsigned NumArgs) {
8395 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8396 return false;
8397
8398 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8399 SemaRef.LookupQualifiedName(R, DC);
8400
8401 if (!R.empty()) {
8402 R.suppressDiagnostics();
8403
8404 if (isa<CXXRecordDecl>(DC)) {
8405 // Don't diagnose names we find in classes; we get much better
8406 // diagnostics for these from DiagnoseEmptyLookup.
8407 R.clear();
8408 return false;
8409 }
8410
8411 OverloadCandidateSet Candidates(FnLoc);
8412 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8413 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8414 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith95ce4f62011-06-26 22:19:54 +00008415 Candidates, false, /*KnownValid*/ false);
Richard Smith998a5912011-06-05 22:42:48 +00008416
8417 OverloadCandidateSet::iterator Best;
Richard Smith95ce4f62011-06-26 22:19:54 +00008418 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smith998a5912011-06-05 22:42:48 +00008419 // No viable functions. Don't bother the user with notes for functions
8420 // which don't work and shouldn't be found anyway.
Richard Smith95ce4f62011-06-26 22:19:54 +00008421 R.clear();
Richard Smith998a5912011-06-05 22:42:48 +00008422 return false;
Richard Smith95ce4f62011-06-26 22:19:54 +00008423 }
Richard Smith998a5912011-06-05 22:42:48 +00008424
8425 // Find the namespaces where ADL would have looked, and suggest
8426 // declaring the function there instead.
8427 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8428 Sema::AssociatedClassSet AssociatedClasses;
8429 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8430 AssociatedNamespaces,
8431 AssociatedClasses);
8432 // Never suggest declaring a function within namespace 'std'.
Chandler Carruthd50f1692011-06-05 23:36:55 +00008433 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008434 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smith998a5912011-06-05 22:42:48 +00008435 for (Sema::AssociatedNamespaceSet::iterator
8436 it = AssociatedNamespaces.begin(),
Chandler Carruthd50f1692011-06-05 23:36:55 +00008437 end = AssociatedNamespaces.end(); it != end; ++it) {
8438 if (!Std->Encloses(*it))
8439 SuggestedNamespaces.insert(*it);
8440 }
Chandler Carruthd54186a2011-06-08 10:13:17 +00008441 } else {
8442 // Lacking the 'std::' namespace, use all of the associated namespaces.
8443 SuggestedNamespaces = AssociatedNamespaces;
Richard Smith998a5912011-06-05 22:42:48 +00008444 }
8445
8446 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8447 << R.getLookupName();
Chandler Carruthd50f1692011-06-05 23:36:55 +00008448 if (SuggestedNamespaces.empty()) {
Richard Smith998a5912011-06-05 22:42:48 +00008449 SemaRef.Diag(Best->Function->getLocation(),
8450 diag::note_not_found_by_two_phase_lookup)
8451 << R.getLookupName() << 0;
Chandler Carruthd50f1692011-06-05 23:36:55 +00008452 } else if (SuggestedNamespaces.size() == 1) {
Richard Smith998a5912011-06-05 22:42:48 +00008453 SemaRef.Diag(Best->Function->getLocation(),
8454 diag::note_not_found_by_two_phase_lookup)
Chandler Carruthd50f1692011-06-05 23:36:55 +00008455 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smith998a5912011-06-05 22:42:48 +00008456 } else {
8457 // FIXME: It would be useful to list the associated namespaces here,
8458 // but the diagnostics infrastructure doesn't provide a way to produce
8459 // a localized representation of a list of items.
8460 SemaRef.Diag(Best->Function->getLocation(),
8461 diag::note_not_found_by_two_phase_lookup)
8462 << R.getLookupName() << 2;
8463 }
8464
8465 // Try to recover by calling this function.
8466 return true;
8467 }
8468
8469 R.clear();
8470 }
8471
8472 return false;
8473}
8474
8475/// Attempt to recover from ill-formed use of a non-dependent operator in a
8476/// template, where the non-dependent operator was declared after the template
8477/// was defined.
8478///
8479/// Returns true if a viable candidate was found and a diagnostic was issued.
8480static bool
8481DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8482 SourceLocation OpLoc,
8483 Expr **Args, unsigned NumArgs) {
8484 DeclarationName OpName =
8485 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8486 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8487 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8488 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8489}
8490
John McCalld681c392009-12-16 08:11:27 +00008491/// Attempts to recover from a call where no functions were found.
8492///
8493/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00008494static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008495BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00008496 UnresolvedLookupExpr *ULE,
8497 SourceLocation LParenLoc,
8498 Expr **Args, unsigned NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008499 SourceLocation RParenLoc,
8500 bool EmptyLookup) {
John McCalld681c392009-12-16 08:11:27 +00008501
8502 CXXScopeSpec SS;
Douglas Gregor0da1d432011-02-28 20:01:57 +00008503 SS.Adopt(ULE->getQualifierLoc());
John McCalld681c392009-12-16 08:11:27 +00008504
John McCall57500772009-12-16 12:17:52 +00008505 TemplateArgumentListInfo TABuffer;
Richard Smith998a5912011-06-05 22:42:48 +00008506 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall57500772009-12-16 12:17:52 +00008507 if (ULE->hasExplicitTemplateArgs()) {
8508 ULE->copyTemplateArgumentsInto(TABuffer);
8509 ExplicitTemplateArgs = &TABuffer;
8510 }
8511
John McCalld681c392009-12-16 08:11:27 +00008512 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8513 Sema::LookupOrdinaryName);
Richard Smith998a5912011-06-05 22:42:48 +00008514 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8515 ExplicitTemplateArgs, Args, NumArgs) &&
8516 (!EmptyLookup ||
Kaelyn Uhrainacbdc572011-08-03 20:36:05 +00008517 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrain42830922011-08-05 00:09:52 +00008518 ExplicitTemplateArgs, Args, NumArgs)))
John McCallfaf5fb42010-08-26 23:41:50 +00008519 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00008520
John McCall57500772009-12-16 12:17:52 +00008521 assert(!R.empty() && "lookup results empty despite recovery");
8522
8523 // Build an implicit member call if appropriate. Just drop the
8524 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00008525 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00008526 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00008527 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8528 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00008529 else if (ExplicitTemplateArgs)
8530 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8531 else
8532 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8533
8534 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00008535 return ExprError();
John McCall57500772009-12-16 12:17:52 +00008536
8537 // This shouldn't cause an infinite loop because we're giving it
Richard Smith998a5912011-06-05 22:42:48 +00008538 // an expression with viable lookup results, which should never
John McCall57500772009-12-16 12:17:52 +00008539 // end up here.
John McCallb268a282010-08-23 23:25:46 +00008540 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00008541 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00008542}
Douglas Gregor4038cf42010-06-08 17:35:15 +00008543
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008544/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00008545/// (which eventually refers to the declaration Func) and the call
8546/// arguments Args/NumArgs, attempt to resolve the function call down
8547/// to a specific function. If overload resolution succeeds, returns
8548/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00008549/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008550/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00008551ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008552Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00008553 SourceLocation LParenLoc,
8554 Expr **Args, unsigned NumArgs,
Peter Collingbourne41f85462011-02-09 21:07:24 +00008555 SourceLocation RParenLoc,
8556 Expr *ExecConfig) {
John McCall57500772009-12-16 12:17:52 +00008557#ifndef NDEBUG
8558 if (ULE->requiresADL()) {
8559 // To do ADL, we must have found an unqualified name.
8560 assert(!ULE->getQualifier() && "qualified name with ADL");
8561
8562 // We don't perform ADL for implicit declarations of builtins.
8563 // Verify that this was correctly set up.
8564 FunctionDecl *F;
8565 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8566 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8567 F->getBuiltinID() && F->isImplicit())
David Blaikie83d382b2011-09-23 05:06:16 +00008568 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008569
John McCall57500772009-12-16 12:17:52 +00008570 // We don't perform ADL in C.
8571 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smith02e85f32011-04-14 22:09:26 +00008572 } else
8573 assert(!ULE->isStdAssociatedNamespace() &&
8574 "std is associated namespace but not doing ADL");
John McCall57500772009-12-16 12:17:52 +00008575#endif
8576
John McCallbc077cf2010-02-08 23:07:23 +00008577 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00008578
John McCall57500772009-12-16 12:17:52 +00008579 // Add the functions denoted by the callee to the set of candidate
8580 // functions, including those from argument-dependent lookup.
8581 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00008582
8583 // If we found nothing, try to recover.
Richard Smith998a5912011-06-05 22:42:48 +00008584 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8585 // out if it fails.
Francois Pichetbcf64712011-09-07 00:14:57 +00008586 if (CandidateSet.empty()) {
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008587 // In Microsoft mode, if we are inside a template class member function then
8588 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichetbcf64712011-09-07 00:14:57 +00008589 // to instantiation time to be able to search into type dependent base
Sebastian Redlb49c46c2011-09-24 17:48:00 +00008590 // classes.
8591 if (getLangOptions().MicrosoftExt && CurContext->isDependentContext() &&
8592 isa<CXXMethodDecl>(CurContext)) {
8593 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8594 Context.DependentTy, VK_RValue,
8595 RParenLoc);
8596 CE->setTypeDependent(true);
8597 return Owned(CE);
8598 }
Douglas Gregor2fb18b72010-04-14 20:27:54 +00008599 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smith998a5912011-06-05 22:42:48 +00008600 RParenLoc, /*EmptyLookup=*/true);
Francois Pichetbcf64712011-09-07 00:14:57 +00008601 }
John McCalld681c392009-12-16 08:11:27 +00008602
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008603 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008604 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00008605 case OR_Success: {
8606 FunctionDecl *FDecl = Best->Function;
Chandler Carruth30141632011-02-25 19:41:05 +00008607 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCalla0296f72010-03-19 07:35:19 +00008608 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008609 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
8610 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00008611 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbourne41f85462011-02-09 21:07:24 +00008612 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8613 ExecConfig);
John McCall57500772009-12-16 12:17:52 +00008614 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008615
Richard Smith998a5912011-06-05 22:42:48 +00008616 case OR_No_Viable_Function: {
8617 // Try to recover by looking for viable functions which the user might
8618 // have meant to call.
8619 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8620 Args, NumArgs, RParenLoc,
8621 /*EmptyLookup=*/false);
8622 if (!Recovery.isInvalid())
8623 return Recovery;
8624
Chris Lattner45d9d602009-02-17 07:29:20 +00008625 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008626 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00008627 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008628 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008629 break;
Richard Smith998a5912011-06-05 22:42:48 +00008630 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008631
8632 case OR_Ambiguous:
8633 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00008634 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008635 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008636 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008637
8638 case OR_Deleted:
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008639 {
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008640 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8641 << Best->Function->isDeleted()
8642 << ULE->getName()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00008643 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00008644 << Fn->getSourceRange();
Fariborz Jahanianbff158d2011-02-25 18:38:59 +00008645 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
8646 }
Douglas Gregor171c45a2009-02-18 21:56:37 +00008647 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008648 }
8649
Douglas Gregorb412e172010-07-25 18:17:45 +00008650 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00008651 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00008652}
8653
John McCall4c4c1df2010-01-26 03:27:55 +00008654static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00008655 return Functions.size() > 1 ||
8656 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8657}
8658
Douglas Gregor084d8552009-03-13 23:49:33 +00008659/// \brief Create a unary operation that may resolve to an overloaded
8660/// operator.
8661///
8662/// \param OpLoc The location of the operator itself (e.g., '*').
8663///
8664/// \param OpcIn The UnaryOperator::Opcode that describes this
8665/// operator.
8666///
8667/// \param Functions The set of non-member functions that will be
8668/// considered by overload resolution. The caller needs to build this
8669/// set based on the context using, e.g.,
8670/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8671/// set should not contain any member functions; those will be added
8672/// by CreateOverloadedUnaryOp().
8673///
8674/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00008675ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00008676Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8677 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00008678 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008679 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00008680
8681 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8682 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8683 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008684 // TODO: provide better source location info.
8685 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008686
John Wiegley01296292011-04-08 18:41:53 +00008687 if (Input->getObjectKind() == OK_ObjCProperty) {
8688 ExprResult Result = ConvertPropertyForRValue(Input);
8689 if (Result.isInvalid())
8690 return ExprError();
8691 Input = Result.take();
8692 }
John McCalle26a8722010-12-04 08:14:53 +00008693
Douglas Gregor084d8552009-03-13 23:49:33 +00008694 Expr *Args[2] = { Input, 0 };
8695 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00008696
Douglas Gregor084d8552009-03-13 23:49:33 +00008697 // For post-increment and post-decrement, add the implicit '0' as
8698 // the second argument, so that we know this is a post-increment or
8699 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00008700 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008701 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00008702 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8703 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00008704 NumArgs = 2;
8705 }
8706
8707 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00008708 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00008709 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008710 Opc,
Douglas Gregor630dec52010-06-17 15:46:20 +00008711 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008712 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00008713 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008714
John McCall58cc69d2010-01-27 01:50:18 +00008715 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00008716 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00008717 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008718 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008719 /*ADL*/ true, IsOverloaded(Fns),
8720 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00008721 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor0da1d432011-02-28 20:01:57 +00008722 &Args[0], NumArgs,
Douglas Gregor084d8552009-03-13 23:49:33 +00008723 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008724 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00008725 OpLoc));
8726 }
8727
8728 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008729 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00008730
8731 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008732 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00008733
8734 // Add operator candidates that are member functions.
8735 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8736
John McCall4c4c1df2010-01-26 03:27:55 +00008737 // Add candidates from ADL.
8738 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00008739 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00008740 /*ExplicitTemplateArgs*/ 0,
8741 CandidateSet);
8742
Douglas Gregor084d8552009-03-13 23:49:33 +00008743 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008744 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00008745
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008746 bool HadMultipleCandidates = (CandidateSet.size() > 1);
8747
Douglas Gregor084d8552009-03-13 23:49:33 +00008748 // Perform overload resolution.
8749 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008750 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00008751 case OR_Success: {
8752 // We found a built-in operator or an overloaded operator.
8753 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00008754
Douglas Gregor084d8552009-03-13 23:49:33 +00008755 if (FnDecl) {
8756 // We matched an overloaded operator. Build a call to that
8757 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00008758
Chandler Carruth30141632011-02-25 19:41:05 +00008759 MarkDeclarationReferenced(OpLoc, FnDecl);
8760
Douglas Gregor084d8552009-03-13 23:49:33 +00008761 // Convert the arguments.
8762 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00008763 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00008764
John Wiegley01296292011-04-08 18:41:53 +00008765 ExprResult InputRes =
8766 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8767 Best->FoundDecl, Method);
8768 if (InputRes.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008769 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00008770 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008771 } else {
8772 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00008773 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00008774 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008775 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00008776 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008777 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00008778 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00008779 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00008780 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008781 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008782 }
8783
John McCall4fa0d5f2010-05-06 18:15:07 +00008784 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8785
John McCall7decc9e2010-11-18 06:31:45 +00008786 // Determine the result type.
8787 QualType ResultTy = FnDecl->getResultType();
8788 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8789 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00008790
Douglas Gregor084d8552009-03-13 23:49:33 +00008791 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008792 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
8793 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00008794 if (FnExpr.isInvalid())
8795 return ExprError();
Mike Stump11289f42009-09-09 15:08:12 +00008796
Eli Friedman030eee42009-11-18 03:58:17 +00008797 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00008798 CallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00008799 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00008800 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00008801
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008802 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00008803 FnDecl))
8804 return ExprError();
8805
John McCallb268a282010-08-23 23:25:46 +00008806 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00008807 } else {
8808 // We matched a built-in operator. Convert the arguments, then
8809 // break out so that we will build the appropriate built-in
8810 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00008811 ExprResult InputRes =
8812 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8813 Best->Conversions[0], AA_Passing);
8814 if (InputRes.isInvalid())
8815 return ExprError();
8816 Input = InputRes.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00008817 break;
Douglas Gregor084d8552009-03-13 23:49:33 +00008818 }
John Wiegley01296292011-04-08 18:41:53 +00008819 }
8820
8821 case OR_No_Viable_Function:
Richard Smith998a5912011-06-05 22:42:48 +00008822 // This is an erroneous use of an operator which can be overloaded by
8823 // a non-member function. Check for non-member operators which were
8824 // defined too late to be candidates.
8825 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8826 // FIXME: Recover by calling the found function.
8827 return ExprError();
8828
John Wiegley01296292011-04-08 18:41:53 +00008829 // No viable function; fall through to handling this as a
8830 // built-in operator, which will produce an error message for us.
8831 break;
8832
8833 case OR_Ambiguous:
8834 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8835 << UnaryOperator::getOpcodeStr(Opc)
8836 << Input->getType()
8837 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008838 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley01296292011-04-08 18:41:53 +00008839 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8840 return ExprError();
8841
8842 case OR_Deleted:
8843 Diag(OpLoc, diag::err_ovl_deleted_oper)
8844 << Best->Function->isDeleted()
8845 << UnaryOperator::getOpcodeStr(Opc)
8846 << getDeletedOrUnavailableSuffix(Best->Function)
8847 << Input->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00008848 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
8849 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00008850 return ExprError();
8851 }
Douglas Gregor084d8552009-03-13 23:49:33 +00008852
8853 // Either we found no viable overloaded operator or we matched a
8854 // built-in operator. In either case, fall through to trying to
8855 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00008856 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00008857}
8858
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008859/// \brief Create a binary operation that may resolve to an overloaded
8860/// operator.
8861///
8862/// \param OpLoc The location of the operator itself (e.g., '+').
8863///
8864/// \param OpcIn The BinaryOperator::Opcode that describes this
8865/// operator.
8866///
8867/// \param Functions The set of non-member functions that will be
8868/// considered by overload resolution. The caller needs to build this
8869/// set based on the context using, e.g.,
8870/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8871/// set should not contain any member functions; those will be added
8872/// by CreateOverloadedBinOp().
8873///
8874/// \param LHS Left-hand argument.
8875/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00008876ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008877Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00008878 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00008879 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008880 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008881 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00008882 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008883
8884 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
8885 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
8886 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
8887
8888 // If either side is type-dependent, create an appropriate dependent
8889 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00008890 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00008891 if (Fns.empty()) {
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008892 // If there are no functions to store, just build a dependent
Douglas Gregor5287f092009-11-05 00:51:44 +00008893 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00008894 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00008895 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00008896 Context.DependentTy,
8897 VK_RValue, OK_Ordinary,
8898 OpLoc));
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00008899
Douglas Gregor5287f092009-11-05 00:51:44 +00008900 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
8901 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008902 VK_LValue,
8903 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00008904 Context.DependentTy,
8905 Context.DependentTy,
8906 OpLoc));
8907 }
John McCall4c4c1df2010-01-26 03:27:55 +00008908
8909 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00008910 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008911 // TODO: provide better source location info in DNLoc component.
8912 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00008913 UnresolvedLookupExpr *Fn
Douglas Gregor0da1d432011-02-28 20:01:57 +00008914 = UnresolvedLookupExpr::Create(Context, NamingClass,
8915 NestedNameSpecifierLoc(), OpNameInfo,
8916 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00008917 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008918 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00008919 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008920 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00008921 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008922 OpLoc));
8923 }
8924
John McCalle26a8722010-12-04 08:14:53 +00008925 // Always do property rvalue conversions on the RHS.
John Wiegley01296292011-04-08 18:41:53 +00008926 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
8927 ExprResult Result = ConvertPropertyForRValue(Args[1]);
8928 if (Result.isInvalid())
8929 return ExprError();
8930 Args[1] = Result.take();
8931 }
John McCalle26a8722010-12-04 08:14:53 +00008932
8933 // The LHS is more complicated.
8934 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
8935
8936 // There's a tension for assignment operators between primitive
8937 // property assignment and the overloaded operators.
8938 if (BinaryOperator::isAssignmentOp(Opc)) {
8939 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
8940
8941 // Is the property "logically" settable?
8942 bool Settable = (PRE->isExplicitProperty() ||
8943 PRE->getImplicitPropertySetter());
8944
8945 // To avoid gratuitously inventing semantics, use the primitive
8946 // unless it isn't. Thoughts in case we ever really care:
8947 // - If the property isn't logically settable, we have to
8948 // load and hope.
8949 // - If the property is settable and this is simple assignment,
8950 // we really should use the primitive.
8951 // - If the property is settable, then we could try overloading
8952 // on a generic lvalue of the appropriate type; if it works
8953 // out to a builtin candidate, we would do that same operation
8954 // on the property, and otherwise just error.
8955 if (Settable)
8956 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8957 }
8958
John Wiegley01296292011-04-08 18:41:53 +00008959 ExprResult Result = ConvertPropertyForRValue(Args[0]);
8960 if (Result.isInvalid())
8961 return ExprError();
8962 Args[0] = Result.take();
John McCalle26a8722010-12-04 08:14:53 +00008963 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008964
Sebastian Redl6a96bf72009-11-18 23:10:33 +00008965 // If this is the assignment operator, we only perform overload resolution
8966 // if the left-hand side is a class or enumeration type. This is actually
8967 // a hack. The standard requires that we do overload resolution between the
8968 // various built-in candidates, but as DR507 points out, this can lead to
8969 // problems. So we do it this way, which pretty much follows what GCC does.
8970 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00008971 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00008972 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008973
John McCalle26a8722010-12-04 08:14:53 +00008974 // If this is the .* operator, which is not overloadable, just
8975 // create a built-in binary operator.
8976 if (Opc == BO_PtrMemD)
8977 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
8978
Douglas Gregor084d8552009-03-13 23:49:33 +00008979 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00008980 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008981
8982 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00008983 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008984
8985 // Add operator candidates that are member functions.
8986 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
8987
John McCall4c4c1df2010-01-26 03:27:55 +00008988 // Add candidates from ADL.
8989 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
8990 Args, 2,
8991 /*ExplicitTemplateArgs*/ 0,
8992 CandidateSet);
8993
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008994 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00008995 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008996
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00008997 bool HadMultipleCandidates = (CandidateSet.size() > 1);
8998
Douglas Gregor1baf54e2009-03-13 18:40:31 +00008999 // Perform overload resolution.
9000 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009001 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00009002 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009003 // We found a built-in operator or an overloaded operator.
9004 FunctionDecl *FnDecl = Best->Function;
9005
9006 if (FnDecl) {
9007 // We matched an overloaded operator. Build a call to that
9008 // operator.
9009
Chandler Carruth30141632011-02-25 19:41:05 +00009010 MarkDeclarationReferenced(OpLoc, FnDecl);
9011
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009012 // Convert the arguments.
9013 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00009014 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00009015 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00009016
Chandler Carruth8e543b32010-12-12 08:17:55 +00009017 ExprResult Arg1 =
9018 PerformCopyInitialization(
9019 InitializedEntity::InitializeParameter(Context,
9020 FnDecl->getParamDecl(0)),
9021 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009022 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009023 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009024
John Wiegley01296292011-04-08 18:41:53 +00009025 ExprResult Arg0 =
9026 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9027 Best->FoundDecl, Method);
9028 if (Arg0.isInvalid())
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009029 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009030 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009031 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009032 } else {
9033 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00009034 ExprResult Arg0 = PerformCopyInitialization(
9035 InitializedEntity::InitializeParameter(Context,
9036 FnDecl->getParamDecl(0)),
9037 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009038 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009039 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009040
Chandler Carruth8e543b32010-12-12 08:17:55 +00009041 ExprResult Arg1 =
9042 PerformCopyInitialization(
9043 InitializedEntity::InitializeParameter(Context,
9044 FnDecl->getParamDecl(1)),
9045 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00009046 if (Arg1.isInvalid())
9047 return ExprError();
9048 Args[0] = LHS = Arg0.takeAs<Expr>();
9049 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009050 }
9051
John McCall4fa0d5f2010-05-06 18:15:07 +00009052 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9053
John McCall7decc9e2010-11-18 06:31:45 +00009054 // Determine the result type.
9055 QualType ResultTy = FnDecl->getResultType();
9056 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9057 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009058
9059 // Build the actual expression node.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009060 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9061 HadMultipleCandidates, OpLoc);
John Wiegley01296292011-04-08 18:41:53 +00009062 if (FnExpr.isInvalid())
9063 return ExprError();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009064
John McCallb268a282010-08-23 23:25:46 +00009065 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009066 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009067 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009068
9069 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009070 FnDecl))
9071 return ExprError();
9072
John McCallb268a282010-08-23 23:25:46 +00009073 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009074 } else {
9075 // We matched a built-in operator. Convert the arguments, then
9076 // break out so that we will build the appropriate built-in
9077 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009078 ExprResult ArgsRes0 =
9079 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9080 Best->Conversions[0], AA_Passing);
9081 if (ArgsRes0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009082 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009083 Args[0] = ArgsRes0.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009084
John Wiegley01296292011-04-08 18:41:53 +00009085 ExprResult ArgsRes1 =
9086 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9087 Best->Conversions[1], AA_Passing);
9088 if (ArgsRes1.isInvalid())
9089 return ExprError();
9090 Args[1] = ArgsRes1.take();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009091 break;
9092 }
9093 }
9094
Douglas Gregor66950a32009-09-30 21:46:01 +00009095 case OR_No_Viable_Function: {
9096 // C++ [over.match.oper]p9:
9097 // If the operator is the operator , [...] and there are no
9098 // viable functions, then the operator is assumed to be the
9099 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00009100 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00009101 break;
9102
Chandler Carruth8e543b32010-12-12 08:17:55 +00009103 // For class as left operand for assignment or compound assigment
9104 // operator do not fall through to handling in built-in, but report that
9105 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00009106 ExprResult Result = ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009107 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00009108 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00009109 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9110 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00009111 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00009112 } else {
Richard Smith998a5912011-06-05 22:42:48 +00009113 // This is an erroneous use of an operator which can be overloaded by
9114 // a non-member function. Check for non-member operators which were
9115 // defined too late to be candidates.
9116 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9117 // FIXME: Recover by calling the found function.
9118 return ExprError();
9119
Douglas Gregor66950a32009-09-30 21:46:01 +00009120 // No viable function; try to create a built-in operation, which will
9121 // produce an error. Then, show the non-viable candidates.
9122 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00009123 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009124 assert(Result.isInvalid() &&
Douglas Gregor66950a32009-09-30 21:46:01 +00009125 "C++ binary operator overloading is missing candidates!");
9126 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00009127 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9128 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00009129 return move(Result);
9130 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009131
9132 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009133 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009134 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00009135 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00009136 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009137 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9138 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009139 return ExprError();
9140
9141 case OR_Deleted:
9142 Diag(OpLoc, diag::err_ovl_deleted_oper)
9143 << Best->Function->isDeleted()
9144 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009145 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregore9899d92009-08-26 17:08:25 +00009146 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman79b2d3a2011-08-26 19:46:22 +00009147 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9148 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009149 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00009150 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009151
Douglas Gregor66950a32009-09-30 21:46:01 +00009152 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00009153 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00009154}
9155
John McCalldadc5752010-08-24 06:29:42 +00009156ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00009157Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9158 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00009159 Expr *Base, Expr *Idx) {
9160 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00009161 DeclarationName OpName =
9162 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9163
9164 // If either side is type-dependent, create an appropriate dependent
9165 // expression.
9166 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9167
John McCall58cc69d2010-01-27 01:50:18 +00009168 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00009169 // CHECKME: no 'operator' keyword?
9170 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9171 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00009172 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00009173 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor0da1d432011-02-28 20:01:57 +00009174 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00009175 /*ADL*/ true, /*Overloaded*/ false,
9176 UnresolvedSetIterator(),
9177 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00009178 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00009179
Sebastian Redladba46e2009-10-29 20:17:01 +00009180 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9181 Args, 2,
9182 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00009183 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00009184 RLoc));
9185 }
9186
John Wiegley01296292011-04-08 18:41:53 +00009187 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
9188 ExprResult Result = ConvertPropertyForRValue(Args[0]);
9189 if (Result.isInvalid())
9190 return ExprError();
9191 Args[0] = Result.take();
9192 }
9193 if (Args[1]->getObjectKind() == OK_ObjCProperty) {
9194 ExprResult Result = ConvertPropertyForRValue(Args[1]);
9195 if (Result.isInvalid())
9196 return ExprError();
9197 Args[1] = Result.take();
9198 }
John McCalle26a8722010-12-04 08:14:53 +00009199
Sebastian Redladba46e2009-10-29 20:17:01 +00009200 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00009201 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009202
9203 // Subscript can only be overloaded as a member function.
9204
9205 // Add operator candidates that are member functions.
9206 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9207
9208 // Add builtin operator candidates.
9209 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9210
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009211 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9212
Sebastian Redladba46e2009-10-29 20:17:01 +00009213 // Perform overload resolution.
9214 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009215 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00009216 case OR_Success: {
9217 // We found a built-in operator or an overloaded operator.
9218 FunctionDecl *FnDecl = Best->Function;
9219
9220 if (FnDecl) {
9221 // We matched an overloaded operator. Build a call to that
9222 // operator.
9223
Chandler Carruth30141632011-02-25 19:41:05 +00009224 MarkDeclarationReferenced(LLoc, FnDecl);
9225
John McCalla0296f72010-03-19 07:35:19 +00009226 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009227 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00009228
Sebastian Redladba46e2009-10-29 20:17:01 +00009229 // Convert the arguments.
9230 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley01296292011-04-08 18:41:53 +00009231 ExprResult Arg0 =
9232 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9233 Best->FoundDecl, Method);
9234 if (Arg0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009235 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009236 Args[0] = Arg0.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009237
Anders Carlssona68e51e2010-01-29 18:37:50 +00009238 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00009239 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00009240 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009241 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00009242 FnDecl->getParamDecl(0)),
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009243 SourceLocation(),
Anders Carlssona68e51e2010-01-29 18:37:50 +00009244 Owned(Args[1]));
9245 if (InputInit.isInvalid())
9246 return ExprError();
9247
9248 Args[1] = InputInit.takeAs<Expr>();
9249
Sebastian Redladba46e2009-10-29 20:17:01 +00009250 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00009251 QualType ResultTy = FnDecl->getResultType();
9252 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9253 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00009254
9255 // Build the actual expression node.
Douglas Gregore9d62932011-07-15 16:25:15 +00009256 DeclarationNameLoc LocInfo;
9257 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9258 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009259 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9260 HadMultipleCandidates,
9261 LLoc, LocInfo);
John Wiegley01296292011-04-08 18:41:53 +00009262 if (FnExpr.isInvalid())
9263 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009264
John McCallb268a282010-08-23 23:25:46 +00009265 CXXOperatorCallExpr *TheCall =
9266 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley01296292011-04-08 18:41:53 +00009267 FnExpr.take(), Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00009268 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009269
John McCallb268a282010-08-23 23:25:46 +00009270 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00009271 FnDecl))
9272 return ExprError();
9273
John McCallb268a282010-08-23 23:25:46 +00009274 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00009275 } else {
9276 // We matched a built-in operator. Convert the arguments, then
9277 // break out so that we will build the appropriate built-in
9278 // operator node.
John Wiegley01296292011-04-08 18:41:53 +00009279 ExprResult ArgsRes0 =
9280 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9281 Best->Conversions[0], AA_Passing);
9282 if (ArgsRes0.isInvalid())
Sebastian Redladba46e2009-10-29 20:17:01 +00009283 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009284 Args[0] = ArgsRes0.take();
9285
9286 ExprResult ArgsRes1 =
9287 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9288 Best->Conversions[1], AA_Passing);
9289 if (ArgsRes1.isInvalid())
9290 return ExprError();
9291 Args[1] = ArgsRes1.take();
Sebastian Redladba46e2009-10-29 20:17:01 +00009292
9293 break;
9294 }
9295 }
9296
9297 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00009298 if (CandidateSet.empty())
9299 Diag(LLoc, diag::err_ovl_no_oper)
9300 << Args[0]->getType() << /*subscript*/ 0
9301 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9302 else
9303 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9304 << Args[0]->getType()
9305 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009306 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9307 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00009308 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00009309 }
9310
9311 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009312 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009313 << "[]"
Douglas Gregor052caec2010-11-13 20:06:38 +00009314 << Args[0]->getType() << Args[1]->getType()
9315 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009316 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9317 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009318 return ExprError();
9319
9320 case OR_Deleted:
9321 Diag(LLoc, diag::err_ovl_deleted_oper)
9322 << Best->Function->isDeleted() << "[]"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009323 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redladba46e2009-10-29 20:17:01 +00009324 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009325 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9326 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009327 return ExprError();
9328 }
9329
9330 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00009331 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00009332}
9333
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009334/// BuildCallToMemberFunction - Build a call to a member
9335/// function. MemExpr is the expression that refers to the member
9336/// function (and includes the object parameter), Args/NumArgs are the
9337/// arguments to the function call (not including the object
9338/// parameter). The caller needs to validate that the member
John McCall0009fcc2011-04-26 20:42:42 +00009339/// expression refers to a non-static member function or an overloaded
9340/// member function.
John McCalldadc5752010-08-24 06:29:42 +00009341ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00009342Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9343 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00009344 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall0009fcc2011-04-26 20:42:42 +00009345 assert(MemExprE->getType() == Context.BoundMemberTy ||
9346 MemExprE->getType() == Context.OverloadTy);
9347
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009348 // Dig out the member expression. This holds both the object
9349 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00009350 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009351
John McCall0009fcc2011-04-26 20:42:42 +00009352 // Determine whether this is a call to a pointer-to-member function.
9353 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9354 assert(op->getType() == Context.BoundMemberTy);
9355 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9356
9357 QualType fnType =
9358 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9359
9360 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9361 QualType resultType = proto->getCallResultType(Context);
9362 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9363
9364 // Check that the object type isn't more qualified than the
9365 // member function we're calling.
9366 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9367
9368 QualType objectType = op->getLHS()->getType();
9369 if (op->getOpcode() == BO_PtrMemI)
9370 objectType = objectType->castAs<PointerType>()->getPointeeType();
9371 Qualifiers objectQuals = objectType.getQualifiers();
9372
9373 Qualifiers difference = objectQuals - funcQuals;
9374 difference.removeObjCGCAttr();
9375 difference.removeAddressSpace();
9376 if (difference) {
9377 std::string qualsString = difference.getAsString();
9378 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9379 << fnType.getUnqualifiedType()
9380 << qualsString
9381 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9382 }
9383
9384 CXXMemberCallExpr *call
9385 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9386 resultType, valueKind, RParenLoc);
9387
9388 if (CheckCallReturnType(proto->getResultType(),
9389 op->getRHS()->getSourceRange().getBegin(),
9390 call, 0))
9391 return ExprError();
9392
9393 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9394 return ExprError();
9395
9396 return MaybeBindToTemporary(call);
9397 }
9398
John McCall10eae182009-11-30 22:42:35 +00009399 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009400 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00009401 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009402 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00009403 if (isa<MemberExpr>(NakedMemExpr)) {
9404 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00009405 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00009406 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009407 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00009408 } else {
9409 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00009410 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009411
John McCall6e9f8f62009-12-03 04:06:58 +00009412 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor02824322011-01-26 19:30:28 +00009413 Expr::Classification ObjectClassification
9414 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9415 : UnresExpr->getBase()->Classify(Context);
John McCall10eae182009-11-30 22:42:35 +00009416
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009417 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00009418 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00009419
John McCall2d74de92009-12-01 22:10:20 +00009420 // FIXME: avoid copy.
9421 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9422 if (UnresExpr->hasExplicitTemplateArgs()) {
9423 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9424 TemplateArgs = &TemplateArgsBuffer;
9425 }
9426
John McCall10eae182009-11-30 22:42:35 +00009427 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9428 E = UnresExpr->decls_end(); I != E; ++I) {
9429
John McCall6e9f8f62009-12-03 04:06:58 +00009430 NamedDecl *Func = *I;
9431 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9432 if (isa<UsingShadowDecl>(Func))
9433 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9434
Douglas Gregor02824322011-01-26 19:30:28 +00009435
Francois Pichet64225792011-01-18 05:04:39 +00009436 // Microsoft supports direct constructor calls.
Francois Pichet0706d202011-09-17 17:15:52 +00009437 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichet64225792011-01-18 05:04:39 +00009438 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9439 CandidateSet);
9440 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00009441 // If explicit template arguments were provided, we can't call a
9442 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00009443 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00009444 continue;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009445
John McCalla0296f72010-03-19 07:35:19 +00009446 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009447 ObjectClassification,
9448 Args, NumArgs, CandidateSet,
Douglas Gregor02824322011-01-26 19:30:28 +00009449 /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009450 } else {
John McCall10eae182009-11-30 22:42:35 +00009451 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00009452 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009453 ObjectType, ObjectClassification,
Douglas Gregor02824322011-01-26 19:30:28 +00009454 Args, NumArgs, CandidateSet,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009455 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00009456 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00009457 }
Mike Stump11289f42009-09-09 15:08:12 +00009458
John McCall10eae182009-11-30 22:42:35 +00009459 DeclarationName DeclName = UnresExpr->getMemberName();
9460
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009461 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009462 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00009463 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009464 case OR_Success:
9465 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth30141632011-02-25 19:41:05 +00009466 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall16df1e52010-03-30 21:47:33 +00009467 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00009468 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009469 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009470 break;
9471
9472 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00009473 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009474 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009475 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009476 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009477 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009478 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009479
9480 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00009481 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00009482 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009483 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009484 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009485 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009486
9487 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00009488 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00009489 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009490 << DeclName
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009491 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009492 << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009493 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009494 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00009495 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009496 }
9497
John McCall16df1e52010-03-30 21:47:33 +00009498 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00009499
John McCall2d74de92009-12-01 22:10:20 +00009500 // If overload resolution picked a static member, build a
9501 // non-member call based on that function.
9502 if (Method->isStatic()) {
9503 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9504 Args, NumArgs, RParenLoc);
9505 }
9506
John McCall10eae182009-11-30 22:42:35 +00009507 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009508 }
9509
John McCall7decc9e2010-11-18 06:31:45 +00009510 QualType ResultType = Method->getResultType();
9511 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9512 ResultType = ResultType.getNonLValueExprType(Context);
9513
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009514 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009515 CXXMemberCallExpr *TheCall =
John McCallb268a282010-08-23 23:25:46 +00009516 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00009517 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009518
Anders Carlssonc4859ba2009-10-10 00:06:20 +00009519 // Check for a valid return type.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009520 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00009521 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00009522 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009523
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009524 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00009525 // We only need to do this if there was actually an overload; otherwise
9526 // it was done at lookup.
John Wiegley01296292011-04-08 18:41:53 +00009527 if (!Method->isStatic()) {
9528 ExprResult ObjectArg =
9529 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9530 FoundDecl, Method);
9531 if (ObjectArg.isInvalid())
9532 return ExprError();
9533 MemExpr->setBase(ObjectArg.take());
9534 }
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009535
9536 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00009537 const FunctionProtoType *Proto =
9538 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00009539 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009540 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00009541 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009542
John McCallb268a282010-08-23 23:25:46 +00009543 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00009544 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00009545
Anders Carlsson47061ee2011-05-06 14:25:31 +00009546 if ((isa<CXXConstructorDecl>(CurContext) ||
9547 isa<CXXDestructorDecl>(CurContext)) &&
9548 TheCall->getMethodDecl()->isPure()) {
9549 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9550
Chandler Carruth59259262011-06-27 08:31:58 +00009551 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson47061ee2011-05-06 14:25:31 +00009552 Diag(MemExpr->getLocStart(),
9553 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9554 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9555 << MD->getParent()->getDeclName();
9556
9557 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruth59259262011-06-27 08:31:58 +00009558 }
Anders Carlsson47061ee2011-05-06 14:25:31 +00009559 }
John McCallb268a282010-08-23 23:25:46 +00009560 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00009561}
9562
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009563/// BuildCallToObjectOfClassType - Build a call to an object of class
9564/// type (C++ [over.call.object]), which can end up invoking an
9565/// overloaded function call operator (@c operator()) or performing a
9566/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00009567ExprResult
John Wiegley01296292011-04-08 18:41:53 +00009568Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregorb0846b02008-12-06 00:22:45 +00009569 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009570 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009571 SourceLocation RParenLoc) {
John Wiegley01296292011-04-08 18:41:53 +00009572 ExprResult Object = Owned(Obj);
9573 if (Object.get()->getObjectKind() == OK_ObjCProperty) {
9574 Object = ConvertPropertyForRValue(Object.take());
9575 if (Object.isInvalid())
9576 return ExprError();
9577 }
John McCalle26a8722010-12-04 08:14:53 +00009578
John Wiegley01296292011-04-08 18:41:53 +00009579 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9580 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00009581
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009582 // C++ [over.call.object]p1:
9583 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00009584 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009585 // candidate functions includes at least the function call
9586 // operators of T. The function call operators of T are obtained by
9587 // ordinary lookup of the name operator() in the context of
9588 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00009589 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00009590 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009591
John Wiegley01296292011-04-08 18:41:53 +00009592 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00009593 PDiag(diag::err_incomplete_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009594 << Object.get()->getSourceRange()))
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009595 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009596
John McCall27b18f82009-11-17 02:14:36 +00009597 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9598 LookupQualifiedName(R, Record->getDecl());
9599 R.suppressDiagnostics();
9600
Douglas Gregorc473cbb2009-11-15 07:48:03 +00009601 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00009602 Oper != OperEnd; ++Oper) {
John Wiegley01296292011-04-08 18:41:53 +00009603 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9604 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00009605 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00009606 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009607
Douglas Gregorab7897a2008-11-19 22:57:39 +00009608 // C++ [over.call.object]p2:
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009609 // In addition, for each (non-explicit in C++0x) conversion function
9610 // declared in T of the form
Douglas Gregorab7897a2008-11-19 22:57:39 +00009611 //
9612 // operator conversion-type-id () cv-qualifier;
9613 //
9614 // where cv-qualifier is the same cv-qualification as, or a
9615 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00009616 // denotes the type "pointer to function of (P1,...,Pn) returning
9617 // R", or the type "reference to pointer to function of
9618 // (P1,...,Pn) returning R", or the type "reference to function
9619 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00009620 // is also considered as a candidate function. Similarly,
9621 // surrogate call functions are added to the set of candidate
9622 // functions for each conversion function declared in an
9623 // accessible base class provided the function is not hidden
9624 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00009625 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00009626 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00009627 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00009628 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00009629 NamedDecl *D = *I;
9630 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9631 if (isa<UsingShadowDecl>(D))
9632 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009633
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009634 // Skip over templated conversion functions; they aren't
9635 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00009636 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00009637 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00009638
John McCall6e9f8f62009-12-03 04:06:58 +00009639 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009640 if (!Conv->isExplicit()) {
9641 // Strip the reference type (if any) and then the pointer type (if
9642 // any) to get down to what might be a function type.
9643 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9644 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9645 ConvType = ConvPtrType->getPointeeType();
John McCalld14a8642009-11-21 08:51:07 +00009646
Douglas Gregor38b2d3f2011-07-23 18:59:35 +00009647 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9648 {
9649 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9650 Object.get(), Args, NumArgs, CandidateSet);
9651 }
9652 }
Douglas Gregorab7897a2008-11-19 22:57:39 +00009653 }
Mike Stump11289f42009-09-09 15:08:12 +00009654
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009655 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9656
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009657 // Perform overload resolution.
9658 OverloadCandidateSet::iterator Best;
John Wiegley01296292011-04-08 18:41:53 +00009659 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall5c32be02010-08-24 20:38:10 +00009660 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009661 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00009662 // Overload resolution succeeded; we'll build the appropriate call
9663 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009664 break;
9665
9666 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00009667 if (CandidateSet.empty())
John Wiegley01296292011-04-08 18:41:53 +00009668 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9669 << Object.get()->getType() << /*call*/ 1
9670 << Object.get()->getSourceRange();
John McCall02374852010-01-07 02:04:15 +00009671 else
John Wiegley01296292011-04-08 18:41:53 +00009672 Diag(Object.get()->getSourceRange().getBegin(),
John McCall02374852010-01-07 02:04:15 +00009673 diag::err_ovl_no_viable_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009674 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009675 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009676 break;
9677
9678 case OR_Ambiguous:
John Wiegley01296292011-04-08 18:41:53 +00009679 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009680 diag::err_ovl_ambiguous_object_call)
John Wiegley01296292011-04-08 18:41:53 +00009681 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009682 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009683 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00009684
9685 case OR_Deleted:
John Wiegley01296292011-04-08 18:41:53 +00009686 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor171c45a2009-02-18 21:56:37 +00009687 diag::err_ovl_deleted_object_call)
9688 << Best->Function->isDeleted()
John Wiegley01296292011-04-08 18:41:53 +00009689 << Object.get()->getType()
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009690 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley01296292011-04-08 18:41:53 +00009691 << Object.get()->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009692 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00009693 break;
Mike Stump11289f42009-09-09 15:08:12 +00009694 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009695
Douglas Gregorb412e172010-07-25 18:17:45 +00009696 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009697 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009698
Douglas Gregorab7897a2008-11-19 22:57:39 +00009699 if (Best->Function == 0) {
9700 // Since there is no function declaration, this is one of the
9701 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00009702 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00009703 = cast<CXXConversionDecl>(
9704 Best->Conversions[0].UserDefined.ConversionFunction);
9705
John Wiegley01296292011-04-08 18:41:53 +00009706 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009707 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009708
Douglas Gregorab7897a2008-11-19 22:57:39 +00009709 // We selected one of the surrogate functions that converts the
9710 // object parameter to a function pointer. Perform the conversion
9711 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009712
Fariborz Jahanian774cf792009-09-28 18:35:46 +00009713 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00009714 // and then call it.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009715 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
9716 Conv, HadMultipleCandidates);
Douglas Gregor668443e2011-01-20 00:18:04 +00009717 if (Call.isInvalid())
9718 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009719
Douglas Gregor668443e2011-01-20 00:18:04 +00009720 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00009721 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00009722 }
9723
Chandler Carruth30141632011-02-25 19:41:05 +00009724 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009725 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009726 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00009727
Douglas Gregorab7897a2008-11-19 22:57:39 +00009728 // We found an overloaded operator(). Build a CXXOperatorCallExpr
9729 // that calls this method, using Object for the implicit object
9730 // parameter and passing along the remaining arguments.
9731 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00009732 const FunctionProtoType *Proto =
9733 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009734
9735 unsigned NumArgsInProto = Proto->getNumArgs();
9736 unsigned NumArgsToCheck = NumArgs;
9737
9738 // Build the full argument list for the method call (the
9739 // implicit object parameter is placed at the beginning of the
9740 // list).
9741 Expr **MethodArgs;
9742 if (NumArgs < NumArgsInProto) {
9743 NumArgsToCheck = NumArgsInProto;
9744 MethodArgs = new Expr*[NumArgsInProto + 1];
9745 } else {
9746 MethodArgs = new Expr*[NumArgs + 1];
9747 }
John Wiegley01296292011-04-08 18:41:53 +00009748 MethodArgs[0] = Object.get();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009749 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9750 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00009751
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009752 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
9753 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00009754 if (NewFn.isInvalid())
9755 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009756
9757 // Once we've built TheCall, all of the expressions are properly
9758 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00009759 QualType ResultTy = Method->getResultType();
9760 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9761 ResultTy = ResultTy.getNonLValueExprType(Context);
9762
John McCallb268a282010-08-23 23:25:46 +00009763 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009764 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCallb268a282010-08-23 23:25:46 +00009765 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00009766 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009767 delete [] MethodArgs;
9768
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009769 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00009770 Method))
9771 return true;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009772
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009773 // We may have default arguments. If so, we need to allocate more
9774 // slots in the call for them.
9775 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00009776 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009777 else if (NumArgs > NumArgsInProto)
9778 NumArgsToCheck = NumArgsInProto;
9779
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009780 bool IsError = false;
9781
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009782 // Initialize the implicit object parameter.
John Wiegley01296292011-04-08 18:41:53 +00009783 ExprResult ObjRes =
9784 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9785 Best->FoundDecl, Method);
9786 if (ObjRes.isInvalid())
9787 IsError = true;
9788 else
9789 Object = move(ObjRes);
9790 TheCall->setArg(0, Object.take());
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009791
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009792 // Check the argument types.
9793 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009794 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009795 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009796 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00009797
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009798 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009799
John McCalldadc5752010-08-24 06:29:42 +00009800 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009801 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00009802 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009803 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00009804 SourceLocation(), Arg);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009805
Anders Carlsson7c5fe482010-01-29 18:43:53 +00009806 IsError |= InputInit.isInvalid();
9807 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009808 } else {
John McCalldadc5752010-08-24 06:29:42 +00009809 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009810 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9811 if (DefArg.isInvalid()) {
9812 IsError = true;
9813 break;
9814 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009815
Douglas Gregor1bc688d2009-11-09 19:27:57 +00009816 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00009817 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009818
9819 TheCall->setArg(i + 1, Arg);
9820 }
9821
9822 // If this is a variadic call, handle args passed through "...".
9823 if (Proto->isVariadic()) {
9824 // Promote the arguments (C99 6.5.2.2p7).
9825 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley01296292011-04-08 18:41:53 +00009826 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9827 IsError |= Arg.isInvalid();
9828 TheCall->setArg(i + 1, Arg.take());
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009829 }
9830 }
9831
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00009832 if (IsError) return true;
9833
John McCallb268a282010-08-23 23:25:46 +00009834 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00009835 return true;
9836
John McCalle172be52010-08-24 06:09:16 +00009837 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00009838}
9839
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009840/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00009841/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009842/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00009843ExprResult
John McCallb268a282010-08-23 23:25:46 +00009844Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00009845 assert(Base->getType()->isRecordType() &&
9846 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00009847
John Wiegley01296292011-04-08 18:41:53 +00009848 if (Base->getObjectKind() == OK_ObjCProperty) {
9849 ExprResult Result = ConvertPropertyForRValue(Base);
9850 if (Result.isInvalid())
9851 return ExprError();
9852 Base = Result.take();
9853 }
John McCalle26a8722010-12-04 08:14:53 +00009854
John McCallbc077cf2010-02-08 23:07:23 +00009855 SourceLocation Loc = Base->getExprLoc();
9856
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009857 // C++ [over.ref]p1:
9858 //
9859 // [...] An expression x->m is interpreted as (x.operator->())->m
9860 // for a class object x of type T if T::operator->() exists and if
9861 // the operator is selected as the best match function by the
9862 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00009863 DeclarationName OpName =
9864 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00009865 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00009866 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00009867
John McCallbc077cf2010-02-08 23:07:23 +00009868 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00009869 PDiag(diag::err_typecheck_incomplete_tag)
9870 << Base->getSourceRange()))
9871 return ExprError();
9872
John McCall27b18f82009-11-17 02:14:36 +00009873 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9874 LookupQualifiedName(R, BaseRecord->getDecl());
9875 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00009876
9877 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00009878 Oper != OperEnd; ++Oper) {
Douglas Gregor02824322011-01-26 19:30:28 +00009879 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9880 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00009881 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009882
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009883 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9884
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009885 // Perform overload resolution.
9886 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00009887 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009888 case OR_Success:
9889 // Overload resolution succeeded; we'll build the call below.
9890 break;
9891
9892 case OR_No_Viable_Function:
9893 if (CandidateSet.empty())
9894 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00009895 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009896 else
9897 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00009898 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009899 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009900 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009901
9902 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00009903 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9904 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009905 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009906 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00009907
9908 case OR_Deleted:
9909 Diag(OpLoc, diag::err_ovl_deleted_oper)
9910 << Best->Function->isDeleted()
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009911 << "->"
Douglas Gregor20b2ebd2011-03-23 00:50:03 +00009912 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahaniane6b127d2011-02-25 20:51:14 +00009913 << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00009914 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00009915 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009916 }
9917
Chandler Carruth30141632011-02-25 19:41:05 +00009918 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCalla0296f72010-03-19 07:35:19 +00009919 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00009920 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00009921
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009922 // Convert the object parameter.
9923 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley01296292011-04-08 18:41:53 +00009924 ExprResult BaseResult =
9925 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
9926 Best->FoundDecl, Method);
9927 if (BaseResult.isInvalid())
Douglas Gregord8061562009-08-06 03:17:00 +00009928 return ExprError();
John Wiegley01296292011-04-08 18:41:53 +00009929 Base = BaseResult.take();
Douglas Gregor9ecea262008-11-21 03:04:22 +00009930
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009931 // Build the operator call.
Abramo Bagnara635ed24e2011-10-05 07:56:41 +00009932 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
9933 HadMultipleCandidates);
John Wiegley01296292011-04-08 18:41:53 +00009934 if (FnExpr.isInvalid())
9935 return ExprError();
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009936
John McCall7decc9e2010-11-18 06:31:45 +00009937 QualType ResultTy = Method->getResultType();
9938 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9939 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00009940 CXXOperatorCallExpr *TheCall =
John Wiegley01296292011-04-08 18:41:53 +00009941 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCall7decc9e2010-11-18 06:31:45 +00009942 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009943
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009944 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00009945 Method))
9946 return ExprError();
Eli Friedman2d9c47e2011-04-04 01:18:25 +00009947
9948 return MaybeBindToTemporary(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00009949}
9950
Douglas Gregorcd695e52008-11-10 20:40:00 +00009951/// FixOverloadedFunctionReference - E is an expression that refers to
9952/// a C++ overloaded function (possibly with some parentheses and
9953/// perhaps a '&' around it). We have resolved the overloaded function
9954/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00009955/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00009956Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00009957 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00009958 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009959 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
9960 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00009961 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009962 return PE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009963
Douglas Gregor51c538b2009-11-20 19:42:02 +00009964 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009965 }
9966
Douglas Gregor51c538b2009-11-20 19:42:02 +00009967 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00009968 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
9969 Found, Fn);
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009970 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00009971 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00009972 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00009973 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00009974 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009975 return ICE;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009976
9977 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallcf142162010-08-07 06:22:56 +00009978 ICE->getCastKind(),
9979 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00009980 ICE->getValueKind());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +00009981 }
9982
Douglas Gregor51c538b2009-11-20 19:42:02 +00009983 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00009984 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00009985 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00009986 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
9987 if (Method->isStatic()) {
9988 // Do nothing: static member functions aren't any different
9989 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00009990 } else {
John McCalle66edc12009-11-24 19:00:30 +00009991 // Fix the sub expression, which really has to be an
9992 // UnresolvedLookupExpr holding an overloaded member function
9993 // or template.
John McCall16df1e52010-03-30 21:47:33 +00009994 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
9995 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00009996 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00009997 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00009998
John McCalld14a8642009-11-21 08:51:07 +00009999 assert(isa<DeclRefExpr>(SubExpr)
10000 && "fixed to something other than a decl ref");
10001 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10002 && "fixed to a member ref with no nested name qualifier");
10003
10004 // We have taken the address of a pointer to member
10005 // function. Perform the computation here so that we get the
10006 // appropriate pointer to member type.
10007 QualType ClassType
10008 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10009 QualType MemPtrType
10010 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10011
John McCall7decc9e2010-11-18 06:31:45 +000010012 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10013 VK_RValue, OK_Ordinary,
10014 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +000010015 }
10016 }
John McCall16df1e52010-03-30 21:47:33 +000010017 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10018 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +000010019 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +000010020 return UnOp;
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010021
John McCalle3027922010-08-25 11:45:40 +000010022 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010023 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +000010024 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +000010025 UnOp->getOperatorLoc());
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010026 }
John McCalld14a8642009-11-21 08:51:07 +000010027
10028 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +000010029 // FIXME: avoid copy.
10030 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +000010031 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +000010032 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10033 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +000010034 }
10035
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010036 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10037 ULE->getQualifierLoc(),
10038 Fn,
10039 ULE->getNameLoc(),
10040 Fn->getType(),
10041 VK_LValue,
10042 Found.getDecl(),
10043 TemplateArgs);
10044 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10045 return DRE;
John McCalld14a8642009-11-21 08:51:07 +000010046 }
10047
John McCall10eae182009-11-30 22:42:35 +000010048 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +000010049 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +000010050 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10051 if (MemExpr->hasExplicitTemplateArgs()) {
10052 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10053 TemplateArgs = &TemplateArgsBuffer;
10054 }
John McCall6b51f282009-11-23 01:53:49 +000010055
John McCall2d74de92009-12-01 22:10:20 +000010056 Expr *Base;
10057
John McCall7decc9e2010-11-18 06:31:45 +000010058 // If we're filling in a static method where we used to have an
10059 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +000010060 if (MemExpr->isImplicitAccess()) {
10061 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010062 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10063 MemExpr->getQualifierLoc(),
10064 Fn,
10065 MemExpr->getMemberLoc(),
10066 Fn->getType(),
10067 VK_LValue,
10068 Found.getDecl(),
10069 TemplateArgs);
10070 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10071 return DRE;
Douglas Gregorb15af892010-01-07 23:12:05 +000010072 } else {
10073 SourceLocation Loc = MemExpr->getMemberLoc();
10074 if (MemExpr->getQualifier())
Douglas Gregor0da1d432011-02-28 20:01:57 +000010075 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregorb15af892010-01-07 23:12:05 +000010076 Base = new (Context) CXXThisExpr(Loc,
10077 MemExpr->getBaseType(),
10078 /*isImplicit=*/true);
10079 }
John McCall2d74de92009-12-01 22:10:20 +000010080 } else
John McCallc3007a22010-10-26 07:05:15 +000010081 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +000010082
John McCall4adb38c2011-04-27 00:36:17 +000010083 ExprValueKind valueKind;
10084 QualType type;
10085 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10086 valueKind = VK_LValue;
10087 type = Fn->getType();
10088 } else {
10089 valueKind = VK_RValue;
10090 type = Context.BoundMemberTy;
10091 }
10092
Abramo Bagnara635ed24e2011-10-05 07:56:41 +000010093 MemberExpr *ME = MemberExpr::Create(Context, Base,
10094 MemExpr->isArrow(),
10095 MemExpr->getQualifierLoc(),
10096 Fn,
10097 Found,
10098 MemExpr->getMemberNameInfo(),
10099 TemplateArgs,
10100 type, valueKind, OK_Ordinary);
10101 ME->setHadMultipleCandidates(true);
10102 return ME;
Douglas Gregor51c538b2009-11-20 19:42:02 +000010103 }
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010104
John McCallc3007a22010-10-26 07:05:15 +000010105 llvm_unreachable("Invalid reference to overloaded function");
10106 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +000010107}
10108
NAKAMURA Takumif9cbcc42011-01-27 07:10:08 +000010109ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCalldadc5752010-08-24 06:29:42 +000010110 DeclAccessPair Found,
10111 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +000010112 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +000010113}
10114
Douglas Gregor5251f1b2008-10-21 16:13:35 +000010115} // end namespace clang