blob: 6977462bc92a5d1e3f3dd3566d0676a484087a90 [file] [log] [blame]
Douglas Gregor8e9bebd2008-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 McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregore737f502010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCall7cd088e2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall2a7fb272010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCall7cd088e2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregorf9eb9052008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCall0e800c92010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregoreb8f3062008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssonb7906612009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor661b4932010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregorbf3af052008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor3fc749d2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall2a7fb272010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000036
John McCallf89e55a2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
John Wiegley429bb272011-04-08 18:41:53 +000039static ExprResult
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000040CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn, bool HadMultipleCandidates,
Douglas Gregor5b8968c2011-07-15 16:25:15 +000041 SourceLocation Loc = SourceLocation(),
42 const DeclarationNameLoc &LocInfo = DeclarationNameLoc()){
Abramo Bagnara7cc58b42011-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 Wiegley429bb272011-04-08 18:41:53 +000048 E = S.DefaultFunctionArrayConversion(E.take());
49 if (E.isInvalid())
50 return ExprError();
51 return move(E);
John McCallf89e55a2010-11-18 06:31:45 +000052}
53
John McCall120d63c2010-08-24 20:38:10 +000054static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
55 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +000056 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +000057 bool CStyle,
58 bool AllowObjCWritebackConversion);
Fariborz Jahaniand97f5582011-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 McCall120d63c2010-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 Gregor8e9bebd2008-10-21 16:13:35 +000089/// GetConversionCategory - Retrieve the implicit conversion
90/// category corresponding to the given implicit conversion kind.
Mike Stump1eb44332009-09-09 15:08:12 +000091ImplicitConversionCategory
Douglas Gregor8e9bebd2008-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 Gregor43c79c22009-12-09 00:47:37 +000099 ICC_Identity,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000100 ICC_Qualification_Adjustment,
101 ICC_Promotion,
102 ICC_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000103 ICC_Promotion,
104 ICC_Conversion,
105 ICC_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000106 ICC_Conversion,
107 ICC_Conversion,
108 ICC_Conversion,
109 ICC_Conversion,
110 ICC_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000111 ICC_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000112 ICC_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000113 ICC_Conversion,
114 ICC_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000115 ICC_Conversion,
Douglas Gregor8e9bebd2008-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 Gregor43c79c22009-12-09 00:47:37 +0000131 ICR_Exact_Match,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000132 ICR_Promotion,
133 ICR_Promotion,
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000134 ICR_Promotion,
135 ICR_Conversion,
136 ICR_Conversion,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000137 ICR_Conversion,
138 ICR_Conversion,
139 ICR_Conversion,
140 ICR_Conversion,
141 ICR_Conversion,
Douglas Gregor15da57e2008-10-29 02:00:59 +0000142 ICR_Conversion,
Douglas Gregorf9201e02009-02-11 23:02:49 +0000143 ICR_Conversion,
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000144 ICR_Conversion,
145 ICR_Conversion,
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000146 ICR_Complex_Real_Conversion,
147 ICR_Conversion,
John McCallf85e1932011-06-15 23:02:42 +0000148 ICR_Conversion,
149 ICR_Writeback_Conversion
Douglas Gregor8e9bebd2008-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 Lopes2550d702009-12-23 17:49:57 +0000157 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000158 "No conversion",
159 "Lvalue-to-rvalue",
160 "Array-to-pointer",
161 "Function-to-pointer",
Douglas Gregor43c79c22009-12-09 00:47:37 +0000162 "Noreturn adjustment",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000163 "Qualification",
164 "Integral promotion",
165 "Floating point promotion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000166 "Complex promotion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000167 "Integral conversion",
168 "Floating conversion",
Douglas Gregor5cdf8212009-02-12 00:15:05 +0000169 "Complex conversion",
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000170 "Floating-integral conversion",
171 "Pointer conversion",
172 "Pointer-to-member conversion",
Douglas Gregor15da57e2008-10-29 02:00:59 +0000173 "Boolean conversion",
Douglas Gregorf9201e02009-02-11 23:02:49 +0000174 "Compatible-types conversion",
Douglas Gregorfb4a5432010-05-18 22:42:18 +0000175 "Derived-to-base conversion",
176 "Vector conversion",
177 "Vector splat",
Fariborz Jahaniand97f5582011-03-23 19:50:54 +0000178 "Complex-real conversion",
179 "Block Pointer conversion",
180 "Transparent Union Conversion"
John McCallf85e1932011-06-15 23:02:42 +0000181 "Writeback conversion"
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000182 };
183 return Name[Kind];
184}
185
Douglas Gregor60d62c22008-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 Gregora9bff302010-02-28 18:30:25 +0000192 DeprecatedStringLiteralToCharPtr = false;
John McCallf85e1932011-06-15 23:02:42 +0000193 QualificationIncludesObjCLifetime = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000194 ReferenceBinding = false;
195 DirectBinding = false;
Douglas Gregor440a4832011-01-26 14:52:12 +0000196 IsLvalueReference = true;
197 BindsToFunctionLvalue = false;
198 BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +0000199 BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +0000200 ObjCLifetimeConversionBinding = false;
Douglas Gregor225c41e2008-11-03 19:09:14 +0000201 CopyConstructor = 0;
Douglas Gregor60d62c22008-10-31 16:23:19 +0000202}
203
Douglas Gregor8e9bebd2008-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 Stump1eb44332009-09-09 15:08:12 +0000220/// used as part of the ranking of standard conversion sequences
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000221/// (C++ 13.3.3.2p4).
Mike Stump1eb44332009-09-09 15:08:12 +0000222bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor8e9bebd2008-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 Gregorad323a82010-01-27 03:51:04 +0000227 if (getToType(1)->isBooleanType() &&
John McCallddb0ce72010-06-11 10:04:22 +0000228 (getFromType()->isPointerType() ||
229 getFromType()->isObjCObjectPointerType() ||
230 getFromType()->isBlockPointerType() ||
Anders Carlssonc8df0b62010-11-05 00:12:09 +0000231 getFromType()->isNullPtrType() ||
Douglas Gregor8e9bebd2008-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 Gregorbc0805a2008-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 Stump1eb44332009-09-09 15:08:12 +0000242bool
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000243StandardConversionSequence::
Mike Stump1eb44332009-09-09 15:08:12 +0000244isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall1d318332010-01-12 00:44:57 +0000245 QualType FromType = getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +0000246 QualType ToType = getToType(1);
Douglas Gregorbc0805a2008-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 Gregorf9af5242011-04-15 20:45:44 +0000254 if (Second == ICK_Pointer_Conversion && FromType->isAnyPointerType())
Ted Kremenek6217b802009-07-29 21:53:49 +0000255 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregorbc0805a2008-10-23 00:40:37 +0000256 return ToPtrType->getPointeeType()->isVoidType();
257
258 return false;
259}
260
Douglas Gregor8e9bebd2008-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 Lattner5f9e2722011-07-23 10:55:15 +0000264 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000265 bool PrintedSomething = false;
266 if (First != ICK_Identity) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000267 OS << GetImplicitConversionName(First);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000268 PrintedSomething = true;
269 }
270
271 if (Second != ICK_Identity) {
272 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000273 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000274 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000275 OS << GetImplicitConversionName(Second);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000276
277 if (CopyConstructor) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000278 OS << " (by copy constructor)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000279 } else if (DirectBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000280 OS << " (direct reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000281 } else if (ReferenceBinding) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000282 OS << " (reference binding)";
Douglas Gregor225c41e2008-11-03 19:09:14 +0000283 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000284 PrintedSomething = true;
285 }
286
287 if (Third != ICK_Identity) {
288 if (PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000289 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000290 }
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000291 OS << GetImplicitConversionName(Third);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000292 PrintedSomething = true;
293 }
294
295 if (!PrintedSomething) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000296 OS << "No conversions required";
Douglas Gregor8e9bebd2008-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 Lattner5f9e2722011-07-23 10:55:15 +0000303 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000304 if (Before.First || Before.Second || Before.Third) {
305 Before.DebugPrint();
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000306 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000307 }
Sebastian Redlcc7a6482011-11-01 15:53:09 +0000308 if (ConversionFunction)
309 OS << '\'' << *ConversionFunction << '\'';
310 else
311 OS << "aggregate initialization";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000312 if (After.First || After.Second || After.Third) {
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000313 OS << " -> ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000314 After.DebugPrint();
315 }
316}
317
318/// DebugPrint - Print this implicit conversion sequence to standard
319/// error. Useful for debugging overloading issues.
320void ImplicitConversionSequence::DebugPrint() const {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000321 raw_ostream &OS = llvm::errs();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000322 switch (ConversionKind) {
323 case StandardConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000324 OS << "Standard conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000325 Standard.DebugPrint();
326 break;
327 case UserDefinedConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000328 OS << "User-defined conversion: ";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000329 UserDefined.DebugPrint();
330 break;
331 case EllipsisConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000332 OS << "Ellipsis conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000333 break;
John McCall1d318332010-01-12 00:44:57 +0000334 case AmbiguousConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000335 OS << "Ambiguous conversion";
John McCall1d318332010-01-12 00:44:57 +0000336 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000337 case BadConversion:
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000338 OS << "Bad conversion";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000339 break;
340 }
341
Daniel Dunbarf3f91f32010-01-22 02:04:41 +0000342 OS << "\n";
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000343}
344
John McCall1d318332010-01-12 00:44:57 +0000345void AmbiguousConversionSequence::construct() {
346 new (&conversions()) ConversionSet();
347}
348
349void AmbiguousConversionSequence::destruct() {
350 conversions().~ConversionSet();
351}
352
353void
354AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
355 FromTypePtr = O.FromTypePtr;
356 ToTypePtr = O.ToTypePtr;
357 new (&conversions()) ConversionSet(O.conversions());
358}
359
Douglas Gregora9333192010-05-08 17:41:32 +0000360namespace {
361 // Structure used by OverloadCandidate::DeductionFailureInfo to store
362 // template parameter and template argument information.
363 struct DFIParamWithArguments {
364 TemplateParameter Param;
365 TemplateArgument FirstArg;
366 TemplateArgument SecondArg;
367 };
368}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000369
Douglas Gregora9333192010-05-08 17:41:32 +0000370/// \brief Convert from Sema's representation of template deduction information
371/// to the form used in overload-candidate information.
372OverloadCandidate::DeductionFailureInfo
Douglas Gregorff5adac2010-05-08 20:18:54 +0000373static MakeDeductionFailureInfo(ASTContext &Context,
374 Sema::TemplateDeductionResult TDK,
John McCall2a7fb272010-08-25 05:32:35 +0000375 TemplateDeductionInfo &Info) {
Douglas Gregora9333192010-05-08 17:41:32 +0000376 OverloadCandidate::DeductionFailureInfo Result;
377 Result.Result = static_cast<unsigned>(TDK);
378 Result.Data = 0;
379 switch (TDK) {
380 case Sema::TDK_Success:
381 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000382 case Sema::TDK_TooManyArguments:
383 case Sema::TDK_TooFewArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000384 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000385
Douglas Gregora9333192010-05-08 17:41:32 +0000386 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000387 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000388 Result.Data = Info.Param.getOpaqueValue();
389 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000390
Douglas Gregora9333192010-05-08 17:41:32 +0000391 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000392 case Sema::TDK_Underqualified: {
Douglas Gregorff5adac2010-05-08 20:18:54 +0000393 // FIXME: Should allocate from normal heap so that we can free this later.
394 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregora9333192010-05-08 17:41:32 +0000395 Saved->Param = Info.Param;
396 Saved->FirstArg = Info.FirstArg;
397 Saved->SecondArg = Info.SecondArg;
398 Result.Data = Saved;
399 break;
400 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000401
Douglas Gregora9333192010-05-08 17:41:32 +0000402 case Sema::TDK_SubstitutionFailure:
Douglas Gregorec20f462010-05-08 20:07:26 +0000403 Result.Data = Info.take();
404 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000405
Douglas Gregora9333192010-05-08 17:41:32 +0000406 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000407 case Sema::TDK_FailedOverloadResolution:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000408 break;
Douglas Gregora9333192010-05-08 17:41:32 +0000409 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000410
Douglas Gregora9333192010-05-08 17:41:32 +0000411 return Result;
412}
John McCall1d318332010-01-12 00:44:57 +0000413
Douglas Gregora9333192010-05-08 17:41:32 +0000414void OverloadCandidate::DeductionFailureInfo::Destroy() {
415 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
416 case Sema::TDK_Success:
417 case Sema::TDK_InstantiationDepth:
418 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000419 case Sema::TDK_TooManyArguments:
420 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000421 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregora9333192010-05-08 17:41:32 +0000422 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000423
Douglas Gregora9333192010-05-08 17:41:32 +0000424 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000425 case Sema::TDK_Underqualified:
Douglas Gregoraaa045d2010-05-08 20:20:05 +0000426 // FIXME: Destroy the data?
Douglas Gregora9333192010-05-08 17:41:32 +0000427 Data = 0;
428 break;
Douglas Gregorec20f462010-05-08 20:07:26 +0000429
430 case Sema::TDK_SubstitutionFailure:
431 // FIXME: Destroy the template arugment list?
432 Data = 0;
433 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000434
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000435 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000436 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000437 case Sema::TDK_FailedOverloadResolution:
438 break;
439 }
440}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000441
442TemplateParameter
Douglas Gregora9333192010-05-08 17:41:32 +0000443OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
444 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
445 case Sema::TDK_Success:
446 case Sema::TDK_InstantiationDepth:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000447 case Sema::TDK_TooManyArguments:
448 case Sema::TDK_TooFewArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000449 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000450 return TemplateParameter();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000451
Douglas Gregora9333192010-05-08 17:41:32 +0000452 case Sema::TDK_Incomplete:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000453 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000454 return TemplateParameter::getFromOpaqueValue(Data);
Douglas Gregora9333192010-05-08 17:41:32 +0000455
456 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000457 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000458 return static_cast<DFIParamWithArguments*>(Data)->Param;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000459
Douglas Gregora9333192010-05-08 17:41:32 +0000460 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000461 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000462 case Sema::TDK_FailedOverloadResolution:
463 break;
464 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000465
Douglas Gregora9333192010-05-08 17:41:32 +0000466 return TemplateParameter();
467}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000468
Douglas Gregorec20f462010-05-08 20:07:26 +0000469TemplateArgumentList *
470OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
471 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
472 case Sema::TDK_Success:
473 case Sema::TDK_InstantiationDepth:
474 case Sema::TDK_TooManyArguments:
475 case Sema::TDK_TooFewArguments:
476 case Sema::TDK_Incomplete:
477 case Sema::TDK_InvalidExplicitArguments:
478 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000479 case Sema::TDK_Underqualified:
Douglas Gregorec20f462010-05-08 20:07:26 +0000480 return 0;
481
482 case Sema::TDK_SubstitutionFailure:
483 return static_cast<TemplateArgumentList*>(Data);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000484
Douglas Gregorec20f462010-05-08 20:07:26 +0000485 // Unhandled
486 case Sema::TDK_NonDeducedMismatch:
487 case Sema::TDK_FailedOverloadResolution:
488 break;
489 }
490
491 return 0;
492}
493
Douglas Gregora9333192010-05-08 17:41:32 +0000494const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
495 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
496 case Sema::TDK_Success:
497 case Sema::TDK_InstantiationDepth:
498 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000499 case Sema::TDK_TooManyArguments:
500 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000501 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000502 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000503 return 0;
504
Douglas Gregora9333192010-05-08 17:41:32 +0000505 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000506 case Sema::TDK_Underqualified:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000507 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
Douglas Gregora9333192010-05-08 17:41:32 +0000508
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000509 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000510 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000511 case Sema::TDK_FailedOverloadResolution:
512 break;
513 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000514
Douglas Gregora9333192010-05-08 17:41:32 +0000515 return 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000516}
Douglas Gregora9333192010-05-08 17:41:32 +0000517
518const TemplateArgument *
519OverloadCandidate::DeductionFailureInfo::getSecondArg() {
520 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
521 case Sema::TDK_Success:
522 case Sema::TDK_InstantiationDepth:
523 case Sema::TDK_Incomplete:
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000524 case Sema::TDK_TooManyArguments:
525 case Sema::TDK_TooFewArguments:
Douglas Gregorf1a84452010-05-08 19:15:54 +0000526 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregorec20f462010-05-08 20:07:26 +0000527 case Sema::TDK_SubstitutionFailure:
Douglas Gregora9333192010-05-08 17:41:32 +0000528 return 0;
529
Douglas Gregora9333192010-05-08 17:41:32 +0000530 case Sema::TDK_Inconsistent:
John McCall57e97782010-08-05 09:05:08 +0000531 case Sema::TDK_Underqualified:
Douglas Gregora9333192010-05-08 17:41:32 +0000532 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
533
Douglas Gregor0ca4c582010-05-08 18:20:53 +0000534 // Unhandled
Douglas Gregora9333192010-05-08 17:41:32 +0000535 case Sema::TDK_NonDeducedMismatch:
Douglas Gregora9333192010-05-08 17:41:32 +0000536 case Sema::TDK_FailedOverloadResolution:
537 break;
538 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000539
Douglas Gregora9333192010-05-08 17:41:32 +0000540 return 0;
541}
542
543void OverloadCandidateSet::clear() {
Douglas Gregora9333192010-05-08 17:41:32 +0000544 inherited::clear();
545 Functions.clear();
546}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000547
John McCall5acb0c92011-10-17 18:40:02 +0000548namespace {
549 class UnbridgedCastsSet {
550 struct Entry {
551 Expr **Addr;
552 Expr *Saved;
553 };
554 SmallVector<Entry, 2> Entries;
555
556 public:
557 void save(Sema &S, Expr *&E) {
558 assert(E->hasPlaceholderType(BuiltinType::ARCUnbridgedCast));
559 Entry entry = { &E, E };
560 Entries.push_back(entry);
561 E = S.stripARCUnbridgedCast(E);
562 }
563
564 void restore() {
565 for (SmallVectorImpl<Entry>::iterator
566 i = Entries.begin(), e = Entries.end(); i != e; ++i)
567 *i->Addr = i->Saved;
568 }
569 };
570}
571
572/// checkPlaceholderForOverload - Do any interesting placeholder-like
573/// preprocessing on the given expression.
574///
575/// \param unbridgedCasts a collection to which to add unbridged casts;
576/// without this, they will be immediately diagnosed as errors
577///
578/// Return true on unrecoverable error.
579static bool checkPlaceholderForOverload(Sema &S, Expr *&E,
580 UnbridgedCastsSet *unbridgedCasts = 0) {
John McCall5acb0c92011-10-17 18:40:02 +0000581 if (const BuiltinType *placeholder = E->getType()->getAsPlaceholderType()) {
582 // We can't handle overloaded expressions here because overload
583 // resolution might reasonably tweak them.
584 if (placeholder->getKind() == BuiltinType::Overload) return false;
585
586 // If the context potentially accepts unbridged ARC casts, strip
587 // the unbridged cast and add it to the collection for later restoration.
588 if (placeholder->getKind() == BuiltinType::ARCUnbridgedCast &&
589 unbridgedCasts) {
590 unbridgedCasts->save(S, E);
591 return false;
592 }
593
594 // Go ahead and check everything else.
595 ExprResult result = S.CheckPlaceholderExpr(E);
596 if (result.isInvalid())
597 return true;
598
599 E = result.take();
600 return false;
601 }
602
603 // Nothing to do.
604 return false;
605}
606
607/// checkArgPlaceholdersForOverload - Check a set of call operands for
608/// placeholders.
609static bool checkArgPlaceholdersForOverload(Sema &S, Expr **args,
610 unsigned numArgs,
611 UnbridgedCastsSet &unbridged) {
612 for (unsigned i = 0; i != numArgs; ++i)
613 if (checkPlaceholderForOverload(S, args[i], &unbridged))
614 return true;
615
616 return false;
617}
618
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000619// IsOverload - Determine whether the given New declaration is an
John McCall51fa86f2009-12-02 08:47:38 +0000620// overload of the declarations in Old. This routine returns false if
621// New and Old cannot be overloaded, e.g., if New has the same
622// signature as some function in Old (C++ 1.3.10) or if the Old
623// declarations aren't functions (or function templates) at all. When
John McCall871b2e72009-12-09 03:35:25 +0000624// it does return false, MatchedDecl will point to the decl that New
625// cannot be overloaded with. This decl may be a UsingShadowDecl on
626// top of the underlying declaration.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000627//
628// Example: Given the following input:
629//
630// void f(int, float); // #1
631// void f(int, int); // #2
632// int f(int, int); // #3
633//
634// When we process #1, there is no previous declaration of "f",
Mike Stump1eb44332009-09-09 15:08:12 +0000635// so IsOverload will not be used.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000636//
John McCall51fa86f2009-12-02 08:47:38 +0000637// When we process #2, Old contains only the FunctionDecl for #1. By
638// comparing the parameter types, we see that #1 and #2 are overloaded
639// (since they have different signatures), so this routine returns
640// false; MatchedDecl is unchanged.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000641//
John McCall51fa86f2009-12-02 08:47:38 +0000642// When we process #3, Old is an overload set containing #1 and #2. We
643// compare the signatures of #3 to #1 (they're overloaded, so we do
644// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
645// identical (return types of functions are not part of the
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000646// signature), IsOverload returns false and MatchedDecl will be set to
647// point to the FunctionDecl for #2.
John McCallad00b772010-06-16 08:42:20 +0000648//
649// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
650// into a class by a using declaration. The rules for whether to hide
651// shadow declarations ignore some properties which otherwise figure
652// into a function template's signature.
John McCall871b2e72009-12-09 03:35:25 +0000653Sema::OverloadKind
John McCallad00b772010-06-16 08:42:20 +0000654Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
655 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall51fa86f2009-12-02 08:47:38 +0000656 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall68263142009-11-18 22:49:29 +0000657 I != E; ++I) {
John McCallad00b772010-06-16 08:42:20 +0000658 NamedDecl *OldD = *I;
659
660 bool OldIsUsingDecl = false;
661 if (isa<UsingShadowDecl>(OldD)) {
662 OldIsUsingDecl = true;
663
664 // We can always introduce two using declarations into the same
665 // context, even if they have identical signatures.
666 if (NewIsUsingDecl) continue;
667
668 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
669 }
670
671 // If either declaration was introduced by a using declaration,
672 // we'll need to use slightly different rules for matching.
673 // Essentially, these rules are the normal rules, except that
674 // function templates hide function templates with different
675 // return types or template parameter lists.
676 bool UseMemberUsingDeclRules =
677 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
678
John McCall51fa86f2009-12-02 08:47:38 +0000679 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000680 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
681 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
682 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
683 continue;
684 }
685
John McCall871b2e72009-12-09 03:35:25 +0000686 Match = *I;
687 return Ovl_Match;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000688 }
John McCall51fa86f2009-12-02 08:47:38 +0000689 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCallad00b772010-06-16 08:42:20 +0000690 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
691 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
692 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
693 continue;
694 }
695
John McCall871b2e72009-12-09 03:35:25 +0000696 Match = *I;
697 return Ovl_Match;
John McCall68263142009-11-18 22:49:29 +0000698 }
John McCalld7945c62010-11-10 03:01:53 +0000699 } else if (isa<UsingDecl>(OldD)) {
John McCall9f54ad42009-12-10 09:41:52 +0000700 // We can overload with these, which can show up when doing
701 // redeclaration checks for UsingDecls.
702 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalld7945c62010-11-10 03:01:53 +0000703 } else if (isa<TagDecl>(OldD)) {
704 // We can always overload with tags by hiding them.
John McCall9f54ad42009-12-10 09:41:52 +0000705 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
706 // Optimistically assume that an unresolved using decl will
707 // overload; if it doesn't, we'll have to diagnose during
708 // template instantiation.
709 } else {
John McCall68263142009-11-18 22:49:29 +0000710 // (C++ 13p1):
711 // Only function declarations can be overloaded; object and type
712 // declarations cannot be overloaded.
John McCall871b2e72009-12-09 03:35:25 +0000713 Match = *I;
714 return Ovl_NonFunction;
John McCall68263142009-11-18 22:49:29 +0000715 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000716 }
John McCall68263142009-11-18 22:49:29 +0000717
John McCall871b2e72009-12-09 03:35:25 +0000718 return Ovl_Overload;
John McCall68263142009-11-18 22:49:29 +0000719}
720
John McCallad00b772010-06-16 08:42:20 +0000721bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
722 bool UseUsingDeclRules) {
John McCall7b492022010-08-12 07:09:11 +0000723 // If both of the functions are extern "C", then they are not
724 // overloads.
725 if (Old->isExternC() && New->isExternC())
726 return false;
727
John McCall68263142009-11-18 22:49:29 +0000728 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
729 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
730
731 // C++ [temp.fct]p2:
732 // A function template can be overloaded with other function templates
733 // and with normal (non-template) functions.
734 if ((OldTemplate == 0) != (NewTemplate == 0))
735 return true;
736
737 // Is the function New an overload of the function Old?
738 QualType OldQType = Context.getCanonicalType(Old->getType());
739 QualType NewQType = Context.getCanonicalType(New->getType());
740
741 // Compare the signatures (C++ 1.3.10) of the two functions to
742 // determine whether they are overloads. If we find any mismatch
743 // in the signature, they are overloads.
744
745 // If either of these functions is a K&R-style function (no
746 // prototype), then we consider them to have matching signatures.
747 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
748 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
749 return false;
750
John McCallf4c73712011-01-19 06:33:43 +0000751 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
752 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall68263142009-11-18 22:49:29 +0000753
754 // The signature of a function includes the types of its
755 // parameters (C++ 1.3.10), which includes the presence or absence
756 // of the ellipsis; see C++ DR 357).
757 if (OldQType != NewQType &&
758 (OldType->getNumArgs() != NewType->getNumArgs() ||
759 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahaniand8d34412010-05-03 21:06:18 +0000760 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall68263142009-11-18 22:49:29 +0000761 return true;
762
763 // C++ [temp.over.link]p4:
764 // The signature of a function template consists of its function
765 // signature, its return type and its template parameter list. The names
766 // of the template parameters are significant only for establishing the
767 // relationship between the template parameters and the rest of the
768 // signature.
769 //
770 // We check the return type and template parameter lists for function
771 // templates first; the remaining checks follow.
John McCallad00b772010-06-16 08:42:20 +0000772 //
773 // However, we don't consider either of these when deciding whether
774 // a member introduced by a shadow declaration is hidden.
775 if (!UseUsingDeclRules && NewTemplate &&
John McCall68263142009-11-18 22:49:29 +0000776 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
777 OldTemplate->getTemplateParameters(),
778 false, TPL_TemplateMatch) ||
779 OldType->getResultType() != NewType->getResultType()))
780 return true;
781
782 // If the function is a class member, its signature includes the
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000783 // cv-qualifiers (if any) and ref-qualifier (if any) on the function itself.
John McCall68263142009-11-18 22:49:29 +0000784 //
785 // As part of this, also check whether one of the member functions
786 // is static, in which case they are not overloads (C++
787 // 13.1p2). While not part of the definition of the signature,
788 // this check is important to determine whether these functions
789 // can be overloaded.
790 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
791 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
792 if (OldMethod && NewMethod &&
793 !OldMethod->isStatic() && !NewMethod->isStatic() &&
Douglas Gregor57c9f4f2011-01-26 17:47:49 +0000794 (OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers() ||
Douglas Gregorb145ee62011-01-26 21:20:37 +0000795 OldMethod->getRefQualifier() != NewMethod->getRefQualifier())) {
796 if (!UseUsingDeclRules &&
797 OldMethod->getRefQualifier() != NewMethod->getRefQualifier() &&
798 (OldMethod->getRefQualifier() == RQ_None ||
799 NewMethod->getRefQualifier() == RQ_None)) {
800 // C++0x [over.load]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000801 // - Member function declarations with the same name and the same
802 // parameter-type-list as well as member function template
803 // declarations with the same name, the same parameter-type-list, and
804 // the same template parameter lists cannot be overloaded if any of
Douglas Gregorb145ee62011-01-26 21:20:37 +0000805 // them, but not all, have a ref-qualifier (8.3.5).
806 Diag(NewMethod->getLocation(), diag::err_ref_qualifier_overload)
807 << NewMethod->getRefQualifier() << OldMethod->getRefQualifier();
808 Diag(OldMethod->getLocation(), diag::note_previous_declaration);
809 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000810
John McCall68263142009-11-18 22:49:29 +0000811 return true;
Douglas Gregorb145ee62011-01-26 21:20:37 +0000812 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000813
John McCall68263142009-11-18 22:49:29 +0000814 // The signatures match; this is not an overload.
815 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000816}
817
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +0000818/// \brief Checks availability of the function depending on the current
819/// function context. Inside an unavailable function, unavailability is ignored.
820///
821/// \returns true if \arg FD is unavailable and current context is inside
822/// an available function, false otherwise.
823bool Sema::isFunctionConsideredUnavailable(FunctionDecl *FD) {
824 return FD->isUnavailable() && !cast<Decl>(CurContext)->isUnavailable();
825}
826
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000827/// TryImplicitConversion - Attempt to perform an implicit conversion
828/// from the given expression (Expr) to the given type (ToType). This
829/// function returns an implicit conversion sequence that can be used
830/// to perform the initialization. Given
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000831///
832/// void f(float f);
833/// void g(int i) { f(i); }
834///
835/// this routine would produce an implicit conversion sequence to
836/// describe the initialization of f from i, which will be a standard
837/// conversion sequence containing an lvalue-to-rvalue conversion (C++
838/// 4.1) followed by a floating-integral conversion (C++ 4.9).
839//
840/// Note that this routine only determines how the conversion can be
841/// performed; it does not actually perform the conversion. As such,
842/// it will not produce any diagnostics if no conversion is available,
843/// but will instead return an implicit conversion sequence of kind
844/// "BadConversion".
Douglas Gregor225c41e2008-11-03 19:09:14 +0000845///
846/// If @p SuppressUserConversions, then user-defined conversions are
847/// not permitted.
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000848/// If @p AllowExplicit, then explicit user-defined conversions are
849/// permitted.
John McCallf85e1932011-06-15 23:02:42 +0000850///
851/// \param AllowObjCWritebackConversion Whether we allow the Objective-C
852/// writeback conversion, which allows __autoreleasing id* parameters to
853/// be initialized with __strong id* or __weak id* arguments.
John McCall120d63c2010-08-24 20:38:10 +0000854static ImplicitConversionSequence
855TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
856 bool SuppressUserConversions,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000857 bool AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +0000858 bool InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +0000859 bool CStyle,
860 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000861 ImplicitConversionSequence ICS;
John McCall120d63c2010-08-24 20:38:10 +0000862 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +0000863 ICS.Standard, CStyle, AllowObjCWritebackConversion)){
John McCall1d318332010-01-12 00:44:57 +0000864 ICS.setStandard();
John McCall5769d612010-02-08 23:07:23 +0000865 return ICS;
866 }
867
John McCall120d63c2010-08-24 20:38:10 +0000868 if (!S.getLangOptions().CPlusPlus) {
John McCallb1bdc622010-02-25 01:37:24 +0000869 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCall5769d612010-02-08 23:07:23 +0000870 return ICS;
871 }
872
Douglas Gregor604eb652010-08-11 02:15:33 +0000873 // C++ [over.ics.user]p4:
874 // A conversion of an expression of class type to the same class
875 // type is given Exact Match rank, and a conversion of an
876 // expression of class type to a base class of that type is
877 // given Conversion rank, in spite of the fact that a copy/move
878 // constructor (i.e., a user-defined conversion function) is
879 // called for those cases.
880 QualType FromType = From->getType();
881 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +0000882 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
883 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000884 ICS.setStandard();
885 ICS.Standard.setAsIdentityConversion();
886 ICS.Standard.setFromType(FromType);
887 ICS.Standard.setAllToTypes(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000888
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000889 // We don't actually check at this point whether there is a valid
890 // copy/move constructor, since overloading just assumes that it
891 // exists. When we actually perform initialization, we'll find the
892 // appropriate constructor to copy the returned object, if needed.
893 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000894
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000895 // Determine whether this is considered a derived-to-base conversion.
John McCall120d63c2010-08-24 20:38:10 +0000896 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000897 ICS.Standard.Second = ICK_Derived_To_Base;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000898
Douglas Gregor604eb652010-08-11 02:15:33 +0000899 return ICS;
900 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +0000901
Douglas Gregor604eb652010-08-11 02:15:33 +0000902 if (SuppressUserConversions) {
903 // We're not in the case above, so there is no conversion that
904 // we can perform.
905 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000906 return ICS;
907 }
908
909 // Attempt user-defined conversion.
John McCall5769d612010-02-08 23:07:23 +0000910 OverloadCandidateSet Conversions(From->getExprLoc());
911 OverloadingResult UserDefResult
John McCall120d63c2010-08-24 20:38:10 +0000912 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +0000913 AllowExplicit);
John McCall5769d612010-02-08 23:07:23 +0000914
915 if (UserDefResult == OR_Success) {
John McCall1d318332010-01-12 00:44:57 +0000916 ICS.setUserDefined();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000917 // C++ [over.ics.user]p4:
918 // A conversion of an expression of class type to the same class
919 // type is given Exact Match rank, and a conversion of an
920 // expression of class type to a base class of that type is
921 // given Conversion rank, in spite of the fact that a copy
922 // constructor (i.e., a user-defined conversion function) is
923 // called for those cases.
Mike Stump1eb44332009-09-09 15:08:12 +0000924 if (CXXConstructorDecl *Constructor
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000925 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000926 QualType FromCanon
John McCall120d63c2010-08-24 20:38:10 +0000927 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
928 QualType ToCanon
929 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor9e9199d2009-12-22 00:34:07 +0000930 if (Constructor->isCopyConstructor() &&
John McCall120d63c2010-08-24 20:38:10 +0000931 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor225c41e2008-11-03 19:09:14 +0000932 // Turn this into a "standard" conversion sequence, so that it
933 // gets ranked with standard conversion sequences.
John McCall1d318332010-01-12 00:44:57 +0000934 ICS.setStandard();
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000935 ICS.Standard.setAsIdentityConversion();
John McCall1d318332010-01-12 00:44:57 +0000936 ICS.Standard.setFromType(From->getType());
Douglas Gregorad323a82010-01-27 03:51:04 +0000937 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor225c41e2008-11-03 19:09:14 +0000938 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregor2b1e0032009-02-02 22:11:10 +0000939 if (ToCanon != FromCanon)
Douglas Gregor396b7cd2008-11-03 17:51:48 +0000940 ICS.Standard.Second = ICK_Derived_To_Base;
941 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000942 }
Douglas Gregor734d9862009-01-30 23:27:23 +0000943
944 // C++ [over.best.ics]p4:
945 // However, when considering the argument of a user-defined
946 // conversion function that is a candidate by 13.3.1.3 when
947 // invoked for the copying of the temporary in the second step
948 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
949 // 13.3.1.6 in all cases, only standard conversion sequences and
950 // ellipsis conversion sequences are allowed.
John McCalladbb8f82010-01-13 09:16:55 +0000951 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCallb1bdc622010-02-25 01:37:24 +0000952 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCalladbb8f82010-01-13 09:16:55 +0000953 }
John McCallcefd3ad2010-01-13 22:30:33 +0000954 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall1d318332010-01-12 00:44:57 +0000955 ICS.setAmbiguous();
956 ICS.Ambiguous.setFromType(From->getType());
957 ICS.Ambiguous.setToType(ToType);
958 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
959 Cand != Conversions.end(); ++Cand)
960 if (Cand->Viable)
961 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000962 } else {
John McCallb1bdc622010-02-25 01:37:24 +0000963 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanianb1663d02009-09-23 00:58:07 +0000964 }
Douglas Gregor60d62c22008-10-31 16:23:19 +0000965
966 return ICS;
967}
968
John McCallf85e1932011-06-15 23:02:42 +0000969ImplicitConversionSequence
970Sema::TryImplicitConversion(Expr *From, QualType ToType,
971 bool SuppressUserConversions,
972 bool AllowExplicit,
973 bool InOverloadResolution,
974 bool CStyle,
975 bool AllowObjCWritebackConversion) {
976 return clang::TryImplicitConversion(*this, From, ToType,
977 SuppressUserConversions, AllowExplicit,
978 InOverloadResolution, CStyle,
979 AllowObjCWritebackConversion);
John McCall120d63c2010-08-24 20:38:10 +0000980}
981
Douglas Gregor575c63a2010-04-16 22:27:05 +0000982/// PerformImplicitConversion - Perform an implicit conversion of the
John Wiegley429bb272011-04-08 18:41:53 +0000983/// expression From to the type ToType. Returns the
Douglas Gregor575c63a2010-04-16 22:27:05 +0000984/// converted expression. Flavor is the kind of conversion we're
985/// performing, used in the error message. If @p AllowExplicit,
986/// explicit user-defined conversions are permitted.
John Wiegley429bb272011-04-08 18:41:53 +0000987ExprResult
988Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Sebastian Redl091fffe2011-10-16 18:19:06 +0000989 AssignmentAction Action, bool AllowExplicit) {
Douglas Gregor575c63a2010-04-16 22:27:05 +0000990 ImplicitConversionSequence ICS;
Sebastian Redl091fffe2011-10-16 18:19:06 +0000991 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
Douglas Gregor575c63a2010-04-16 22:27:05 +0000992}
993
John Wiegley429bb272011-04-08 18:41:53 +0000994ExprResult
995Sema::PerformImplicitConversion(Expr *From, QualType ToType,
Douglas Gregor575c63a2010-04-16 22:27:05 +0000996 AssignmentAction Action, bool AllowExplicit,
Sebastian Redl091fffe2011-10-16 18:19:06 +0000997 ImplicitConversionSequence& ICS) {
John McCall3c3b7f92011-10-25 17:37:35 +0000998 if (checkPlaceholderForOverload(*this, From))
999 return ExprError();
1000
John McCallf85e1932011-06-15 23:02:42 +00001001 // Objective-C ARC: Determine whether we will allow the writeback conversion.
1002 bool AllowObjCWritebackConversion
1003 = getLangOptions().ObjCAutoRefCount &&
1004 (Action == AA_Passing || Action == AA_Sending);
John McCallf85e1932011-06-15 23:02:42 +00001005
John McCall120d63c2010-08-24 20:38:10 +00001006 ICS = clang::TryImplicitConversion(*this, From, ToType,
1007 /*SuppressUserConversions=*/false,
1008 AllowExplicit,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001009 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00001010 /*CStyle=*/false,
1011 AllowObjCWritebackConversion);
Douglas Gregor575c63a2010-04-16 22:27:05 +00001012 return PerformImplicitConversion(From, ToType, ICS, Action);
1013}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001014
1015/// \brief Determine whether the conversion from FromType to ToType is a valid
Douglas Gregor43c79c22009-12-09 00:47:37 +00001016/// conversion that strips "noreturn" off the nested function type.
Chandler Carruth18e04612011-06-18 01:19:03 +00001017bool Sema::IsNoReturnConversion(QualType FromType, QualType ToType,
1018 QualType &ResultTy) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001019 if (Context.hasSameUnqualifiedType(FromType, ToType))
1020 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001021
John McCall00ccbef2010-12-21 00:44:39 +00001022 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
1023 // where F adds one of the following at most once:
1024 // - a pointer
1025 // - a member pointer
1026 // - a block pointer
1027 CanQualType CanTo = Context.getCanonicalType(ToType);
1028 CanQualType CanFrom = Context.getCanonicalType(FromType);
1029 Type::TypeClass TyClass = CanTo->getTypeClass();
1030 if (TyClass != CanFrom->getTypeClass()) return false;
1031 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
1032 if (TyClass == Type::Pointer) {
1033 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
1034 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
1035 } else if (TyClass == Type::BlockPointer) {
1036 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
1037 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
1038 } else if (TyClass == Type::MemberPointer) {
1039 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
1040 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
1041 } else {
1042 return false;
1043 }
Douglas Gregor43c79c22009-12-09 00:47:37 +00001044
John McCall00ccbef2010-12-21 00:44:39 +00001045 TyClass = CanTo->getTypeClass();
1046 if (TyClass != CanFrom->getTypeClass()) return false;
1047 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
1048 return false;
1049 }
1050
1051 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
1052 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
1053 if (!EInfo.getNoReturn()) return false;
1054
1055 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
1056 assert(QualType(FromFn, 0).isCanonical());
1057 if (QualType(FromFn, 0) != CanTo) return false;
1058
1059 ResultTy = ToType;
Douglas Gregor43c79c22009-12-09 00:47:37 +00001060 return true;
1061}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001062
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001063/// \brief Determine whether the conversion from FromType to ToType is a valid
1064/// vector conversion.
1065///
1066/// \param ICK Will be set to the vector conversion kind, if this is a vector
1067/// conversion.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001068static bool IsVectorConversion(ASTContext &Context, QualType FromType,
1069 QualType ToType, ImplicitConversionKind &ICK) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001070 // We need at least one of these types to be a vector type to have a vector
1071 // conversion.
1072 if (!ToType->isVectorType() && !FromType->isVectorType())
1073 return false;
1074
1075 // Identical types require no conversions.
1076 if (Context.hasSameUnqualifiedType(FromType, ToType))
1077 return false;
1078
1079 // There are no conversions between extended vector types, only identity.
1080 if (ToType->isExtVectorType()) {
1081 // There are no conversions between extended vector types other than the
1082 // identity conversion.
1083 if (FromType->isExtVectorType())
1084 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001085
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001086 // Vector splat from any arithmetic type to a vector.
Douglas Gregor00619622010-06-22 23:41:02 +00001087 if (FromType->isArithmeticType()) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001088 ICK = ICK_Vector_Splat;
1089 return true;
1090 }
1091 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001092
1093 // We can perform the conversion between vector types in the following cases:
1094 // 1)vector types are equivalent AltiVec and GCC vector types
1095 // 2)lax vector conversions are permitted and the vector types are of the
1096 // same size
1097 if (ToType->isVectorType() && FromType->isVectorType()) {
1098 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruthc45eb9c2010-08-08 05:02:51 +00001099 (Context.getLangOptions().LaxVectorConversions &&
1100 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor255210e2010-08-06 10:14:59 +00001101 ICK = ICK_Vector_Conversion;
1102 return true;
1103 }
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001104 }
Douglas Gregor255210e2010-08-06 10:14:59 +00001105
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001106 return false;
1107}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001108
Douglas Gregor60d62c22008-10-31 16:23:19 +00001109/// IsStandardConversion - Determines whether there is a standard
1110/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
1111/// expression From to the type ToType. Standard conversion sequences
1112/// only consider non-class types; for conversions that involve class
1113/// types, use TryImplicitConversion. If a conversion exists, SCS will
1114/// contain the standard conversion sequence required to perform this
1115/// conversion and this routine will return true. Otherwise, this
1116/// routine will return false and the value of SCS is unspecified.
John McCall120d63c2010-08-24 20:38:10 +00001117static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
1118 bool InOverloadResolution,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00001119 StandardConversionSequence &SCS,
John McCallf85e1932011-06-15 23:02:42 +00001120 bool CStyle,
1121 bool AllowObjCWritebackConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001122 QualType FromType = From->getType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001123
Douglas Gregor60d62c22008-10-31 16:23:19 +00001124 // Standard conversions (C++ [conv])
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001125 SCS.setAsIdentityConversion();
Douglas Gregora9bff302010-02-28 18:30:25 +00001126 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor45920e82008-12-19 17:40:08 +00001127 SCS.IncompatibleObjC = false;
John McCall1d318332010-01-12 00:44:57 +00001128 SCS.setFromType(FromType);
Douglas Gregor225c41e2008-11-03 19:09:14 +00001129 SCS.CopyConstructor = 0;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001130
Douglas Gregorf9201e02009-02-11 23:02:49 +00001131 // There are no standard conversions for class types in C++, so
Mike Stump1eb44332009-09-09 15:08:12 +00001132 // abort early. When overloading in C, however, we do permit
Douglas Gregorf9201e02009-02-11 23:02:49 +00001133 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall120d63c2010-08-24 20:38:10 +00001134 if (S.getLangOptions().CPlusPlus)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001135 return false;
1136
Mike Stump1eb44332009-09-09 15:08:12 +00001137 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001138 }
1139
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001140 // The first conversion can be an lvalue-to-rvalue conversion,
1141 // array-to-pointer conversion, or function-to-pointer conversion
1142 // (C++ 4p1).
1143
John McCall120d63c2010-08-24 20:38:10 +00001144 if (FromType == S.Context.OverloadTy) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001145 DeclAccessPair AccessPair;
1146 if (FunctionDecl *Fn
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001147 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
John McCall120d63c2010-08-24 20:38:10 +00001148 AccessPair)) {
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001149 // We were able to resolve the address of the overloaded function,
1150 // so we can convert to the type of that function.
1151 FromType = Fn->getType();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001152
1153 // we can sometimes resolve &foo<int> regardless of ToType, so check
1154 // if the type matches (identity) or we are converting to bool
1155 if (!S.Context.hasSameUnqualifiedType(
1156 S.ExtractUnqualifiedFunctionType(ToType), FromType)) {
1157 QualType resultTy;
1158 // if the function type matches except for [[noreturn]], it's ok
Chandler Carruth18e04612011-06-18 01:19:03 +00001159 if (!S.IsNoReturnConversion(FromType,
Douglas Gregor1be8eec2011-02-19 21:32:49 +00001160 S.ExtractUnqualifiedFunctionType(ToType), resultTy))
1161 // otherwise, only a boolean conversion is standard
1162 if (!ToType->isBooleanType())
1163 return false;
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001164 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001165
Chandler Carruth90434232011-03-29 08:08:18 +00001166 // Check if the "from" expression is taking the address of an overloaded
1167 // function and recompute the FromType accordingly. Take advantage of the
1168 // fact that non-static member functions *must* have such an address-of
1169 // expression.
1170 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn);
1171 if (Method && !Method->isStatic()) {
1172 assert(isa<UnaryOperator>(From->IgnoreParens()) &&
1173 "Non-unary operator on non-static member address");
1174 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode()
1175 == UO_AddrOf &&
1176 "Non-address-of operator on non-static member address");
1177 const Type *ClassType
1178 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1179 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Chandler Carruthfc5c8fc2011-03-29 18:38:10 +00001180 } else if (isa<UnaryOperator>(From->IgnoreParens())) {
1181 assert(cast<UnaryOperator>(From->IgnoreParens())->getOpcode() ==
1182 UO_AddrOf &&
Chandler Carruth90434232011-03-29 08:08:18 +00001183 "Non-address-of operator for overloaded function expression");
1184 FromType = S.Context.getPointerType(FromType);
1185 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001186
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001187 // Check that we've computed the proper type after overload resolution.
Chandler Carruth90434232011-03-29 08:08:18 +00001188 assert(S.Context.hasSameType(
1189 FromType,
1190 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregorad4e02f2010-04-29 18:24:40 +00001191 } else {
1192 return false;
1193 }
Anders Carlsson2bd62502010-11-04 05:28:09 +00001194 }
John McCall21480112011-08-30 00:57:29 +00001195 // Lvalue-to-rvalue conversion (C++11 4.1):
1196 // A glvalue (3.10) of a non-function, non-array type T can
1197 // be converted to a prvalue.
1198 bool argIsLValue = From->isGLValue();
John McCall7eb0a9e2010-11-24 05:12:34 +00001199 if (argIsLValue &&
Douglas Gregor904eed32008-11-10 20:40:00 +00001200 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall120d63c2010-08-24 20:38:10 +00001201 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001202 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001203
1204 // If T is a non-class type, the type of the rvalue is the
1205 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregorf9201e02009-02-11 23:02:49 +00001206 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1207 // just strip the qualifiers because they don't matter.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001208 FromType = FromType.getUnqualifiedType();
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001209 } else if (FromType->isArrayType()) {
1210 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001211 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001212
1213 // An lvalue or rvalue of type "array of N T" or "array of unknown
1214 // bound of T" can be converted to an rvalue of type "pointer to
1215 // T" (C++ 4.2p1).
John McCall120d63c2010-08-24 20:38:10 +00001216 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001217
John McCall120d63c2010-08-24 20:38:10 +00001218 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001219 // This conversion is deprecated. (C++ D.4).
Douglas Gregora9bff302010-02-28 18:30:25 +00001220 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001221
1222 // For the purpose of ranking in overload resolution
1223 // (13.3.3.1.1), this conversion is considered an
1224 // array-to-pointer conversion followed by a qualification
1225 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001226 SCS.Second = ICK_Identity;
1227 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001228 SCS.QualificationIncludesObjCLifetime = false;
Douglas Gregorad323a82010-01-27 03:51:04 +00001229 SCS.setAllToTypes(FromType);
Douglas Gregor60d62c22008-10-31 16:23:19 +00001230 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001231 }
John McCall7eb0a9e2010-11-24 05:12:34 +00001232 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001233 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001234 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001235
1236 // An lvalue of function type T can be converted to an rvalue of
1237 // type "pointer to T." The result is a pointer to the
1238 // function. (C++ 4.3p1).
John McCall120d63c2010-08-24 20:38:10 +00001239 FromType = S.Context.getPointerType(FromType);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001240 } else {
1241 // We don't require any conversions for the first step.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001242 SCS.First = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001243 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001244 SCS.setToType(0, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001245
1246 // The second conversion can be an integral promotion, floating
1247 // point promotion, integral conversion, floating point conversion,
1248 // floating-integral conversion, pointer conversion,
1249 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregorf9201e02009-02-11 23:02:49 +00001250 // For overloading in C, this can also be a "compatible-type"
1251 // conversion.
Douglas Gregor45920e82008-12-19 17:40:08 +00001252 bool IncompatibleObjC = false;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001253 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001254 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001255 // The unqualified versions of the types are the same: there's no
1256 // conversion to do.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001257 SCS.Second = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00001258 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001259 // Integral promotion (C++ 4.5).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001260 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001261 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001262 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001263 // Floating point promotion (C++ 4.6).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001264 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001265 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001266 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001267 // Complex promotion (Clang extension)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001268 SCS.Second = ICK_Complex_Promotion;
1269 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001270 } else if (ToType->isBooleanType() &&
1271 (FromType->isArithmeticType() ||
1272 FromType->isAnyPointerType() ||
1273 FromType->isBlockPointerType() ||
1274 FromType->isMemberPointerType() ||
1275 FromType->isNullPtrType())) {
1276 // Boolean conversions (C++ 4.12).
1277 SCS.Second = ICK_Boolean_Conversion;
1278 FromType = S.Context.BoolTy;
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001279 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall120d63c2010-08-24 20:38:10 +00001280 ToType->isIntegralType(S.Context)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001281 // Integral conversions (C++ 4.7).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001282 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001283 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001284 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001285 // Complex conversions (C99 6.3.1.6)
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001286 SCS.Second = ICK_Complex_Conversion;
1287 FromType = ToType.getUnqualifiedType();
John McCalldaa8e4e2010-11-15 09:13:47 +00001288 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1289 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001290 // Complex-real conversions (C99 6.3.1.7)
1291 SCS.Second = ICK_Complex_Real;
1292 FromType = ToType.getUnqualifiedType();
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001293 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth23a370f2010-02-25 07:20:54 +00001294 // Floating point conversions (C++ 4.8).
1295 SCS.Second = ICK_Floating_Conversion;
1296 FromType = ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001297 } else if ((FromType->isRealFloatingType() &&
John McCalldaa8e4e2010-11-15 09:13:47 +00001298 ToType->isIntegralType(S.Context)) ||
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001299 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor0c293ea2010-06-22 23:07:26 +00001300 ToType->isRealFloatingType())) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001301 // Floating-integral conversions (C++ 4.9).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001302 SCS.Second = ICK_Floating_Integral;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001303 FromType = ToType.getUnqualifiedType();
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00001304 } else if (S.IsBlockPointerConversion(FromType, ToType, FromType)) {
John McCallf85e1932011-06-15 23:02:42 +00001305 SCS.Second = ICK_Block_Pointer_Conversion;
1306 } else if (AllowObjCWritebackConversion &&
1307 S.isObjCWritebackConversion(FromType, ToType, FromType)) {
1308 SCS.Second = ICK_Writeback_Conversion;
John McCall120d63c2010-08-24 20:38:10 +00001309 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1310 FromType, IncompatibleObjC)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001311 // Pointer conversions (C++ 4.10).
Douglas Gregor60d62c22008-10-31 16:23:19 +00001312 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor45920e82008-12-19 17:40:08 +00001313 SCS.IncompatibleObjC = IncompatibleObjC;
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001314 FromType = FromType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001315 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
John McCall120d63c2010-08-24 20:38:10 +00001316 InOverloadResolution, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001317 // Pointer to member conversions (4.11).
Sebastian Redl4433aaf2009-01-25 19:43:20 +00001318 SCS.Second = ICK_Pointer_Member;
John McCall120d63c2010-08-24 20:38:10 +00001319 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001320 SCS.Second = SecondICK;
1321 FromType = ToType.getUnqualifiedType();
John McCall120d63c2010-08-24 20:38:10 +00001322 } else if (!S.getLangOptions().CPlusPlus &&
1323 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001324 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregorf9201e02009-02-11 23:02:49 +00001325 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregorfb4a5432010-05-18 22:42:18 +00001326 FromType = ToType.getUnqualifiedType();
Chandler Carruth18e04612011-06-18 01:19:03 +00001327 } else if (S.IsNoReturnConversion(FromType, ToType, FromType)) {
Douglas Gregor43c79c22009-12-09 00:47:37 +00001328 // Treat a conversion that strips "noreturn" as an identity conversion.
1329 SCS.Second = ICK_NoReturn_Adjustment;
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001330 } else if (IsTransparentUnionStandardConversion(S, From, ToType,
1331 InOverloadResolution,
1332 SCS, CStyle)) {
1333 SCS.Second = ICK_TransparentUnionConversion;
1334 FromType = ToType;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001335 } else {
1336 // No second conversion required.
Douglas Gregor60d62c22008-10-31 16:23:19 +00001337 SCS.Second = ICK_Identity;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001338 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001339 SCS.setToType(1, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001340
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001341 QualType CanonFrom;
1342 QualType CanonTo;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001343 // The third conversion can be a qualification conversion (C++ 4p1).
John McCallf85e1932011-06-15 23:02:42 +00001344 bool ObjCLifetimeConversion;
1345 if (S.IsQualificationConversion(FromType, ToType, CStyle,
1346 ObjCLifetimeConversion)) {
Douglas Gregor60d62c22008-10-31 16:23:19 +00001347 SCS.Third = ICK_Qualification;
John McCallf85e1932011-06-15 23:02:42 +00001348 SCS.QualificationIncludesObjCLifetime = ObjCLifetimeConversion;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001349 FromType = ToType;
John McCall120d63c2010-08-24 20:38:10 +00001350 CanonFrom = S.Context.getCanonicalType(FromType);
1351 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001352 } else {
1353 // No conversion required
Douglas Gregor60d62c22008-10-31 16:23:19 +00001354 SCS.Third = ICK_Identity;
1355
Mike Stump1eb44332009-09-09 15:08:12 +00001356 // C++ [over.best.ics]p6:
Douglas Gregor60d62c22008-10-31 16:23:19 +00001357 // [...] Any difference in top-level cv-qualification is
1358 // subsumed by the initialization itself and does not constitute
1359 // a conversion. [...]
John McCall120d63c2010-08-24 20:38:10 +00001360 CanonFrom = S.Context.getCanonicalType(FromType);
1361 CanonTo = S.Context.getCanonicalType(ToType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001362 if (CanonFrom.getLocalUnqualifiedType()
Douglas Gregora4923eb2009-11-16 21:35:15 +00001363 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian62ac5d02010-05-18 23:04:17 +00001364 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
John McCallf85e1932011-06-15 23:02:42 +00001365 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr()
1366 || CanonFrom.getObjCLifetime() != CanonTo.getObjCLifetime())) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001367 FromType = ToType;
1368 CanonFrom = CanonTo;
1369 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001370 }
Douglas Gregorad323a82010-01-27 03:51:04 +00001371 SCS.setToType(2, FromType);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001372
1373 // If we have not converted the argument type to the parameter type,
1374 // this is a bad conversion sequence.
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001375 if (CanonFrom != CanonTo)
Douglas Gregor60d62c22008-10-31 16:23:19 +00001376 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001377
Douglas Gregor60d62c22008-10-31 16:23:19 +00001378 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001379}
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001380
1381static bool
1382IsTransparentUnionStandardConversion(Sema &S, Expr* From,
1383 QualType &ToType,
1384 bool InOverloadResolution,
1385 StandardConversionSequence &SCS,
1386 bool CStyle) {
1387
1388 const RecordType *UT = ToType->getAsUnionType();
1389 if (!UT || !UT->getDecl()->hasAttr<TransparentUnionAttr>())
1390 return false;
1391 // The field to initialize within the transparent union.
1392 RecordDecl *UD = UT->getDecl();
1393 // It's compatible if the expression matches any of the fields.
1394 for (RecordDecl::field_iterator it = UD->field_begin(),
1395 itend = UD->field_end();
1396 it != itend; ++it) {
John McCallf85e1932011-06-15 23:02:42 +00001397 if (IsStandardConversion(S, From, it->getType(), InOverloadResolution, SCS,
1398 CStyle, /*ObjCWritebackConversion=*/false)) {
Fariborz Jahaniand97f5582011-03-23 19:50:54 +00001399 ToType = it->getType();
1400 return true;
1401 }
1402 }
1403 return false;
1404}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001405
1406/// IsIntegralPromotion - Determines whether the conversion from the
1407/// expression From (whose potentially-adjusted type is FromType) to
1408/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1409/// sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001410bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001411 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlf7be9442008-11-04 15:59:10 +00001412 // All integers are built-in.
Sebastian Redl07779722008-10-31 14:43:28 +00001413 if (!To) {
1414 return false;
1415 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001416
1417 // An rvalue of type char, signed char, unsigned char, short int, or
1418 // unsigned short int can be converted to an rvalue of type int if
1419 // int can represent all the values of the source type; otherwise,
1420 // the source rvalue can be converted to an rvalue of type unsigned
1421 // int (C++ 4.5p1).
Douglas Gregoraa74a1e2010-02-02 20:10:50 +00001422 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1423 !FromType->isEnumeralType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001424 if (// We can promote any signed, promotable integer type to an int
1425 (FromType->isSignedIntegerType() ||
1426 // We can promote any unsigned integer type whose size is
1427 // less than int to an int.
Mike Stump1eb44332009-09-09 15:08:12 +00001428 (!FromType->isSignedIntegerType() &&
Sebastian Redl07779722008-10-31 14:43:28 +00001429 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001430 return To->getKind() == BuiltinType::Int;
Sebastian Redl07779722008-10-31 14:43:28 +00001431 }
1432
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001433 return To->getKind() == BuiltinType::UInt;
1434 }
1435
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001436 // C++0x [conv.prom]p3:
1437 // A prvalue of an unscoped enumeration type whose underlying type is not
1438 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1439 // following types that can represent all the values of the enumeration
1440 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1441 // unsigned int, long int, unsigned long int, long long int, or unsigned
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001442 // long long int. If none of the types in that list can represent all the
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001443 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001444 // type can be converted to an rvalue a prvalue of the extended integer type
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001445 // with lowest integer conversion rank (4.13) greater than the rank of long
1446 // long in which all the values of the enumeration can be represented. If
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001447 // there are two such extended types, the signed one is chosen.
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001448 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1449 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1450 // provided for a scoped enumeration.
1451 if (FromEnumType->getDecl()->isScoped())
1452 return false;
1453
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001454 // We have already pre-calculated the promotion type, so this is trivial.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001455 if (ToType->isIntegerType() &&
Douglas Gregor5dde1602010-09-12 03:38:25 +00001456 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall842aef82009-12-09 09:09:27 +00001457 return Context.hasSameUnqualifiedType(ToType,
1458 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor1274ccd2010-10-08 23:50:27 +00001459 }
John McCall842aef82009-12-09 09:09:27 +00001460
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001461 // C++0x [conv.prom]p2:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001462 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1463 // to an rvalue a prvalue of the first of the following types that can
1464 // represent all the values of its underlying type: int, unsigned int,
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001465 // long int, unsigned long int, long long int, or unsigned long long int.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001466 // If none of the types in that list can represent all the values of its
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001467 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001468 // or wchar_t can be converted to an rvalue a prvalue of its underlying
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001469 // type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001470 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
Douglas Gregor0b8ddb92010-10-21 18:04:08 +00001471 ToType->isIntegerType()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001472 // Determine whether the type we're converting from is signed or
1473 // unsigned.
David Majnemer0ad92312011-07-22 21:09:04 +00001474 bool FromIsSigned = FromType->isSignedIntegerType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001475 uint64_t FromSize = Context.getTypeSize(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001476
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001477 // The types we'll try to promote to, in the appropriate
1478 // order. Try each of these types.
Mike Stump1eb44332009-09-09 15:08:12 +00001479 QualType PromoteTypes[6] = {
1480 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001481 Context.LongTy, Context.UnsignedLongTy ,
1482 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001483 };
Douglas Gregorc9467cf2008-12-12 02:00:36 +00001484 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001485 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1486 if (FromSize < ToSize ||
Mike Stump1eb44332009-09-09 15:08:12 +00001487 (FromSize == ToSize &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001488 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1489 // We found the type that we can promote to. If this is the
1490 // type we wanted, we have a promotion. Otherwise, no
1491 // promotion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001492 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001493 }
1494 }
1495 }
1496
1497 // An rvalue for an integral bit-field (9.6) can be converted to an
1498 // rvalue of type int if int can represent all the values of the
1499 // bit-field; otherwise, it can be converted to unsigned int if
1500 // unsigned int can represent all the values of the bit-field. If
1501 // the bit-field is larger yet, no integral promotion applies to
1502 // it. If the bit-field has an enumerated type, it is treated as any
1503 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump390b4cc2009-05-16 07:39:55 +00001504 // FIXME: We should delay checking of bit-fields until we actually perform the
1505 // conversion.
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001506 using llvm::APSInt;
1507 if (From)
1508 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor86f19402008-12-20 23:49:58 +00001509 APSInt BitWidth;
Douglas Gregor9d3347a2010-06-16 00:35:25 +00001510 if (FromType->isIntegralType(Context) &&
Douglas Gregor33bbbc52009-05-02 02:18:30 +00001511 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1512 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1513 ToSize = Context.getTypeSize(ToType);
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Douglas Gregor86f19402008-12-20 23:49:58 +00001515 // Are we promoting to an int from a bitfield that fits in an int?
1516 if (BitWidth < ToSize ||
1517 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1518 return To->getKind() == BuiltinType::Int;
1519 }
Mike Stump1eb44332009-09-09 15:08:12 +00001520
Douglas Gregor86f19402008-12-20 23:49:58 +00001521 // Are we promoting to an unsigned int from an unsigned bitfield
1522 // that fits into an unsigned int?
1523 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1524 return To->getKind() == BuiltinType::UInt;
1525 }
Mike Stump1eb44332009-09-09 15:08:12 +00001526
Douglas Gregor86f19402008-12-20 23:49:58 +00001527 return false;
Sebastian Redl07779722008-10-31 14:43:28 +00001528 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001529 }
Mike Stump1eb44332009-09-09 15:08:12 +00001530
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001531 // An rvalue of type bool can be converted to an rvalue of type int,
1532 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl07779722008-10-31 14:43:28 +00001533 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001534 return true;
Sebastian Redl07779722008-10-31 14:43:28 +00001535 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001536
1537 return false;
1538}
1539
1540/// IsFloatingPointPromotion - Determines whether the conversion from
1541/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1542/// returns true and sets PromotedType to the promoted type.
Mike Stump1eb44332009-09-09 15:08:12 +00001543bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001544 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1545 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001546 /// An rvalue of type float can be converted to an rvalue of type
1547 /// double. (C++ 4.6p1).
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001548 if (FromBuiltin->getKind() == BuiltinType::Float &&
1549 ToBuiltin->getKind() == BuiltinType::Double)
1550 return true;
1551
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001552 // C99 6.3.1.5p1:
1553 // When a float is promoted to double or long double, or a
1554 // double is promoted to long double [...].
1555 if (!getLangOptions().CPlusPlus &&
1556 (FromBuiltin->getKind() == BuiltinType::Float ||
1557 FromBuiltin->getKind() == BuiltinType::Double) &&
1558 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1559 return true;
Anton Korobeynikovaa4a99b2011-10-14 23:23:15 +00001560
1561 // Half can be promoted to float.
1562 if (FromBuiltin->getKind() == BuiltinType::Half &&
1563 ToBuiltin->getKind() == BuiltinType::Float)
1564 return true;
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001565 }
1566
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001567 return false;
1568}
1569
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001570/// \brief Determine if a conversion is a complex promotion.
1571///
1572/// A complex promotion is defined as a complex -> complex conversion
1573/// where the conversion between the underlying real types is a
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001574/// floating-point or integral promotion.
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001575bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall183700f2009-09-21 23:43:11 +00001576 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001577 if (!FromComplex)
1578 return false;
1579
John McCall183700f2009-09-21 23:43:11 +00001580 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001581 if (!ToComplex)
1582 return false;
1583
1584 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregorb7b5d132009-02-12 00:26:06 +00001585 ToComplex->getElementType()) ||
1586 IsIntegralPromotion(0, FromComplex->getElementType(),
1587 ToComplex->getElementType());
Douglas Gregor5cdf8212009-02-12 00:15:05 +00001588}
1589
Douglas Gregorcb7de522008-11-26 23:31:11 +00001590/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1591/// the pointer type FromPtr to a pointer to type ToPointee, with the
1592/// same type qualifiers as FromPtr has on its pointee type. ToType,
1593/// if non-empty, will be a pointer to ToType that may or may not have
1594/// the right set of qualifiers on its pointee.
John McCallf85e1932011-06-15 23:02:42 +00001595///
Mike Stump1eb44332009-09-09 15:08:12 +00001596static QualType
Douglas Gregorda80f742010-12-01 21:43:58 +00001597BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001598 QualType ToPointee, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00001599 ASTContext &Context,
1600 bool StripObjCLifetime = false) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001601 assert((FromPtr->getTypeClass() == Type::Pointer ||
1602 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1603 "Invalid similarly-qualified pointer type");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001604
John McCallf85e1932011-06-15 23:02:42 +00001605 /// Conversions to 'id' subsume cv-qualifier conversions.
1606 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
Douglas Gregor143c7ac2010-12-06 22:09:19 +00001607 return ToType.getUnqualifiedType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001608
1609 QualType CanonFromPointee
Douglas Gregorda80f742010-12-01 21:43:58 +00001610 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregorcb7de522008-11-26 23:31:11 +00001611 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall0953e762009-09-24 19:53:00 +00001612 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump1eb44332009-09-09 15:08:12 +00001613
John McCallf85e1932011-06-15 23:02:42 +00001614 if (StripObjCLifetime)
1615 Quals.removeObjCLifetime();
1616
Mike Stump1eb44332009-09-09 15:08:12 +00001617 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregora4923eb2009-11-16 21:35:15 +00001618 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregorcb7de522008-11-26 23:31:11 +00001619 // ToType is exactly what we need. Return it.
John McCall0953e762009-09-24 19:53:00 +00001620 if (!ToType.isNull())
Douglas Gregoraf7bea52010-05-25 15:31:05 +00001621 return ToType.getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001622
1623 // Build a pointer to ToPointee. It has the right qualifiers
1624 // already.
Douglas Gregorda80f742010-12-01 21:43:58 +00001625 if (isa<ObjCObjectPointerType>(ToType))
1626 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregorcb7de522008-11-26 23:31:11 +00001627 return Context.getPointerType(ToPointee);
1628 }
1629
1630 // Just build a canonical type that has the right qualifiers.
Douglas Gregorda80f742010-12-01 21:43:58 +00001631 QualType QualifiedCanonToPointee
1632 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001633
Douglas Gregorda80f742010-12-01 21:43:58 +00001634 if (isa<ObjCObjectPointerType>(ToType))
1635 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1636 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001637}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001638
Mike Stump1eb44332009-09-09 15:08:12 +00001639static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001640 bool InOverloadResolution,
1641 ASTContext &Context) {
1642 // Handle value-dependent integral null pointer constants correctly.
1643 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1644 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00001645 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001646 return !InOverloadResolution;
1647
Douglas Gregorce940492009-09-25 04:25:58 +00001648 return Expr->isNullPointerConstant(Context,
1649 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1650 : Expr::NPC_ValueDependentIsNull);
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001651}
Mike Stump1eb44332009-09-09 15:08:12 +00001652
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001653/// IsPointerConversion - Determines whether the conversion of the
1654/// expression From, which has the (possibly adjusted) type FromType,
1655/// can be converted to the type ToType via a pointer conversion (C++
1656/// 4.10). If so, returns true and places the converted type (that
1657/// might differ from ToType in its cv-qualifiers at some level) into
1658/// ConvertedType.
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001659///
Douglas Gregor7ca09762008-11-27 01:19:21 +00001660/// This routine also supports conversions to and from block pointers
1661/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1662/// pointers to interfaces. FIXME: Once we've determined the
1663/// appropriate overloading rules for Objective-C, we may want to
1664/// split the Objective-C checks into a different routine; however,
1665/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor45920e82008-12-19 17:40:08 +00001666/// conversions, so for now they live here. IncompatibleObjC will be
1667/// set if the conversion is an allowed Objective-C conversion that
1668/// should result in a warning.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001669bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson08972922009-08-28 15:33:32 +00001670 bool InOverloadResolution,
Douglas Gregor45920e82008-12-19 17:40:08 +00001671 QualType& ConvertedType,
Mike Stump1eb44332009-09-09 15:08:12 +00001672 bool &IncompatibleObjC) {
Douglas Gregor45920e82008-12-19 17:40:08 +00001673 IncompatibleObjC = false;
Chandler Carruth6df868e2010-12-12 08:17:55 +00001674 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1675 IncompatibleObjC))
Douglas Gregorc7887512008-12-19 19:13:09 +00001676 return true;
Douglas Gregor45920e82008-12-19 17:40:08 +00001677
Mike Stump1eb44332009-09-09 15:08:12 +00001678 // Conversion from a null pointer constant to any Objective-C pointer type.
1679 if (ToType->isObjCObjectPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001680 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor27b09ac2008-12-22 20:51:52 +00001681 ConvertedType = ToType;
1682 return true;
1683 }
1684
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001685 // Blocks: Block pointers can be converted to void*.
1686 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenek6217b802009-07-29 21:53:49 +00001687 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001688 ConvertedType = ToType;
1689 return true;
1690 }
1691 // Blocks: A null pointer constant can be converted to a block
1692 // pointer type.
Mike Stump1eb44332009-09-09 15:08:12 +00001693 if (ToType->isBlockPointerType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001694 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor071f2ae2008-11-27 00:15:41 +00001695 ConvertedType = ToType;
1696 return true;
1697 }
1698
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001699 // If the left-hand-side is nullptr_t, the right side can be a null
1700 // pointer constant.
Mike Stump1eb44332009-09-09 15:08:12 +00001701 if (ToType->isNullPtrType() &&
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001702 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl6e8ed162009-05-10 18:38:11 +00001703 ConvertedType = ToType;
1704 return true;
1705 }
1706
Ted Kremenek6217b802009-07-29 21:53:49 +00001707 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001708 if (!ToTypePtr)
1709 return false;
1710
1711 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlssonbbf306b2009-08-28 15:55:56 +00001712 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001713 ConvertedType = ToType;
1714 return true;
1715 }
Sebastian Redl07779722008-10-31 14:43:28 +00001716
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001717 // Beyond this point, both types need to be pointers
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001718 // , including objective-c pointers.
1719 QualType ToPointeeType = ToTypePtr->getPointeeType();
John McCallf85e1932011-06-15 23:02:42 +00001720 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType() &&
1721 !getLangOptions().ObjCAutoRefCount) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001722 ConvertedType = BuildSimilarlyQualifiedPointerType(
1723 FromType->getAs<ObjCObjectPointerType>(),
1724 ToPointeeType,
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001725 ToType, Context);
1726 return true;
Fariborz Jahanianadcfab12009-12-16 23:13:33 +00001727 }
Ted Kremenek6217b802009-07-29 21:53:49 +00001728 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001729 if (!FromTypePtr)
1730 return false;
1731
1732 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00001733
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001734 // If the unqualified pointee types are the same, this can't be a
Douglas Gregor4e938f57b2010-08-18 21:25:30 +00001735 // pointer conversion, so don't do all of the work below.
1736 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1737 return false;
1738
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001739 // An rvalue of type "pointer to cv T," where T is an object type,
1740 // can be converted to an rvalue of type "pointer to cv void" (C++
1741 // 4.10p2).
Eli Friedman13578692010-08-05 02:49:48 +00001742 if (FromPointeeType->isIncompleteOrObjectType() &&
1743 ToPointeeType->isVoidType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001744 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001745 ToPointeeType,
John McCallf85e1932011-06-15 23:02:42 +00001746 ToType, Context,
1747 /*StripObjCLifetime=*/true);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001748 return true;
1749 }
1750
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001751 // MSVC allows implicit function to void* type conversion.
Francois Pichet62ec1f22011-09-17 17:15:52 +00001752 if (getLangOptions().MicrosoftExt && FromPointeeType->isFunctionType() &&
Francois Picheta8ef3ac2011-05-08 22:52:41 +00001753 ToPointeeType->isVoidType()) {
1754 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1755 ToPointeeType,
1756 ToType, Context);
1757 return true;
1758 }
1759
Douglas Gregorf9201e02009-02-11 23:02:49 +00001760 // When we're overloading in C, we allow a special kind of pointer
1761 // conversion for compatible-but-not-identical pointee types.
Mike Stump1eb44332009-09-09 15:08:12 +00001762 if (!getLangOptions().CPlusPlus &&
Douglas Gregorf9201e02009-02-11 23:02:49 +00001763 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001764 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorf9201e02009-02-11 23:02:49 +00001765 ToPointeeType,
Mike Stump1eb44332009-09-09 15:08:12 +00001766 ToType, Context);
Douglas Gregorf9201e02009-02-11 23:02:49 +00001767 return true;
1768 }
1769
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001770 // C++ [conv.ptr]p3:
Mike Stump1eb44332009-09-09 15:08:12 +00001771 //
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001772 // An rvalue of type "pointer to cv D," where D is a class type,
1773 // can be converted to an rvalue of type "pointer to cv B," where
1774 // B is a base class (clause 10) of D. If B is an inaccessible
1775 // (clause 11) or ambiguous (10.2) base class of D, a program that
1776 // necessitates this conversion is ill-formed. The result of the
1777 // conversion is a pointer to the base class sub-object of the
1778 // derived class object. The null pointer value is converted to
1779 // the null pointer value of the destination type.
1780 //
Douglas Gregor94b1dd22008-10-24 04:54:22 +00001781 // Note that we do not check for ambiguity or inaccessibility
1782 // here. That is handled by CheckPointerConversion.
Douglas Gregorf9201e02009-02-11 23:02:49 +00001783 if (getLangOptions().CPlusPlus &&
1784 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregorbf1764c2010-02-22 17:06:41 +00001785 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregor2685eab2009-10-29 23:08:22 +00001786 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregorcb7de522008-11-26 23:31:11 +00001787 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001788 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbf408182008-11-27 00:52:49 +00001789 ToPointeeType,
Douglas Gregorcb7de522008-11-26 23:31:11 +00001790 ToType, Context);
1791 return true;
1792 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00001793
Fariborz Jahanian5da3c082011-04-14 20:33:36 +00001794 if (FromPointeeType->isVectorType() && ToPointeeType->isVectorType() &&
1795 Context.areCompatibleVectorTypes(FromPointeeType, ToPointeeType)) {
1796 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
1797 ToPointeeType,
1798 ToType, Context);
1799 return true;
1800 }
1801
Douglas Gregorc7887512008-12-19 19:13:09 +00001802 return false;
1803}
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001804
1805/// \brief Adopt the given qualifiers for the given type.
1806static QualType AdoptQualifiers(ASTContext &Context, QualType T, Qualifiers Qs){
1807 Qualifiers TQs = T.getQualifiers();
1808
1809 // Check whether qualifiers already match.
1810 if (TQs == Qs)
1811 return T;
1812
1813 if (Qs.compatiblyIncludes(TQs))
1814 return Context.getQualifiedType(T, Qs);
1815
1816 return Context.getQualifiedType(T.getUnqualifiedType(), Qs);
1817}
Douglas Gregorc7887512008-12-19 19:13:09 +00001818
1819/// isObjCPointerConversion - Determines whether this is an
1820/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1821/// with the same arguments and return values.
Mike Stump1eb44332009-09-09 15:08:12 +00001822bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregorc7887512008-12-19 19:13:09 +00001823 QualType& ConvertedType,
1824 bool &IncompatibleObjC) {
1825 if (!getLangOptions().ObjC1)
1826 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001827
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001828 // The set of qualifiers on the type we're converting from.
1829 Qualifiers FromQualifiers = FromType.getQualifiers();
1830
Steve Naroff14108da2009-07-10 23:34:53 +00001831 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth6df868e2010-12-12 08:17:55 +00001832 const ObjCObjectPointerType* ToObjCPtr =
1833 ToType->getAs<ObjCObjectPointerType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001834 const ObjCObjectPointerType *FromObjCPtr =
John McCall183700f2009-09-21 23:43:11 +00001835 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001836
Steve Naroff14108da2009-07-10 23:34:53 +00001837 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregorda80f742010-12-01 21:43:58 +00001838 // If the pointee types are the same (ignoring qualifications),
1839 // then this is not a pointer conversion.
1840 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1841 FromObjCPtr->getPointeeType()))
1842 return false;
1843
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001844 // Check for compatible
Steve Naroffde2e22d2009-07-15 18:40:39 +00001845 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff14108da2009-07-10 23:34:53 +00001846 // pointer to any interface (in both directions).
Steve Naroffde2e22d2009-07-15 18:40:39 +00001847 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001848 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001849 return true;
1850 }
1851 // Conversions with Objective-C's id<...>.
Mike Stump1eb44332009-09-09 15:08:12 +00001852 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff14108da2009-07-10 23:34:53 +00001853 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump1eb44332009-09-09 15:08:12 +00001854 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff4084c302009-07-23 01:01:38 +00001855 /*compare=*/false)) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001856 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001857 return true;
1858 }
1859 // Objective C++: We're able to convert from a pointer to an
1860 // interface to a pointer to a different interface.
1861 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianee9ca692010-03-15 18:36:00 +00001862 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1863 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1864 if (getLangOptions().CPlusPlus && LHS && RHS &&
1865 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1866 FromObjCPtr->getPointeeType()))
1867 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001868 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00001869 ToObjCPtr->getPointeeType(),
1870 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001871 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001872 return true;
1873 }
1874
1875 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1876 // Okay: this is some kind of implicit downcast of Objective-C
1877 // interfaces, which is permitted. However, we're going to
1878 // complain about it.
1879 IncompatibleObjC = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001880 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
Douglas Gregorda80f742010-12-01 21:43:58 +00001881 ToObjCPtr->getPointeeType(),
1882 ToType, Context);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001883 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Steve Naroff14108da2009-07-10 23:34:53 +00001884 return true;
1885 }
Mike Stump1eb44332009-09-09 15:08:12 +00001886 }
Steve Naroff14108da2009-07-10 23:34:53 +00001887 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001888 QualType ToPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001889 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001890 ToPointeeType = ToCPtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001891 else if (const BlockPointerType *ToBlockPtr =
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001892 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian48168392010-01-21 00:08:17 +00001893 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001894 // to a block pointer type.
1895 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001896 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001897 return true;
1898 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001899 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanianb351a7d2010-01-20 22:54:38 +00001900 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001901 else if (FromType->getAs<BlockPointerType>() &&
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001902 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001903 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian48168392010-01-21 00:08:17 +00001904 // pointer to any object.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001905 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Fariborz Jahanianf7c43fd2010-01-21 00:05:09 +00001906 return true;
1907 }
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001908 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001909 return false;
1910
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001911 QualType FromPointeeType;
Ted Kremenek6217b802009-07-29 21:53:49 +00001912 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff14108da2009-07-10 23:34:53 +00001913 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth6df868e2010-12-12 08:17:55 +00001914 else if (const BlockPointerType *FromBlockPtr =
1915 FromType->getAs<BlockPointerType>())
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001916 FromPointeeType = FromBlockPtr->getPointeeType();
1917 else
Douglas Gregorc7887512008-12-19 19:13:09 +00001918 return false;
1919
Douglas Gregorc7887512008-12-19 19:13:09 +00001920 // If we have pointers to pointers, recursively check whether this
1921 // is an Objective-C conversion.
1922 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1923 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1924 IncompatibleObjC)) {
1925 // We always complain about this conversion.
1926 IncompatibleObjC = true;
Douglas Gregorda80f742010-12-01 21:43:58 +00001927 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001928 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00001929 return true;
1930 }
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001931 // Allow conversion of pointee being objective-c pointer to another one;
1932 // as in I* to id.
1933 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1934 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1935 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1936 IncompatibleObjC)) {
John McCallf85e1932011-06-15 23:02:42 +00001937
Douglas Gregorda80f742010-12-01 21:43:58 +00001938 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregor028ea4b2011-04-26 23:16:46 +00001939 ConvertedType = AdoptQualifiers(Context, ConvertedType, FromQualifiers);
Fariborz Jahanian83b7b312010-01-18 22:59:22 +00001940 return true;
1941 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00001942
Douglas Gregor2a7e58d2008-12-23 00:53:59 +00001943 // If we have pointers to functions or blocks, check whether the only
Douglas Gregorc7887512008-12-19 19:13:09 +00001944 // differences in the argument and result types are in Objective-C
1945 // pointer conversions. If so, we permit the conversion (but
1946 // complain about it).
Mike Stump1eb44332009-09-09 15:08:12 +00001947 const FunctionProtoType *FromFunctionType
John McCall183700f2009-09-21 23:43:11 +00001948 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregor72564e72009-02-26 23:50:07 +00001949 const FunctionProtoType *ToFunctionType
John McCall183700f2009-09-21 23:43:11 +00001950 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregorc7887512008-12-19 19:13:09 +00001951 if (FromFunctionType && ToFunctionType) {
1952 // If the function types are exactly the same, this isn't an
1953 // Objective-C pointer conversion.
1954 if (Context.getCanonicalType(FromPointeeType)
1955 == Context.getCanonicalType(ToPointeeType))
1956 return false;
1957
1958 // Perform the quick checks that will tell us whether these
1959 // function types are obviously different.
1960 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1961 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1962 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1963 return false;
1964
1965 bool HasObjCConversion = false;
1966 if (Context.getCanonicalType(FromFunctionType->getResultType())
1967 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1968 // Okay, the types match exactly. Nothing to do.
1969 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1970 ToFunctionType->getResultType(),
1971 ConvertedType, IncompatibleObjC)) {
1972 // Okay, we have an Objective-C pointer conversion.
1973 HasObjCConversion = true;
1974 } else {
1975 // Function types are too different. Abort.
1976 return false;
1977 }
Mike Stump1eb44332009-09-09 15:08:12 +00001978
Douglas Gregorc7887512008-12-19 19:13:09 +00001979 // Check argument types.
1980 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1981 ArgIdx != NumArgs; ++ArgIdx) {
1982 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1983 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1984 if (Context.getCanonicalType(FromArgType)
1985 == Context.getCanonicalType(ToArgType)) {
1986 // Okay, the types match exactly. Nothing to do.
1987 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1988 ConvertedType, IncompatibleObjC)) {
1989 // Okay, we have an Objective-C pointer conversion.
1990 HasObjCConversion = true;
1991 } else {
1992 // Argument types are too different. Abort.
1993 return false;
1994 }
1995 }
1996
1997 if (HasObjCConversion) {
1998 // We had an Objective-C conversion. Allow this pointer
1999 // conversion, but complain about it.
Douglas Gregor028ea4b2011-04-26 23:16:46 +00002000 ConvertedType = AdoptQualifiers(Context, ToType, FromQualifiers);
Douglas Gregorc7887512008-12-19 19:13:09 +00002001 IncompatibleObjC = true;
2002 return true;
2003 }
2004 }
2005
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002006 return false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002007}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002008
John McCallf85e1932011-06-15 23:02:42 +00002009/// \brief Determine whether this is an Objective-C writeback conversion,
2010/// used for parameter passing when performing automatic reference counting.
2011///
2012/// \param FromType The type we're converting form.
2013///
2014/// \param ToType The type we're converting to.
2015///
2016/// \param ConvertedType The type that will be produced after applying
2017/// this conversion.
2018bool Sema::isObjCWritebackConversion(QualType FromType, QualType ToType,
2019 QualType &ConvertedType) {
2020 if (!getLangOptions().ObjCAutoRefCount ||
2021 Context.hasSameUnqualifiedType(FromType, ToType))
2022 return false;
2023
2024 // Parameter must be a pointer to __autoreleasing (with no other qualifiers).
2025 QualType ToPointee;
2026 if (const PointerType *ToPointer = ToType->getAs<PointerType>())
2027 ToPointee = ToPointer->getPointeeType();
2028 else
2029 return false;
2030
2031 Qualifiers ToQuals = ToPointee.getQualifiers();
2032 if (!ToPointee->isObjCLifetimeType() ||
2033 ToQuals.getObjCLifetime() != Qualifiers::OCL_Autoreleasing ||
2034 !ToQuals.withoutObjCGLifetime().empty())
2035 return false;
2036
2037 // Argument must be a pointer to __strong to __weak.
2038 QualType FromPointee;
2039 if (const PointerType *FromPointer = FromType->getAs<PointerType>())
2040 FromPointee = FromPointer->getPointeeType();
2041 else
2042 return false;
2043
2044 Qualifiers FromQuals = FromPointee.getQualifiers();
2045 if (!FromPointee->isObjCLifetimeType() ||
2046 (FromQuals.getObjCLifetime() != Qualifiers::OCL_Strong &&
2047 FromQuals.getObjCLifetime() != Qualifiers::OCL_Weak))
2048 return false;
2049
2050 // Make sure that we have compatible qualifiers.
2051 FromQuals.setObjCLifetime(Qualifiers::OCL_Autoreleasing);
2052 if (!ToQuals.compatiblyIncludes(FromQuals))
2053 return false;
2054
2055 // Remove qualifiers from the pointee type we're converting from; they
2056 // aren't used in the compatibility check belong, and we'll be adding back
2057 // qualifiers (with __autoreleasing) if the compatibility check succeeds.
2058 FromPointee = FromPointee.getUnqualifiedType();
2059
2060 // The unqualified form of the pointee types must be compatible.
2061 ToPointee = ToPointee.getUnqualifiedType();
2062 bool IncompatibleObjC;
2063 if (Context.typesAreCompatible(FromPointee, ToPointee))
2064 FromPointee = ToPointee;
2065 else if (!isObjCPointerConversion(FromPointee, ToPointee, FromPointee,
2066 IncompatibleObjC))
2067 return false;
2068
2069 /// \brief Construct the type we're converting to, which is a pointer to
2070 /// __autoreleasing pointee.
2071 FromPointee = Context.getQualifiedType(FromPointee, FromQuals);
2072 ConvertedType = Context.getPointerType(FromPointee);
2073 return true;
2074}
2075
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002076bool Sema::IsBlockPointerConversion(QualType FromType, QualType ToType,
2077 QualType& ConvertedType) {
2078 QualType ToPointeeType;
2079 if (const BlockPointerType *ToBlockPtr =
2080 ToType->getAs<BlockPointerType>())
2081 ToPointeeType = ToBlockPtr->getPointeeType();
2082 else
2083 return false;
2084
2085 QualType FromPointeeType;
2086 if (const BlockPointerType *FromBlockPtr =
2087 FromType->getAs<BlockPointerType>())
2088 FromPointeeType = FromBlockPtr->getPointeeType();
2089 else
2090 return false;
2091 // We have pointer to blocks, check whether the only
2092 // differences in the argument and result types are in Objective-C
2093 // pointer conversions. If so, we permit the conversion.
2094
2095 const FunctionProtoType *FromFunctionType
2096 = FromPointeeType->getAs<FunctionProtoType>();
2097 const FunctionProtoType *ToFunctionType
2098 = ToPointeeType->getAs<FunctionProtoType>();
2099
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002100 if (!FromFunctionType || !ToFunctionType)
2101 return false;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002102
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002103 if (Context.hasSameType(FromPointeeType, ToPointeeType))
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002104 return true;
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002105
2106 // Perform the quick checks that will tell us whether these
2107 // function types are obviously different.
2108 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
2109 FromFunctionType->isVariadic() != ToFunctionType->isVariadic())
2110 return false;
2111
2112 FunctionType::ExtInfo FromEInfo = FromFunctionType->getExtInfo();
2113 FunctionType::ExtInfo ToEInfo = ToFunctionType->getExtInfo();
2114 if (FromEInfo != ToEInfo)
2115 return false;
2116
2117 bool IncompatibleObjC = false;
Fariborz Jahanian462dae52011-02-13 20:11:42 +00002118 if (Context.hasSameType(FromFunctionType->getResultType(),
2119 ToFunctionType->getResultType())) {
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002120 // Okay, the types match exactly. Nothing to do.
2121 } else {
2122 QualType RHS = FromFunctionType->getResultType();
2123 QualType LHS = ToFunctionType->getResultType();
2124 if ((!getLangOptions().CPlusPlus || !RHS->isRecordType()) &&
2125 !RHS.hasQualifiers() && LHS.hasQualifiers())
2126 LHS = LHS.getUnqualifiedType();
2127
2128 if (Context.hasSameType(RHS,LHS)) {
2129 // OK exact match.
2130 } else if (isObjCPointerConversion(RHS, LHS,
2131 ConvertedType, IncompatibleObjC)) {
2132 if (IncompatibleObjC)
2133 return false;
2134 // Okay, we have an Objective-C pointer conversion.
2135 }
2136 else
2137 return false;
2138 }
2139
2140 // Check argument types.
2141 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
2142 ArgIdx != NumArgs; ++ArgIdx) {
2143 IncompatibleObjC = false;
2144 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
2145 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
2146 if (Context.hasSameType(FromArgType, ToArgType)) {
2147 // Okay, the types match exactly. Nothing to do.
2148 } else if (isObjCPointerConversion(ToArgType, FromArgType,
2149 ConvertedType, IncompatibleObjC)) {
2150 if (IncompatibleObjC)
2151 return false;
2152 // Okay, we have an Objective-C pointer conversion.
2153 } else
2154 // Argument types are too different. Abort.
2155 return false;
2156 }
Fariborz Jahanian78213e42011-09-28 21:52:05 +00002157 if (LangOpts.ObjCAutoRefCount &&
2158 !Context.FunctionTypesMatchOnNSConsumedAttrs(FromFunctionType,
2159 ToFunctionType))
2160 return false;
Fariborz Jahanianf9d95272011-09-28 20:22:05 +00002161
Fariborz Jahanian569bd8f2011-02-13 20:01:48 +00002162 ConvertedType = ToType;
2163 return true;
Fariborz Jahaniane3c8c642011-02-12 19:07:46 +00002164}
2165
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002166/// FunctionArgTypesAreEqual - This routine checks two function proto types
2167/// for equlity of their argument types. Caller has already checked that
2168/// they have same number of arguments. This routine assumes that Objective-C
2169/// pointer types which only differ in their protocol qualifiers are equal.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002170bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
John McCallf4c73712011-01-19 06:33:43 +00002171 const FunctionProtoType *NewType) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002172 if (!getLangOptions().ObjC1)
2173 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
2174 NewType->arg_type_begin());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002175
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002176 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2177 N = NewType->arg_type_begin(),
2178 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2179 QualType ToType = (*O);
2180 QualType FromType = (*N);
2181 if (ToType != FromType) {
2182 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2183 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002184 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2185 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2186 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2187 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002188 continue;
2189 }
John McCallc12c5bb2010-05-15 11:32:37 +00002190 else if (const ObjCObjectPointerType *PTTo =
2191 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002192 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002193 FromType->getAs<ObjCObjectPointerType>())
2194 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
2195 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002196 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002197 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002198 }
2199 }
2200 return true;
2201}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002202
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002203/// CheckPointerConversion - Check the pointer conversion from the
2204/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002205/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002206/// conversions for which IsPointerConversion has already returned
2207/// true. It returns true and produces a diagnostic if there was an
2208/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002209bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002210 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002211 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002212 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002213 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002214 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002215
John McCalldaa8e4e2010-11-15 09:13:47 +00002216 Kind = CK_BitCast;
2217
Chandler Carruth88f0aed2011-04-09 07:32:05 +00002218 if (!IsCStyleOrFunctionalCast &&
2219 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2220 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2221 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruthb6006692011-04-09 07:48:17 +00002222 PDiag(diag::warn_impcast_bool_to_null_pointer)
2223 << ToType << From->getSourceRange());
Douglas Gregord7a95972010-06-08 17:35:15 +00002224
John McCall1d9b3b22011-09-09 05:25:32 +00002225 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2226 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002227 QualType FromPointeeType = FromPtrType->getPointeeType(),
2228 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002229
Douglas Gregor5fccd362010-03-03 23:55:11 +00002230 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2231 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002232 // We must have a derived-to-base conversion. Check an
2233 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002234 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2235 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002236 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002237 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002238 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002239
Anders Carlsson61faec12009-09-12 04:46:44 +00002240 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002241 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002242 }
2243 }
John McCall1d9b3b22011-09-09 05:25:32 +00002244 } else if (const ObjCObjectPointerType *ToPtrType =
2245 ToType->getAs<ObjCObjectPointerType>()) {
2246 if (const ObjCObjectPointerType *FromPtrType =
2247 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002248 // Objective-C++ conversions are always okay.
2249 // FIXME: We should have a different class of conversions for the
2250 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002251 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002252 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002253 } else if (FromType->isBlockPointerType()) {
2254 Kind = CK_BlockPointerToObjCPointerCast;
2255 } else {
2256 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002257 }
John McCall1d9b3b22011-09-09 05:25:32 +00002258 } else if (ToType->isBlockPointerType()) {
2259 if (!FromType->isBlockPointerType())
2260 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002261 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002262
2263 // We shouldn't fall into this case unless it's valid for other
2264 // reasons.
2265 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2266 Kind = CK_NullToPointer;
2267
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002268 return false;
2269}
2270
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002271/// IsMemberPointerConversion - Determines whether the conversion of the
2272/// expression From, which has the (possibly adjusted) type FromType, can be
2273/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2274/// If so, returns true and places the converted type (that might differ from
2275/// ToType in its cv-qualifiers at some level) into ConvertedType.
2276bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002277 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002278 bool InOverloadResolution,
2279 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002280 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002281 if (!ToTypePtr)
2282 return false;
2283
2284 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002285 if (From->isNullPointerConstant(Context,
2286 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2287 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002288 ConvertedType = ToType;
2289 return true;
2290 }
2291
2292 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002293 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002294 if (!FromTypePtr)
2295 return false;
2296
2297 // A pointer to member of B can be converted to a pointer to member of D,
2298 // where D is derived from B (C++ 4.11p2).
2299 QualType FromClass(FromTypePtr->getClass(), 0);
2300 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002301
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002302 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2303 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2304 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002305 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2306 ToClass.getTypePtr());
2307 return true;
2308 }
2309
2310 return false;
2311}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002312
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002313/// CheckMemberPointerConversion - Check the member pointer conversion from the
2314/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002315/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002316/// for which IsMemberPointerConversion has already returned true. It returns
2317/// true and produces a diagnostic if there was an error, or returns false
2318/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002319bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002320 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002321 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002322 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002323 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002324 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002325 if (!FromPtrType) {
2326 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002327 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002328 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002329 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002330 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002331 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002332 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002333
Ted Kremenek6217b802009-07-29 21:53:49 +00002334 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002335 assert(ToPtrType && "No member pointer cast has a target type "
2336 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002337
Sebastian Redl21593ac2009-01-28 18:33:18 +00002338 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2339 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002340
Sebastian Redl21593ac2009-01-28 18:33:18 +00002341 // FIXME: What about dependent types?
2342 assert(FromClass->isRecordType() && "Pointer into non-class.");
2343 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002344
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002345 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002346 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002347 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2348 assert(DerivationOkay &&
2349 "Should not have been called if derivation isn't OK.");
2350 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002351
Sebastian Redl21593ac2009-01-28 18:33:18 +00002352 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2353 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002354 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2355 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2356 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2357 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002358 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002359
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002360 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002361 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2362 << FromClass << ToClass << QualType(VBase, 0)
2363 << From->getSourceRange();
2364 return true;
2365 }
2366
John McCall6b2accb2010-02-10 09:31:12 +00002367 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002368 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2369 Paths.front(),
2370 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002371
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002372 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002373 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002374 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002375 return false;
2376}
2377
Douglas Gregor98cd5992008-10-21 23:43:52 +00002378/// IsQualificationConversion - Determines whether the conversion from
2379/// an rvalue of type FromType to ToType is a qualification conversion
2380/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002381///
2382/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2383/// when the qualification conversion involves a change in the Objective-C
2384/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002385bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002386Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002387 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002388 FromType = Context.getCanonicalType(FromType);
2389 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002390 ObjCLifetimeConversion = false;
2391
Douglas Gregor98cd5992008-10-21 23:43:52 +00002392 // If FromType and ToType are the same type, this is not a
2393 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002394 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002395 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002396
Douglas Gregor98cd5992008-10-21 23:43:52 +00002397 // (C++ 4.4p4):
2398 // A conversion can add cv-qualifiers at levels other than the first
2399 // in multi-level pointers, subject to the following rules: [...]
2400 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002401 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002402 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002403 // Within each iteration of the loop, we check the qualifiers to
2404 // determine if this still looks like a qualification
2405 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002406 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002407 // until there are no more pointers or pointers-to-members left to
2408 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002409 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002410
Douglas Gregor621c92a2011-04-25 18:40:17 +00002411 Qualifiers FromQuals = FromType.getQualifiers();
2412 Qualifiers ToQuals = ToType.getQualifiers();
2413
John McCallf85e1932011-06-15 23:02:42 +00002414 // Objective-C ARC:
2415 // Check Objective-C lifetime conversions.
2416 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2417 UnwrappedAnyPointer) {
2418 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2419 ObjCLifetimeConversion = true;
2420 FromQuals.removeObjCLifetime();
2421 ToQuals.removeObjCLifetime();
2422 } else {
2423 // Qualification conversions cannot cast between different
2424 // Objective-C lifetime qualifiers.
2425 return false;
2426 }
2427 }
2428
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002429 // Allow addition/removal of GC attributes but not changing GC attributes.
2430 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2431 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2432 FromQuals.removeObjCGCAttr();
2433 ToQuals.removeObjCGCAttr();
2434 }
2435
Douglas Gregor98cd5992008-10-21 23:43:52 +00002436 // -- for every j > 0, if const is in cv 1,j then const is in cv
2437 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002438 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002439 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002440
Douglas Gregor98cd5992008-10-21 23:43:52 +00002441 // -- if the cv 1,j and cv 2,j are different, then const is in
2442 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002443 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002444 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002445 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002446
Douglas Gregor98cd5992008-10-21 23:43:52 +00002447 // Keep track of whether all prior cv-qualifiers in the "to" type
2448 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002449 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002450 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002451 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002452
2453 // We are left with FromType and ToType being the pointee types
2454 // after unwrapping the original FromType and ToType the same number
2455 // of types. If we unwrapped any pointers, and if FromType and
2456 // ToType have the same unqualified type (since we checked
2457 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002458 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002459}
2460
Douglas Gregor734d9862009-01-30 23:27:23 +00002461/// Determines whether there is a user-defined conversion sequence
2462/// (C++ [over.ics.user]) that converts expression From to the type
2463/// ToType. If such a conversion exists, User will contain the
2464/// user-defined conversion sequence that performs such a conversion
2465/// and this routine will return true. Otherwise, this routine returns
2466/// false and User is unspecified.
2467///
Douglas Gregor734d9862009-01-30 23:27:23 +00002468/// \param AllowExplicit true if the conversion should consider C++0x
2469/// "explicit" conversion functions as well as non-explicit conversion
2470/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002471static OverloadingResult
2472IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2473 UserDefinedConversionSequence& User,
2474 OverloadCandidateSet& CandidateSet,
2475 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002476 // Whether we will only visit constructors.
2477 bool ConstructorsOnly = false;
2478
2479 // If the type we are conversion to is a class type, enumerate its
2480 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002481 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002482 // C++ [over.match.ctor]p1:
2483 // When objects of class type are direct-initialized (8.5), or
2484 // copy-initialized from an expression of the same or a
2485 // derived class type (8.5), overload resolution selects the
2486 // constructor. [...] For copy-initialization, the candidate
2487 // functions are all the converting constructors (12.3.1) of
2488 // that class. The argument list is the expression-list within
2489 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002490 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002491 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002492 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002493 ConstructorsOnly = true;
2494
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002495 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2496 // RequireCompleteType may have returned true due to some invalid decl
2497 // during template instantiation, but ToType may be complete enough now
2498 // to try to recover.
2499 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002500 // We're not going to find any constructors.
2501 } else if (CXXRecordDecl *ToRecordDecl
2502 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002503 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002504 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002505 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002506 NamedDecl *D = *Con;
2507 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2508
Douglas Gregordec06662009-08-21 18:42:58 +00002509 // Find the constructor (which may be a template).
2510 CXXConstructorDecl *Constructor = 0;
2511 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002512 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002513 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002514 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002515 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2516 else
John McCall9aa472c2010-03-19 07:35:19 +00002517 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002518
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00002519 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00002520 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00002521 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002522 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2523 /*ExplicitArgs*/ 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002524 &From, 1, CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002525 /*SuppressUserConversions=*/
2526 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002527 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002528 // Allow one user-defined conversion when user specifies a
2529 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002530 S.AddOverloadCandidate(Constructor, FoundDecl,
2531 &From, 1, CandidateSet,
2532 /*SuppressUserConversions=*/
2533 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002534 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002535 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002536 }
2537 }
2538
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002539 // Enumerate conversion functions, if we're allowed to.
2540 if (ConstructorsOnly) {
John McCall120d63c2010-08-24 20:38:10 +00002541 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2542 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002543 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002544 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002545 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002546 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002547 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2548 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002549 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002550 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002551 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002552 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002553 DeclAccessPair FoundDecl = I.getPair();
2554 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002555 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2556 if (isa<UsingShadowDecl>(D))
2557 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2558
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002559 CXXConversionDecl *Conv;
2560 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002561 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2562 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002563 else
John McCall32daa422010-03-31 01:36:47 +00002564 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002565
2566 if (AllowExplicit || !Conv->isExplicit()) {
2567 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002568 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2569 ActingContext, From, ToType,
2570 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002571 else
John McCall120d63c2010-08-24 20:38:10 +00002572 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2573 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002574 }
2575 }
2576 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002577 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002578
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002579 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2580
Douglas Gregor60d62c22008-10-31 16:23:19 +00002581 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002582 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002583 case OR_Success:
2584 // Record the standard conversion we used and the conversion function.
2585 if (CXXConstructorDecl *Constructor
2586 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth25ca4212011-02-25 19:41:05 +00002587 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2588
John McCall120d63c2010-08-24 20:38:10 +00002589 // C++ [over.ics.user]p1:
2590 // If the user-defined conversion is specified by a
2591 // constructor (12.3.1), the initial standard conversion
2592 // sequence converts the source type to the type required by
2593 // the argument of the constructor.
2594 //
2595 QualType ThisType = Constructor->getThisType(S.Context);
2596 if (Best->Conversions[0].isEllipsis())
2597 User.EllipsisConversion = true;
2598 else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002599 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002600 User.EllipsisConversion = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002601 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002602 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00002603 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00002604 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00002605 User.After.setAsIdentityConversion();
2606 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2607 User.After.setAllToTypes(ToType);
2608 return OR_Success;
2609 } else if (CXXConversionDecl *Conversion
2610 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth25ca4212011-02-25 19:41:05 +00002611 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2612
John McCall120d63c2010-08-24 20:38:10 +00002613 // C++ [over.ics.user]p1:
2614 //
2615 // [...] If the user-defined conversion is specified by a
2616 // conversion function (12.3.2), the initial standard
2617 // conversion sequence converts the source type to the
2618 // implicit object parameter of the conversion function.
2619 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002620 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00002621 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00002622 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00002623 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002624
John McCall120d63c2010-08-24 20:38:10 +00002625 // C++ [over.ics.user]p2:
2626 // The second standard conversion sequence converts the
2627 // result of the user-defined conversion to the target type
2628 // for the sequence. Since an implicit conversion sequence
2629 // is an initialization, the special rules for
2630 // initialization by user-defined conversion apply when
2631 // selecting the best user-defined conversion for a
2632 // user-defined conversion sequence (see 13.3.3 and
2633 // 13.3.3.1).
2634 User.After = Best->FinalConversion;
2635 return OR_Success;
2636 } else {
2637 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002638 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002639 }
2640
John McCall120d63c2010-08-24 20:38:10 +00002641 case OR_No_Viable_Function:
2642 return OR_No_Viable_Function;
2643 case OR_Deleted:
2644 // No conversion here! We're done.
2645 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002646
John McCall120d63c2010-08-24 20:38:10 +00002647 case OR_Ambiguous:
2648 return OR_Ambiguous;
2649 }
2650
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002651 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002652}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002653
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002654bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002655Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002656 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002657 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002658 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002659 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002660 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002661 if (OvResult == OR_Ambiguous)
2662 Diag(From->getSourceRange().getBegin(),
2663 diag::err_typecheck_ambiguous_condition)
2664 << From->getType() << ToType << From->getSourceRange();
2665 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2666 Diag(From->getSourceRange().getBegin(),
2667 diag::err_typecheck_nonviable_condition)
2668 << From->getType() << ToType << From->getSourceRange();
2669 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002670 return false;
John McCall120d63c2010-08-24 20:38:10 +00002671 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002672 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002673}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002674
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002675/// CompareImplicitConversionSequences - Compare two implicit
2676/// conversion sequences to determine whether one is better than the
2677/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00002678static ImplicitConversionSequence::CompareKind
2679CompareImplicitConversionSequences(Sema &S,
2680 const ImplicitConversionSequence& ICS1,
2681 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002682{
2683 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2684 // conversion sequences (as defined in 13.3.3.1)
2685 // -- a standard conversion sequence (13.3.3.1.1) is a better
2686 // conversion sequence than a user-defined conversion sequence or
2687 // an ellipsis conversion sequence, and
2688 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2689 // conversion sequence than an ellipsis conversion sequence
2690 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002691 //
John McCall1d318332010-01-12 00:44:57 +00002692 // C++0x [over.best.ics]p10:
2693 // For the purpose of ranking implicit conversion sequences as
2694 // described in 13.3.3.2, the ambiguous conversion sequence is
2695 // treated as a user-defined sequence that is indistinguishable
2696 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002697 if (ICS1.getKindRank() < ICS2.getKindRank())
2698 return ImplicitConversionSequence::Better;
2699 else if (ICS2.getKindRank() < ICS1.getKindRank())
2700 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002701
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002702 // The following checks require both conversion sequences to be of
2703 // the same kind.
2704 if (ICS1.getKind() != ICS2.getKind())
2705 return ImplicitConversionSequence::Indistinguishable;
2706
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002707 ImplicitConversionSequence::CompareKind Result =
2708 ImplicitConversionSequence::Indistinguishable;
2709
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002710 // Two implicit conversion sequences of the same form are
2711 // indistinguishable conversion sequences unless one of the
2712 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002713 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002714 Result = CompareStandardConversionSequences(S,
2715 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002716 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002717 // User-defined conversion sequence U1 is a better conversion
2718 // sequence than another user-defined conversion sequence U2 if
2719 // they contain the same user-defined conversion function or
2720 // constructor and if the second standard conversion sequence of
2721 // U1 is better than the second standard conversion sequence of
2722 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002723 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002724 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002725 Result = CompareStandardConversionSequences(S,
2726 ICS1.UserDefined.After,
2727 ICS2.UserDefined.After);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002728 }
2729
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002730 // List-initialization sequence L1 is a better conversion sequence than
2731 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
2732 // for some X and L2 does not.
2733 if (Result == ImplicitConversionSequence::Indistinguishable &&
2734 ICS1.isListInitializationSequence() &&
2735 ICS2.isListInitializationSequence()) {
2736 // FIXME: Find out if ICS1 converts to initializer_list and ICS2 doesn't.
2737 }
2738
2739 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002740}
2741
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002742static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2743 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2744 Qualifiers Quals;
2745 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002746 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002747 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002748
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002749 return Context.hasSameUnqualifiedType(T1, T2);
2750}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002751
Douglas Gregorad323a82010-01-27 03:51:04 +00002752// Per 13.3.3.2p3, compare the given standard conversion sequences to
2753// determine if one is a proper subset of the other.
2754static ImplicitConversionSequence::CompareKind
2755compareStandardConversionSubsets(ASTContext &Context,
2756 const StandardConversionSequence& SCS1,
2757 const StandardConversionSequence& SCS2) {
2758 ImplicitConversionSequence::CompareKind Result
2759 = ImplicitConversionSequence::Indistinguishable;
2760
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002761 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002762 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00002763 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2764 return ImplicitConversionSequence::Better;
2765 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2766 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002767
Douglas Gregorad323a82010-01-27 03:51:04 +00002768 if (SCS1.Second != SCS2.Second) {
2769 if (SCS1.Second == ICK_Identity)
2770 Result = ImplicitConversionSequence::Better;
2771 else if (SCS2.Second == ICK_Identity)
2772 Result = ImplicitConversionSequence::Worse;
2773 else
2774 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002775 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002776 return ImplicitConversionSequence::Indistinguishable;
2777
2778 if (SCS1.Third == SCS2.Third) {
2779 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2780 : ImplicitConversionSequence::Indistinguishable;
2781 }
2782
2783 if (SCS1.Third == ICK_Identity)
2784 return Result == ImplicitConversionSequence::Worse
2785 ? ImplicitConversionSequence::Indistinguishable
2786 : ImplicitConversionSequence::Better;
2787
2788 if (SCS2.Third == ICK_Identity)
2789 return Result == ImplicitConversionSequence::Better
2790 ? ImplicitConversionSequence::Indistinguishable
2791 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002792
Douglas Gregorad323a82010-01-27 03:51:04 +00002793 return ImplicitConversionSequence::Indistinguishable;
2794}
2795
Douglas Gregor440a4832011-01-26 14:52:12 +00002796/// \brief Determine whether one of the given reference bindings is better
2797/// than the other based on what kind of bindings they are.
2798static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2799 const StandardConversionSequence &SCS2) {
2800 // C++0x [over.ics.rank]p3b4:
2801 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2802 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002803 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00002804 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002805 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00002806 // reference*.
2807 //
2808 // FIXME: Rvalue references. We're going rogue with the above edits,
2809 // because the semantics in the current C++0x working paper (N3225 at the
2810 // time of this writing) break the standard definition of std::forward
2811 // and std::reference_wrapper when dealing with references to functions.
2812 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00002813 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2814 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2815 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002816
Douglas Gregor440a4832011-01-26 14:52:12 +00002817 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2818 SCS2.IsLvalueReference) ||
2819 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2820 !SCS2.IsLvalueReference);
2821}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002822
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002823/// CompareStandardConversionSequences - Compare two standard
2824/// conversion sequences to determine whether one is better than the
2825/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00002826static ImplicitConversionSequence::CompareKind
2827CompareStandardConversionSequences(Sema &S,
2828 const StandardConversionSequence& SCS1,
2829 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002830{
2831 // Standard conversion sequence S1 is a better conversion sequence
2832 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2833
2834 // -- S1 is a proper subsequence of S2 (comparing the conversion
2835 // sequences in the canonical form defined by 13.3.3.1.1,
2836 // excluding any Lvalue Transformation; the identity conversion
2837 // sequence is considered to be a subsequence of any
2838 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002839 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002840 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002841 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002842
2843 // -- the rank of S1 is better than the rank of S2 (by the rules
2844 // defined below), or, if not that,
2845 ImplicitConversionRank Rank1 = SCS1.getRank();
2846 ImplicitConversionRank Rank2 = SCS2.getRank();
2847 if (Rank1 < Rank2)
2848 return ImplicitConversionSequence::Better;
2849 else if (Rank2 < Rank1)
2850 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002851
Douglas Gregor57373262008-10-22 14:17:15 +00002852 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2853 // are indistinguishable unless one of the following rules
2854 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002855
Douglas Gregor57373262008-10-22 14:17:15 +00002856 // A conversion that is not a conversion of a pointer, or
2857 // pointer to member, to bool is better than another conversion
2858 // that is such a conversion.
2859 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2860 return SCS2.isPointerConversionToBool()
2861 ? ImplicitConversionSequence::Better
2862 : ImplicitConversionSequence::Worse;
2863
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002864 // C++ [over.ics.rank]p4b2:
2865 //
2866 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002867 // conversion of B* to A* is better than conversion of B* to
2868 // void*, and conversion of A* to void* is better than conversion
2869 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002870 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002871 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002872 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002873 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002874 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2875 // Exactly one of the conversion sequences is a conversion to
2876 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002877 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2878 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002879 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2880 // Neither conversion sequence converts to a void pointer; compare
2881 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002882 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00002883 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002884 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00002885 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2886 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002887 // Both conversion sequences are conversions to void
2888 // pointers. Compare the source types to determine if there's an
2889 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00002890 QualType FromType1 = SCS1.getFromType();
2891 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002892
2893 // Adjust the types we're converting from via the array-to-pointer
2894 // conversion, if we need to.
2895 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002896 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002897 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00002898 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002899
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00002900 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
2901 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002902
John McCall120d63c2010-08-24 20:38:10 +00002903 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00002904 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00002905 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00002906 return ImplicitConversionSequence::Worse;
2907
2908 // Objective-C++: If one interface is more specific than the
2909 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00002910 const ObjCObjectPointerType* FromObjCPtr1
2911 = FromType1->getAs<ObjCObjectPointerType>();
2912 const ObjCObjectPointerType* FromObjCPtr2
2913 = FromType2->getAs<ObjCObjectPointerType>();
2914 if (FromObjCPtr1 && FromObjCPtr2) {
2915 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
2916 FromObjCPtr2);
2917 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
2918 FromObjCPtr1);
2919 if (AssignLeft != AssignRight) {
2920 return AssignLeft? ImplicitConversionSequence::Better
2921 : ImplicitConversionSequence::Worse;
2922 }
Douglas Gregor01919692009-12-13 21:37:05 +00002923 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002924 }
Douglas Gregor57373262008-10-22 14:17:15 +00002925
2926 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2927 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00002928 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00002929 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002930 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00002931
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002932 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00002933 // Check for a better reference binding based on the kind of bindings.
2934 if (isBetterReferenceBindingKind(SCS1, SCS2))
2935 return ImplicitConversionSequence::Better;
2936 else if (isBetterReferenceBindingKind(SCS2, SCS1))
2937 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002938
Sebastian Redlf2e21e52009-03-22 23:49:27 +00002939 // C++ [over.ics.rank]p3b4:
2940 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2941 // which the references refer are the same type except for
2942 // top-level cv-qualifiers, and the type to which the reference
2943 // initialized by S2 refers is more cv-qualified than the type
2944 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00002945 QualType T1 = SCS1.getToType(2);
2946 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00002947 T1 = S.Context.getCanonicalType(T1);
2948 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002949 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00002950 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2951 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002952 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00002953 // Objective-C++ ARC: If the references refer to objects with different
2954 // lifetimes, prefer bindings that don't change lifetime.
2955 if (SCS1.ObjCLifetimeConversionBinding !=
2956 SCS2.ObjCLifetimeConversionBinding) {
2957 return SCS1.ObjCLifetimeConversionBinding
2958 ? ImplicitConversionSequence::Worse
2959 : ImplicitConversionSequence::Better;
2960 }
2961
Chandler Carruth6df868e2010-12-12 08:17:55 +00002962 // If the type is an array type, promote the element qualifiers to the
2963 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00002964 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00002965 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00002966 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00002967 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002968 if (T2.isMoreQualifiedThan(T1))
2969 return ImplicitConversionSequence::Better;
2970 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00002971 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002972 }
2973 }
Douglas Gregor57373262008-10-22 14:17:15 +00002974
Francois Pichet1c98d622011-09-18 21:37:37 +00002975 // In Microsoft mode, prefer an integral conversion to a
2976 // floating-to-integral conversion if the integral conversion
2977 // is between types of the same size.
2978 // For example:
2979 // void f(float);
2980 // void f(int);
2981 // int main {
2982 // long a;
2983 // f(a);
2984 // }
2985 // Here, MSVC will call f(int) instead of generating a compile error
2986 // as clang will do in standard mode.
2987 if (S.getLangOptions().MicrosoftMode &&
2988 SCS1.Second == ICK_Integral_Conversion &&
2989 SCS2.Second == ICK_Floating_Integral &&
2990 S.Context.getTypeSize(SCS1.getFromType()) ==
2991 S.Context.getTypeSize(SCS1.getToType(2)))
2992 return ImplicitConversionSequence::Better;
2993
Douglas Gregor57373262008-10-22 14:17:15 +00002994 return ImplicitConversionSequence::Indistinguishable;
2995}
2996
2997/// CompareQualificationConversions - Compares two standard conversion
2998/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00002999/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3000ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003001CompareQualificationConversions(Sema &S,
3002 const StandardConversionSequence& SCS1,
3003 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003004 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003005 // -- S1 and S2 differ only in their qualification conversion and
3006 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3007 // cv-qualification signature of type T1 is a proper subset of
3008 // the cv-qualification signature of type T2, and S1 is not the
3009 // deprecated string literal array-to-pointer conversion (4.2).
3010 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3011 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3012 return ImplicitConversionSequence::Indistinguishable;
3013
3014 // FIXME: the example in the standard doesn't use a qualification
3015 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003016 QualType T1 = SCS1.getToType(2);
3017 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003018 T1 = S.Context.getCanonicalType(T1);
3019 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003020 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003021 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3022 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003023
3024 // If the types are the same, we won't learn anything by unwrapped
3025 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003026 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003027 return ImplicitConversionSequence::Indistinguishable;
3028
Chandler Carruth28e318c2009-12-29 07:16:59 +00003029 // If the type is an array type, promote the element qualifiers to the type
3030 // for comparison.
3031 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003032 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003033 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003034 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003035
Mike Stump1eb44332009-09-09 15:08:12 +00003036 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003037 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003038
3039 // Objective-C++ ARC:
3040 // Prefer qualification conversions not involving a change in lifetime
3041 // to qualification conversions that do not change lifetime.
3042 if (SCS1.QualificationIncludesObjCLifetime !=
3043 SCS2.QualificationIncludesObjCLifetime) {
3044 Result = SCS1.QualificationIncludesObjCLifetime
3045 ? ImplicitConversionSequence::Worse
3046 : ImplicitConversionSequence::Better;
3047 }
3048
John McCall120d63c2010-08-24 20:38:10 +00003049 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003050 // Within each iteration of the loop, we check the qualifiers to
3051 // determine if this still looks like a qualification
3052 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003053 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003054 // until there are no more pointers or pointers-to-members left
3055 // to unwrap. This essentially mimics what
3056 // IsQualificationConversion does, but here we're checking for a
3057 // strict subset of qualifiers.
3058 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3059 // The qualifiers are the same, so this doesn't tell us anything
3060 // about how the sequences rank.
3061 ;
3062 else if (T2.isMoreQualifiedThan(T1)) {
3063 // T1 has fewer qualifiers, so it could be the better sequence.
3064 if (Result == ImplicitConversionSequence::Worse)
3065 // Neither has qualifiers that are a subset of the other's
3066 // qualifiers.
3067 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003068
Douglas Gregor57373262008-10-22 14:17:15 +00003069 Result = ImplicitConversionSequence::Better;
3070 } else if (T1.isMoreQualifiedThan(T2)) {
3071 // T2 has fewer qualifiers, so it could be the better sequence.
3072 if (Result == ImplicitConversionSequence::Better)
3073 // Neither has qualifiers that are a subset of the other's
3074 // qualifiers.
3075 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003076
Douglas Gregor57373262008-10-22 14:17:15 +00003077 Result = ImplicitConversionSequence::Worse;
3078 } else {
3079 // Qualifiers are disjoint.
3080 return ImplicitConversionSequence::Indistinguishable;
3081 }
3082
3083 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003084 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003085 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003086 }
3087
Douglas Gregor57373262008-10-22 14:17:15 +00003088 // Check that the winning standard conversion sequence isn't using
3089 // the deprecated string literal array to pointer conversion.
3090 switch (Result) {
3091 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003092 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003093 Result = ImplicitConversionSequence::Indistinguishable;
3094 break;
3095
3096 case ImplicitConversionSequence::Indistinguishable:
3097 break;
3098
3099 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003100 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003101 Result = ImplicitConversionSequence::Indistinguishable;
3102 break;
3103 }
3104
3105 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003106}
3107
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003108/// CompareDerivedToBaseConversions - Compares two standard conversion
3109/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003110/// various kinds of derived-to-base conversions (C++
3111/// [over.ics.rank]p4b3). As part of these checks, we also look at
3112/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003113ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003114CompareDerivedToBaseConversions(Sema &S,
3115 const StandardConversionSequence& SCS1,
3116 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003117 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003118 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003119 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003120 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003121
3122 // Adjust the types we're converting from via the array-to-pointer
3123 // conversion, if we need to.
3124 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003125 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003126 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003127 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003128
3129 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003130 FromType1 = S.Context.getCanonicalType(FromType1);
3131 ToType1 = S.Context.getCanonicalType(ToType1);
3132 FromType2 = S.Context.getCanonicalType(FromType2);
3133 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003134
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003135 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003136 //
3137 // If class B is derived directly or indirectly from class A and
3138 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003139 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003140 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003141 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003142 SCS2.Second == ICK_Pointer_Conversion &&
3143 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3144 FromType1->isPointerType() && FromType2->isPointerType() &&
3145 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003146 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003147 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003148 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003149 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003150 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003151 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003152 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003153 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003154
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003155 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003156 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003157 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003158 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003159 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003160 return ImplicitConversionSequence::Worse;
3161 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003162
3163 // -- conversion of B* to A* is better than conversion of C* to A*,
3164 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003165 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003166 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003167 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003168 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003169 }
3170 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3171 SCS2.Second == ICK_Pointer_Conversion) {
3172 const ObjCObjectPointerType *FromPtr1
3173 = FromType1->getAs<ObjCObjectPointerType>();
3174 const ObjCObjectPointerType *FromPtr2
3175 = FromType2->getAs<ObjCObjectPointerType>();
3176 const ObjCObjectPointerType *ToPtr1
3177 = ToType1->getAs<ObjCObjectPointerType>();
3178 const ObjCObjectPointerType *ToPtr2
3179 = ToType2->getAs<ObjCObjectPointerType>();
3180
3181 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3182 // Apply the same conversion ranking rules for Objective-C pointer types
3183 // that we do for C++ pointers to class types. However, we employ the
3184 // Objective-C pseudo-subtyping relationship used for assignment of
3185 // Objective-C pointer types.
3186 bool FromAssignLeft
3187 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3188 bool FromAssignRight
3189 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3190 bool ToAssignLeft
3191 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3192 bool ToAssignRight
3193 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3194
3195 // A conversion to an a non-id object pointer type or qualified 'id'
3196 // type is better than a conversion to 'id'.
3197 if (ToPtr1->isObjCIdType() &&
3198 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3199 return ImplicitConversionSequence::Worse;
3200 if (ToPtr2->isObjCIdType() &&
3201 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3202 return ImplicitConversionSequence::Better;
3203
3204 // A conversion to a non-id object pointer type is better than a
3205 // conversion to a qualified 'id' type
3206 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3207 return ImplicitConversionSequence::Worse;
3208 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3209 return ImplicitConversionSequence::Better;
3210
3211 // A conversion to an a non-Class object pointer type or qualified 'Class'
3212 // type is better than a conversion to 'Class'.
3213 if (ToPtr1->isObjCClassType() &&
3214 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3215 return ImplicitConversionSequence::Worse;
3216 if (ToPtr2->isObjCClassType() &&
3217 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3218 return ImplicitConversionSequence::Better;
3219
3220 // A conversion to a non-Class object pointer type is better than a
3221 // conversion to a qualified 'Class' type.
3222 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3223 return ImplicitConversionSequence::Worse;
3224 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3225 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003226
Douglas Gregor395cc372011-01-31 18:51:41 +00003227 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3228 if (S.Context.hasSameType(FromType1, FromType2) &&
3229 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3230 (ToAssignLeft != ToAssignRight))
3231 return ToAssignLeft? ImplicitConversionSequence::Worse
3232 : ImplicitConversionSequence::Better;
3233
3234 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3235 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3236 (FromAssignLeft != FromAssignRight))
3237 return FromAssignLeft? ImplicitConversionSequence::Better
3238 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003239 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003240 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003241
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003242 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003243 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3244 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3245 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003246 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003247 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003248 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003249 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003250 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003251 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003252 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003253 ToType2->getAs<MemberPointerType>();
3254 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3255 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3256 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3257 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3258 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3259 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3260 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3261 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003262 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003263 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003264 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003265 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003266 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003267 return ImplicitConversionSequence::Better;
3268 }
3269 // conversion of B::* to C::* is better than conversion of A::* to C::*
3270 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003271 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003272 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003273 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003274 return ImplicitConversionSequence::Worse;
3275 }
3276 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003277
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003278 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003279 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003280 // -- binding of an expression of type C to a reference of type
3281 // B& is better than binding an expression of type C to a
3282 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003283 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3284 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3285 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003286 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003287 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003288 return ImplicitConversionSequence::Worse;
3289 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003290
Douglas Gregor225c41e2008-11-03 19:09:14 +00003291 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003292 // -- binding of an expression of type B to a reference of type
3293 // A& is better than binding an expression of type C to a
3294 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003295 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3296 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3297 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003298 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003299 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003300 return ImplicitConversionSequence::Worse;
3301 }
3302 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003303
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003304 return ImplicitConversionSequence::Indistinguishable;
3305}
3306
Douglas Gregorabe183d2010-04-13 16:31:36 +00003307/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3308/// determine whether they are reference-related,
3309/// reference-compatible, reference-compatible with added
3310/// qualification, or incompatible, for use in C++ initialization by
3311/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3312/// type, and the first type (T1) is the pointee type of the reference
3313/// type being initialized.
3314Sema::ReferenceCompareResult
3315Sema::CompareReferenceRelationship(SourceLocation Loc,
3316 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003317 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003318 bool &ObjCConversion,
3319 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003320 assert(!OrigT1->isReferenceType() &&
3321 "T1 must be the pointee type of the reference type");
3322 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3323
3324 QualType T1 = Context.getCanonicalType(OrigT1);
3325 QualType T2 = Context.getCanonicalType(OrigT2);
3326 Qualifiers T1Quals, T2Quals;
3327 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3328 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3329
3330 // C++ [dcl.init.ref]p4:
3331 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3332 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3333 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003334 DerivedToBase = false;
3335 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003336 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003337 if (UnqualT1 == UnqualT2) {
3338 // Nothing to do.
3339 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003340 IsDerivedFrom(UnqualT2, UnqualT1))
3341 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003342 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3343 UnqualT2->isObjCObjectOrInterfaceType() &&
3344 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3345 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003346 else
3347 return Ref_Incompatible;
3348
3349 // At this point, we know that T1 and T2 are reference-related (at
3350 // least).
3351
3352 // If the type is an array type, promote the element qualifiers to the type
3353 // for comparison.
3354 if (isa<ArrayType>(T1) && T1Quals)
3355 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3356 if (isa<ArrayType>(T2) && T2Quals)
3357 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3358
3359 // C++ [dcl.init.ref]p4:
3360 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3361 // reference-related to T2 and cv1 is the same cv-qualification
3362 // as, or greater cv-qualification than, cv2. For purposes of
3363 // overload resolution, cases for which cv1 is greater
3364 // cv-qualification than cv2 are identified as
3365 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003366 //
3367 // Note that we also require equivalence of Objective-C GC and address-space
3368 // qualifiers when performing these computations, so that e.g., an int in
3369 // address space 1 is not reference-compatible with an int in address
3370 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003371 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3372 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3373 T1Quals.removeObjCLifetime();
3374 T2Quals.removeObjCLifetime();
3375 ObjCLifetimeConversion = true;
3376 }
3377
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003378 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003379 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003380 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003381 return Ref_Compatible_With_Added_Qualification;
3382 else
3383 return Ref_Related;
3384}
3385
Douglas Gregor604eb652010-08-11 02:15:33 +00003386/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003387/// with DeclType. Return true if something definite is found.
3388static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003389FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3390 QualType DeclType, SourceLocation DeclLoc,
3391 Expr *Init, QualType T2, bool AllowRvalues,
3392 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003393 assert(T2->isRecordType() && "Can only find conversions of record types.");
3394 CXXRecordDecl *T2RecordDecl
3395 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3396
3397 OverloadCandidateSet CandidateSet(DeclLoc);
3398 const UnresolvedSetImpl *Conversions
3399 = T2RecordDecl->getVisibleConversionFunctions();
3400 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3401 E = Conversions->end(); I != E; ++I) {
3402 NamedDecl *D = *I;
3403 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3404 if (isa<UsingShadowDecl>(D))
3405 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3406
3407 FunctionTemplateDecl *ConvTemplate
3408 = dyn_cast<FunctionTemplateDecl>(D);
3409 CXXConversionDecl *Conv;
3410 if (ConvTemplate)
3411 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3412 else
3413 Conv = cast<CXXConversionDecl>(D);
3414
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003415 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003416 // explicit conversions, skip it.
3417 if (!AllowExplicit && Conv->isExplicit())
3418 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003419
Douglas Gregor604eb652010-08-11 02:15:33 +00003420 if (AllowRvalues) {
3421 bool DerivedToBase = false;
3422 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003423 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003424
3425 // If we are initializing an rvalue reference, don't permit conversion
3426 // functions that return lvalues.
3427 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3428 const ReferenceType *RefType
3429 = Conv->getConversionType()->getAs<LValueReferenceType>();
3430 if (RefType && !RefType->getPointeeType()->isFunctionType())
3431 continue;
3432 }
3433
Douglas Gregor604eb652010-08-11 02:15:33 +00003434 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003435 S.CompareReferenceRelationship(
3436 DeclLoc,
3437 Conv->getConversionType().getNonReferenceType()
3438 .getUnqualifiedType(),
3439 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00003440 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00003441 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00003442 continue;
3443 } else {
3444 // If the conversion function doesn't return a reference type,
3445 // it can't be considered for this conversion. An rvalue reference
3446 // is only acceptable if its referencee is a function type.
3447
3448 const ReferenceType *RefType =
3449 Conv->getConversionType()->getAs<ReferenceType>();
3450 if (!RefType ||
3451 (!RefType->isLValueReferenceType() &&
3452 !RefType->getPointeeType()->isFunctionType()))
3453 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003454 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003455
Douglas Gregor604eb652010-08-11 02:15:33 +00003456 if (ConvTemplate)
3457 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003458 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00003459 else
3460 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003461 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003462 }
3463
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003464 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3465
Sebastian Redl4680bf22010-06-30 18:13:39 +00003466 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003467 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003468 case OR_Success:
3469 // C++ [over.ics.ref]p1:
3470 //
3471 // [...] If the parameter binds directly to the result of
3472 // applying a conversion function to the argument
3473 // expression, the implicit conversion sequence is a
3474 // user-defined conversion sequence (13.3.3.1.2), with the
3475 // second standard conversion sequence either an identity
3476 // conversion or, if the conversion function returns an
3477 // entity of a type that is a derived class of the parameter
3478 // type, a derived-to-base Conversion.
3479 if (!Best->FinalConversion.DirectBinding)
3480 return false;
3481
Chandler Carruth25ca4212011-02-25 19:41:05 +00003482 if (Best->Function)
3483 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003484 ICS.setUserDefined();
3485 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3486 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003487 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003488 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00003489 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003490 ICS.UserDefined.EllipsisConversion = false;
3491 assert(ICS.UserDefined.After.ReferenceBinding &&
3492 ICS.UserDefined.After.DirectBinding &&
3493 "Expected a direct reference binding!");
3494 return true;
3495
3496 case OR_Ambiguous:
3497 ICS.setAmbiguous();
3498 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3499 Cand != CandidateSet.end(); ++Cand)
3500 if (Cand->Viable)
3501 ICS.Ambiguous.addConversion(Cand->Function);
3502 return true;
3503
3504 case OR_No_Viable_Function:
3505 case OR_Deleted:
3506 // There was no suitable conversion, or we found a deleted
3507 // conversion; continue with other checks.
3508 return false;
3509 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003510
Eric Christopher1c3d5022010-06-30 18:36:32 +00003511 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003512}
3513
Douglas Gregorabe183d2010-04-13 16:31:36 +00003514/// \brief Compute an implicit conversion sequence for reference
3515/// initialization.
3516static ImplicitConversionSequence
3517TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
3518 SourceLocation DeclLoc,
3519 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003520 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003521 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3522
3523 // Most paths end in a failed conversion.
3524 ImplicitConversionSequence ICS;
3525 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3526
3527 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3528 QualType T2 = Init->getType();
3529
3530 // If the initializer is the address of an overloaded function, try
3531 // to resolve the overloaded function. If all goes well, T2 is the
3532 // type of the resulting function.
3533 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3534 DeclAccessPair Found;
3535 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3536 false, Found))
3537 T2 = Fn->getType();
3538 }
3539
3540 // Compute some basic properties of the types and the initializer.
3541 bool isRValRef = DeclType->isRValueReferenceType();
3542 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003543 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003544 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003545 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003546 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003547 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003548 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003549
Douglas Gregorabe183d2010-04-13 16:31:36 +00003550
Sebastian Redl4680bf22010-06-30 18:13:39 +00003551 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00003552 // A reference to type "cv1 T1" is initialized by an expression
3553 // of type "cv2 T2" as follows:
3554
Sebastian Redl4680bf22010-06-30 18:13:39 +00003555 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003556 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003557 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3558 // reference-compatible with "cv2 T2," or
3559 //
3560 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3561 if (InitCategory.isLValue() &&
3562 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003563 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00003564 // When a parameter of reference type binds directly (8.5.3)
3565 // to an argument expression, the implicit conversion sequence
3566 // is the identity conversion, unless the argument expression
3567 // has a type that is a derived class of the parameter type,
3568 // in which case the implicit conversion sequence is a
3569 // derived-to-base Conversion (13.3.3.1).
3570 ICS.setStandard();
3571 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00003572 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3573 : ObjCConversion? ICK_Compatible_Conversion
3574 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003575 ICS.Standard.Third = ICK_Identity;
3576 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3577 ICS.Standard.setToType(0, T2);
3578 ICS.Standard.setToType(1, T1);
3579 ICS.Standard.setToType(2, T1);
3580 ICS.Standard.ReferenceBinding = true;
3581 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003582 ICS.Standard.IsLvalueReference = !isRValRef;
3583 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3584 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003585 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003586 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003587 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003588
Sebastian Redl4680bf22010-06-30 18:13:39 +00003589 // Nothing more to do: the inaccessibility/ambiguity check for
3590 // derived-to-base conversions is suppressed when we're
3591 // computing the implicit conversion sequence (C++
3592 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00003593 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003594 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00003595
Sebastian Redl4680bf22010-06-30 18:13:39 +00003596 // -- has a class type (i.e., T2 is a class type), where T1 is
3597 // not reference-related to T2, and can be implicitly
3598 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3599 // is reference-compatible with "cv3 T3" 92) (this
3600 // conversion is selected by enumerating the applicable
3601 // conversion functions (13.3.1.6) and choosing the best
3602 // one through overload resolution (13.3)),
3603 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003604 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00003605 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00003606 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3607 Init, T2, /*AllowRvalues=*/false,
3608 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00003609 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003610 }
3611 }
3612
Sebastian Redl4680bf22010-06-30 18:13:39 +00003613 // -- Otherwise, the reference shall be an lvalue reference to a
3614 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003615 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003616 //
Douglas Gregor66821b52010-04-18 09:22:00 +00003617 // We actually handle one oddity of C++ [over.ics.ref] at this
3618 // point, which is that, due to p2 (which short-circuits reference
3619 // binding by only attempting a simple conversion for non-direct
3620 // bindings) and p3's strange wording, we allow a const volatile
3621 // reference to bind to an rvalue. Hence the check for the presence
3622 // of "const" rather than checking for "const" being the only
3623 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00003624 // This is also the point where rvalue references and lvalue inits no longer
3625 // go together.
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003626 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00003627 return ICS;
3628
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003629 // -- If the initializer expression
3630 //
3631 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00003632 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003633 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3634 (InitCategory.isXValue() ||
3635 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3636 (InitCategory.isLValue() && T2->isFunctionType()))) {
3637 ICS.setStandard();
3638 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003639 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003640 : ObjCConversion? ICK_Compatible_Conversion
3641 : ICK_Identity;
3642 ICS.Standard.Third = ICK_Identity;
3643 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3644 ICS.Standard.setToType(0, T2);
3645 ICS.Standard.setToType(1, T1);
3646 ICS.Standard.setToType(2, T1);
3647 ICS.Standard.ReferenceBinding = true;
3648 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3649 // binding unless we're binding to a class prvalue.
3650 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3651 // allow the use of rvalue references in C++98/03 for the benefit of
3652 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003653 ICS.Standard.DirectBinding =
3654 S.getLangOptions().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003655 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00003656 ICS.Standard.IsLvalueReference = !isRValRef;
3657 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003658 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003659 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003660 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003661 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003662 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003663 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003664
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003665 // -- has a class type (i.e., T2 is a class type), where T1 is not
3666 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003667 // an xvalue, class prvalue, or function lvalue of type
3668 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003669 // "cv3 T3",
3670 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003671 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003672 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003673 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003674 // class subobject).
3675 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003676 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003677 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3678 Init, T2, /*AllowRvalues=*/true,
3679 AllowExplicit)) {
3680 // In the second case, if the reference is an rvalue reference
3681 // and the second standard conversion sequence of the
3682 // user-defined conversion sequence includes an lvalue-to-rvalue
3683 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003684 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003685 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3686 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3687
Douglas Gregor68ed68b2011-01-21 16:36:05 +00003688 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00003689 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003690
Douglas Gregorabe183d2010-04-13 16:31:36 +00003691 // -- Otherwise, a temporary of type "cv1 T1" is created and
3692 // initialized from the initializer expression using the
3693 // rules for a non-reference copy initialization (8.5). The
3694 // reference is then bound to the temporary. If T1 is
3695 // reference-related to T2, cv1 must be the same
3696 // cv-qualification as, or greater cv-qualification than,
3697 // cv2; otherwise, the program is ill-formed.
3698 if (RefRelationship == Sema::Ref_Related) {
3699 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3700 // we would be reference-compatible or reference-compatible with
3701 // added qualification. But that wasn't the case, so the reference
3702 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00003703 //
3704 // Note that we only want to check address spaces and cvr-qualifiers here.
3705 // ObjC GC and lifetime qualifiers aren't important.
3706 Qualifiers T1Quals = T1.getQualifiers();
3707 Qualifiers T2Quals = T2.getQualifiers();
3708 T1Quals.removeObjCGCAttr();
3709 T1Quals.removeObjCLifetime();
3710 T2Quals.removeObjCGCAttr();
3711 T2Quals.removeObjCLifetime();
3712 if (!T1Quals.compatiblyIncludes(T2Quals))
3713 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003714 }
3715
3716 // If at least one of the types is a class type, the types are not
3717 // related, and we aren't allowed any user conversions, the
3718 // reference binding fails. This case is important for breaking
3719 // recursion, since TryImplicitConversion below will attempt to
3720 // create a temporary through the use of a copy constructor.
3721 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3722 (T1->isRecordType() || T2->isRecordType()))
3723 return ICS;
3724
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003725 // If T1 is reference-related to T2 and the reference is an rvalue
3726 // reference, the initializer expression shall not be an lvalue.
3727 if (RefRelationship >= Sema::Ref_Related &&
3728 isRValRef && Init->Classify(S.Context).isLValue())
3729 return ICS;
3730
Douglas Gregorabe183d2010-04-13 16:31:36 +00003731 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00003732 // When a parameter of reference type is not bound directly to
3733 // an argument expression, the conversion sequence is the one
3734 // required to convert the argument expression to the
3735 // underlying type of the reference according to
3736 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3737 // to copy-initializing a temporary of the underlying type with
3738 // the argument expression. Any difference in top-level
3739 // cv-qualification is subsumed by the initialization itself
3740 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00003741 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3742 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003743 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003744 /*CStyle=*/false,
3745 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003746
3747 // Of course, that's still a reference binding.
3748 if (ICS.isStandard()) {
3749 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003750 ICS.Standard.IsLvalueReference = !isRValRef;
3751 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3752 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003753 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003754 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003755 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00003756 // Don't allow rvalue references to bind to lvalues.
3757 if (DeclType->isRValueReferenceType()) {
3758 if (const ReferenceType *RefType
3759 = ICS.UserDefined.ConversionFunction->getResultType()
3760 ->getAs<LValueReferenceType>()) {
3761 if (!RefType->getPointeeType()->isFunctionType()) {
3762 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
3763 DeclType);
3764 return ICS;
3765 }
3766 }
3767 }
3768
Douglas Gregorabe183d2010-04-13 16:31:36 +00003769 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00003770 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3771 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3772 ICS.UserDefined.After.BindsToRvalue = true;
3773 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3774 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003775 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003776
Douglas Gregorabe183d2010-04-13 16:31:36 +00003777 return ICS;
3778}
3779
Sebastian Redl5405b812011-10-16 18:19:34 +00003780static ImplicitConversionSequence
3781TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
3782 bool SuppressUserConversions,
3783 bool InOverloadResolution,
3784 bool AllowObjCWritebackConversion);
3785
3786/// TryListConversion - Try to copy-initialize a value of type ToType from the
3787/// initializer list From.
3788static ImplicitConversionSequence
3789TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
3790 bool SuppressUserConversions,
3791 bool InOverloadResolution,
3792 bool AllowObjCWritebackConversion) {
3793 // C++11 [over.ics.list]p1:
3794 // When an argument is an initializer list, it is not an expression and
3795 // special rules apply for converting it to a parameter type.
3796
3797 ImplicitConversionSequence Result;
3798 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003799 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00003800
3801 // C++11 [over.ics.list]p2:
3802 // If the parameter type is std::initializer_list<X> or "array of X" and
3803 // all the elements can be implicitly converted to X, the implicit
3804 // conversion sequence is the worst conversion necessary to convert an
3805 // element of the list to X.
3806 // FIXME: Recognize std::initializer_list.
3807 // FIXME: Arrays don't make sense until we can deal with references.
3808 if (ToType->isArrayType())
3809 return Result;
3810
3811 // C++11 [over.ics.list]p3:
3812 // Otherwise, if the parameter is a non-aggregate class X and overload
3813 // resolution chooses a single best constructor [...] the implicit
3814 // conversion sequence is a user-defined conversion sequence. If multiple
3815 // constructors are viable but none is better than the others, the
3816 // implicit conversion sequence is a user-defined conversion sequence.
3817 // FIXME: Implement this.
3818 if (ToType->isRecordType() && !ToType->isAggregateType())
3819 return Result;
3820
3821 // C++11 [over.ics.list]p4:
3822 // Otherwise, if the parameter has an aggregate type which can be
3823 // initialized from the initializer list [...] the implicit conversion
3824 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00003825 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003826 // Type is an aggregate, argument is an init list. At this point it comes
3827 // down to checking whether the initialization works.
3828 // FIXME: Find out whether this parameter is consumed or not.
3829 InitializedEntity Entity =
3830 InitializedEntity::InitializeParameter(S.Context, ToType,
3831 /*Consumed=*/false);
3832 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
3833 Result.setUserDefined();
3834 Result.UserDefined.Before.setAsIdentityConversion();
3835 // Initializer lists don't have a type.
3836 Result.UserDefined.Before.setFromType(QualType());
3837 Result.UserDefined.Before.setAllToTypes(QualType());
3838
3839 Result.UserDefined.After.setAsIdentityConversion();
3840 Result.UserDefined.After.setFromType(ToType);
3841 Result.UserDefined.After.setAllToTypes(ToType);
3842 }
Sebastian Redl5405b812011-10-16 18:19:34 +00003843 return Result;
3844 }
3845
3846 // C++11 [over.ics.list]p5:
3847 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
3848 // FIXME: Implement this.
3849 if (ToType->isReferenceType())
3850 return Result;
3851
3852 // C++11 [over.ics.list]p6:
3853 // Otherwise, if the parameter type is not a class:
3854 if (!ToType->isRecordType()) {
3855 // - if the initializer list has one element, the implicit conversion
3856 // sequence is the one required to convert the element to the
3857 // parameter type.
3858 // FIXME: Catch narrowing here?
3859 unsigned NumInits = From->getNumInits();
3860 if (NumInits == 1)
3861 Result = TryCopyInitialization(S, From->getInit(0), ToType,
3862 SuppressUserConversions,
3863 InOverloadResolution,
3864 AllowObjCWritebackConversion);
3865 // - if the initializer list has no elements, the implicit conversion
3866 // sequence is the identity conversion.
3867 else if (NumInits == 0) {
3868 Result.setStandard();
3869 Result.Standard.setAsIdentityConversion();
3870 }
3871 return Result;
3872 }
3873
3874 // C++11 [over.ics.list]p7:
3875 // In all cases other than those enumerated above, no conversion is possible
3876 return Result;
3877}
3878
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003879/// TryCopyInitialization - Try to copy-initialize a value of type
3880/// ToType from the expression From. Return the implicit conversion
3881/// sequence required to pass this argument, which may be a bad
3882/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00003883/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00003884/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00003885static ImplicitConversionSequence
3886TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003887 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00003888 bool InOverloadResolution,
3889 bool AllowObjCWritebackConversion) {
Sebastian Redl5405b812011-10-16 18:19:34 +00003890 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
3891 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
3892 InOverloadResolution,AllowObjCWritebackConversion);
3893
Douglas Gregorabe183d2010-04-13 16:31:36 +00003894 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00003895 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003896 /*FIXME:*/From->getLocStart(),
3897 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003898 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003899
John McCall120d63c2010-08-24 20:38:10 +00003900 return TryImplicitConversion(S, From, ToType,
3901 SuppressUserConversions,
3902 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003903 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00003904 /*CStyle=*/false,
3905 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00003906}
3907
Anna Zaksf3546ee2011-07-28 19:46:48 +00003908static bool TryCopyInitialization(const CanQualType FromQTy,
3909 const CanQualType ToQTy,
3910 Sema &S,
3911 SourceLocation Loc,
3912 ExprValueKind FromVK) {
3913 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
3914 ImplicitConversionSequence ICS =
3915 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
3916
3917 return !ICS.isBad();
3918}
3919
Douglas Gregor96176b32008-11-18 23:14:02 +00003920/// TryObjectArgumentInitialization - Try to initialize the object
3921/// parameter of the given member function (@c Method) from the
3922/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00003923static ImplicitConversionSequence
3924TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003925 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00003926 CXXMethodDecl *Method,
3927 CXXRecordDecl *ActingContext) {
3928 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00003929 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3930 // const volatile object.
3931 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3932 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00003933 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00003934
3935 // Set up the conversion sequence as a "bad" conversion, to allow us
3936 // to exit early.
3937 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00003938
3939 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00003940 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003941 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00003942 FromType = PT->getPointeeType();
3943
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003944 // When we had a pointer, it's implicitly dereferenced, so we
3945 // better have an lvalue.
3946 assert(FromClassification.isLValue());
3947 }
3948
Anders Carlssona552f7c2009-05-01 18:34:30 +00003949 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00003950
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003951 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003952 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003953 // parameter is
3954 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00003955 // - "lvalue reference to cv X" for functions declared without a
3956 // ref-qualifier or with the & ref-qualifier
3957 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003958 // ref-qualifier
3959 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003960 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003961 // cv-qualification on the member function declaration.
3962 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003963 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003964 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00003965 // (C++ [over.match.funcs]p5). We perform a simplified version of
3966 // reference binding here, that allows class rvalues to bind to
3967 // non-constant references.
3968
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003969 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00003970 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003971 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00003972 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00003973 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00003974 ICS.setBad(BadConversionSequence::bad_qualifiers,
3975 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003976 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003977 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003978
3979 // Check that we have either the same type or a derived type. It
3980 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00003981 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00003982 ImplicitConversionKind SecondKind;
3983 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3984 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00003985 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00003986 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00003987 else {
John McCallb1bdc622010-02-25 01:37:24 +00003988 ICS.setBad(BadConversionSequence::unrelated_class,
3989 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00003990 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00003991 }
Douglas Gregor96176b32008-11-18 23:14:02 +00003992
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003993 // Check the ref-qualifier.
3994 switch (Method->getRefQualifier()) {
3995 case RQ_None:
3996 // Do nothing; we don't care about lvalueness or rvalueness.
3997 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003998
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00003999 case RQ_LValue:
4000 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4001 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004002 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004003 ImplicitParamType);
4004 return ICS;
4005 }
4006 break;
4007
4008 case RQ_RValue:
4009 if (!FromClassification.isRValue()) {
4010 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004011 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004012 ImplicitParamType);
4013 return ICS;
4014 }
4015 break;
4016 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004017
Douglas Gregor96176b32008-11-18 23:14:02 +00004018 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004019 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004020 ICS.Standard.setAsIdentityConversion();
4021 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004022 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004023 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004024 ICS.Standard.ReferenceBinding = true;
4025 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004026 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004027 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004028 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4029 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4030 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004031 return ICS;
4032}
4033
4034/// PerformObjectArgumentInitialization - Perform initialization of
4035/// the implicit object parameter for the given Method with the given
4036/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004037ExprResult
4038Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004039 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004040 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004041 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004042 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004043 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004044 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004045
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004046 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004047 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004048 FromRecordType = PT->getPointeeType();
4049 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004050 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004051 } else {
4052 FromRecordType = From->getType();
4053 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004054 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004055 }
4056
John McCall701c89e2009-12-03 04:06:58 +00004057 // Note that we always use the true parent context when performing
4058 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004059 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004060 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4061 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004062 if (ICS.isBad()) {
4063 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4064 Qualifiers FromQs = FromRecordType.getQualifiers();
4065 Qualifiers ToQs = DestType.getQualifiers();
4066 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4067 if (CVR) {
4068 Diag(From->getSourceRange().getBegin(),
4069 diag::err_member_function_call_bad_cvr)
4070 << Method->getDeclName() << FromRecordType << (CVR - 1)
4071 << From->getSourceRange();
4072 Diag(Method->getLocation(), diag::note_previous_decl)
4073 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004074 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004075 }
4076 }
4077
Douglas Gregor96176b32008-11-18 23:14:02 +00004078 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004079 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004080 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004081 }
Mike Stump1eb44332009-09-09 15:08:12 +00004082
John Wiegley429bb272011-04-08 18:41:53 +00004083 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4084 ExprResult FromRes =
4085 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4086 if (FromRes.isInvalid())
4087 return ExprError();
4088 From = FromRes.take();
4089 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004090
Douglas Gregor5fccd362010-03-03 23:55:11 +00004091 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004092 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004093 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004094 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004095}
4096
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004097/// TryContextuallyConvertToBool - Attempt to contextually convert the
4098/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004099static ImplicitConversionSequence
4100TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004101 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004102 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004103 // FIXME: Are these flags correct?
4104 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004105 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004106 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004107 /*CStyle=*/false,
4108 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004109}
4110
4111/// PerformContextuallyConvertToBool - Perform a contextual conversion
4112/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004113ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004114 if (checkPlaceholderForOverload(*this, From))
4115 return ExprError();
4116
John McCall120d63c2010-08-24 20:38:10 +00004117 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004118 if (!ICS.isBad())
4119 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004120
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004121 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall864c0412011-04-26 20:42:42 +00004122 return Diag(From->getSourceRange().getBegin(),
4123 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004124 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004125 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004126}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004127
John McCall0bcc9bc2011-09-09 06:11:02 +00004128/// dropPointerConversions - If the given standard conversion sequence
4129/// involves any pointer conversions, remove them. This may change
4130/// the result type of the conversion sequence.
4131static void dropPointerConversion(StandardConversionSequence &SCS) {
4132 if (SCS.Second == ICK_Pointer_Conversion) {
4133 SCS.Second = ICK_Identity;
4134 SCS.Third = ICK_Identity;
4135 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4136 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004137}
John McCall120d63c2010-08-24 20:38:10 +00004138
John McCall0bcc9bc2011-09-09 06:11:02 +00004139/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4140/// convert the expression From to an Objective-C pointer type.
4141static ImplicitConversionSequence
4142TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4143 // Do an implicit conversion to 'id'.
4144 QualType Ty = S.Context.getObjCIdType();
4145 ImplicitConversionSequence ICS
4146 = TryImplicitConversion(S, From, Ty,
4147 // FIXME: Are these flags correct?
4148 /*SuppressUserConversions=*/false,
4149 /*AllowExplicit=*/true,
4150 /*InOverloadResolution=*/false,
4151 /*CStyle=*/false,
4152 /*AllowObjCWritebackConversion=*/false);
4153
4154 // Strip off any final conversions to 'id'.
4155 switch (ICS.getKind()) {
4156 case ImplicitConversionSequence::BadConversion:
4157 case ImplicitConversionSequence::AmbiguousConversion:
4158 case ImplicitConversionSequence::EllipsisConversion:
4159 break;
4160
4161 case ImplicitConversionSequence::UserDefinedConversion:
4162 dropPointerConversion(ICS.UserDefined.After);
4163 break;
4164
4165 case ImplicitConversionSequence::StandardConversion:
4166 dropPointerConversion(ICS.Standard);
4167 break;
4168 }
4169
4170 return ICS;
4171}
4172
4173/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4174/// conversion of the expression From to an Objective-C pointer type.
4175ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004176 if (checkPlaceholderForOverload(*this, From))
4177 return ExprError();
4178
John McCallc12c5bb2010-05-15 11:32:37 +00004179 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00004180 ImplicitConversionSequence ICS =
4181 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004182 if (!ICS.isBad())
4183 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00004184 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004185}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004186
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004187/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00004188/// enumeration type.
4189///
4190/// This routine will attempt to convert an expression of class type to an
4191/// integral or enumeration type, if that class type only has a single
4192/// conversion to an integral or enumeration type.
4193///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004194/// \param Loc The source location of the construct that requires the
4195/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00004196///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004197/// \param FromE The expression we're converting from.
4198///
4199/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4200/// have integral or enumeration type.
4201///
4202/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4203/// incomplete class type.
4204///
4205/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4206/// explicit conversion function (because no implicit conversion functions
4207/// were available). This is a recovery mode.
4208///
4209/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4210/// showing which conversion was picked.
4211///
4212/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4213/// conversion function that could convert to integral or enumeration type.
4214///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004215/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004216/// usable conversion function.
4217///
4218/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4219/// function, which may be an extension in this case.
4220///
4221/// \returns The expression, converted to an integral or enumeration type if
4222/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004223ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004224Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00004225 const PartialDiagnostic &NotIntDiag,
4226 const PartialDiagnostic &IncompleteDiag,
4227 const PartialDiagnostic &ExplicitConvDiag,
4228 const PartialDiagnostic &ExplicitConvNote,
4229 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004230 const PartialDiagnostic &AmbigNote,
4231 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00004232 // We can't perform any more checking for type-dependent expressions.
4233 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00004234 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004235
Douglas Gregorc30614b2010-06-29 23:17:37 +00004236 // If the expression already has integral or enumeration type, we're golden.
4237 QualType T = From->getType();
4238 if (T->isIntegralOrEnumerationType())
John McCall9ae2f072010-08-23 23:25:46 +00004239 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004240
4241 // FIXME: Check for missing '()' if T is a function type?
4242
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004243 // If we don't have a class type in C++, there's no way we can get an
Douglas Gregorc30614b2010-06-29 23:17:37 +00004244 // expression of integral or enumeration type.
4245 const RecordType *RecordTy = T->getAs<RecordType>();
4246 if (!RecordTy || !getLangOptions().CPlusPlus) {
4247 Diag(Loc, NotIntDiag)
4248 << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00004249 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004250 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004251
Douglas Gregorc30614b2010-06-29 23:17:37 +00004252 // We must have a complete class type.
4253 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00004254 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004255
Douglas Gregorc30614b2010-06-29 23:17:37 +00004256 // Look for a conversion to an integral or enumeration type.
4257 UnresolvedSet<4> ViableConversions;
4258 UnresolvedSet<4> ExplicitConversions;
4259 const UnresolvedSetImpl *Conversions
4260 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004261
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004262 bool HadMultipleCandidates = (Conversions->size() > 1);
4263
Douglas Gregorc30614b2010-06-29 23:17:37 +00004264 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004265 E = Conversions->end();
4266 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00004267 ++I) {
4268 if (CXXConversionDecl *Conversion
4269 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4270 if (Conversion->getConversionType().getNonReferenceType()
4271 ->isIntegralOrEnumerationType()) {
4272 if (Conversion->isExplicit())
4273 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4274 else
4275 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4276 }
4277 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004278
Douglas Gregorc30614b2010-06-29 23:17:37 +00004279 switch (ViableConversions.size()) {
4280 case 0:
4281 if (ExplicitConversions.size() == 1) {
4282 DeclAccessPair Found = ExplicitConversions[0];
4283 CXXConversionDecl *Conversion
4284 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004285
Douglas Gregorc30614b2010-06-29 23:17:37 +00004286 // The user probably meant to invoke the given explicit
4287 // conversion; use it.
4288 QualType ConvTy
4289 = Conversion->getConversionType().getNonReferenceType();
4290 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00004291 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004292
Douglas Gregorc30614b2010-06-29 23:17:37 +00004293 Diag(Loc, ExplicitConvDiag)
4294 << T << ConvTy
4295 << FixItHint::CreateInsertion(From->getLocStart(),
4296 "static_cast<" + TypeStr + ">(")
4297 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4298 ")");
4299 Diag(Conversion->getLocation(), ExplicitConvNote)
4300 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004301
4302 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00004303 // explicit conversion function.
4304 if (isSFINAEContext())
4305 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004306
Douglas Gregorc30614b2010-06-29 23:17:37 +00004307 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004308 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4309 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004310 if (Result.isInvalid())
4311 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004312
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004313 From = Result.get();
Douglas Gregorc30614b2010-06-29 23:17:37 +00004314 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004315
Douglas Gregorc30614b2010-06-29 23:17:37 +00004316 // We'll complain below about a non-integral condition type.
4317 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004318
Douglas Gregorc30614b2010-06-29 23:17:37 +00004319 case 1: {
4320 // Apply this conversion.
4321 DeclAccessPair Found = ViableConversions[0];
4322 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004323
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004324 CXXConversionDecl *Conversion
4325 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4326 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004327 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004328 if (ConvDiag.getDiagID()) {
4329 if (isSFINAEContext())
4330 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004331
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004332 Diag(Loc, ConvDiag)
4333 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4334 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004335
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004336 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4337 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004338 if (Result.isInvalid())
4339 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004340
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004341 From = Result.get();
Douglas Gregorc30614b2010-06-29 23:17:37 +00004342 break;
4343 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004344
Douglas Gregorc30614b2010-06-29 23:17:37 +00004345 default:
4346 Diag(Loc, AmbigDiag)
4347 << T << From->getSourceRange();
4348 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4349 CXXConversionDecl *Conv
4350 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4351 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4352 Diag(Conv->getLocation(), AmbigNote)
4353 << ConvTy->isEnumeralType() << ConvTy;
4354 }
John McCall9ae2f072010-08-23 23:25:46 +00004355 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004356 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004357
Douglas Gregoracb0bd82010-06-29 23:25:20 +00004358 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00004359 Diag(Loc, NotIntDiag)
4360 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00004361
John McCall9ae2f072010-08-23 23:25:46 +00004362 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004363}
4364
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004365/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00004366/// candidate functions, using the given function call arguments. If
4367/// @p SuppressUserConversions, then don't allow user-defined
4368/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004369///
4370/// \para PartialOverloading true if we are performing "partial" overloading
4371/// based on an incomplete set of function arguments. This feature is used by
4372/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00004373void
4374Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00004375 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004376 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00004377 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00004378 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004379 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00004380 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00004381 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004382 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00004383 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004384 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00004385
Douglas Gregor88a35142008-12-22 05:46:06 +00004386 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004387 if (!isa<CXXConstructorDecl>(Method)) {
4388 // If we get here, it's because we're calling a member function
4389 // that is named without a member access expression (e.g.,
4390 // "this->f") that was either written explicitly or created
4391 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00004392 // function, e.g., X::f(). We use an empty type for the implied
4393 // object argument (C++ [over.call.func]p3), and the acting context
4394 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00004395 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004396 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004397 Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004398 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004399 return;
4400 }
4401 // We treat a constructor like a non-member function, since its object
4402 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00004403 }
4404
Douglas Gregorfd476482009-11-13 23:59:09 +00004405 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00004406 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00004407
Douglas Gregor7edfb692009-11-23 12:27:39 +00004408 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004409 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004410
Douglas Gregor66724ea2009-11-14 01:20:54 +00004411 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4412 // C++ [class.copy]p3:
4413 // A member function template is never instantiated to perform the copy
4414 // of a class object to an object of its class type.
4415 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004416 if (NumArgs == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00004417 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00004418 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4419 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00004420 return;
4421 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004422
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004423 // Add this candidate
4424 CandidateSet.push_back(OverloadCandidate());
4425 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004426 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004427 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00004428 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004429 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004430 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004431 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004432
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004433 unsigned NumArgsInProto = Proto->getNumArgs();
4434
4435 // (C++ 13.3.2p2): A candidate function having fewer than m
4436 // parameters is viable only if it has an ellipsis in its parameter
4437 // list (8.3.5).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004438 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00004439 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004440 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004441 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004442 return;
4443 }
4444
4445 // (C++ 13.3.2p2): A candidate function having more than m parameters
4446 // is viable only if the (m+1)st parameter has a default argument
4447 // (8.3.6). For the purposes of overload resolution, the
4448 // parameter list is truncated on the right, so that there are
4449 // exactly m parameters.
4450 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004451 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004452 // Not enough arguments.
4453 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004454 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004455 return;
4456 }
4457
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00004458 // (CUDA B.1): Check for invalid calls between targets.
4459 if (getLangOptions().CUDA)
4460 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4461 if (CheckCUDATarget(Caller, Function)) {
4462 Candidate.Viable = false;
4463 Candidate.FailureKind = ovl_fail_bad_target;
4464 return;
4465 }
4466
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004467 // Determine the implicit conversion sequences for each of the
4468 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004469 Candidate.Conversions.resize(NumArgs);
4470 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4471 if (ArgIdx < NumArgsInProto) {
4472 // (C++ 13.3.2p3): for F to be a viable function, there shall
4473 // exist for each argument an implicit conversion sequence
4474 // (13.3.3.1) that converts that argument to the corresponding
4475 // parameter of F.
4476 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004477 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004478 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004479 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004480 /*InOverloadResolution=*/true,
4481 /*AllowObjCWritebackConversion=*/
4482 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00004483 if (Candidate.Conversions[ArgIdx].isBad()) {
4484 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004485 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00004486 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00004487 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004488 } else {
4489 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4490 // argument for which there is no corresponding parameter is
4491 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004492 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004493 }
4494 }
4495}
4496
Douglas Gregor063daf62009-03-13 18:40:31 +00004497/// \brief Add all of the function declarations in the given function set to
4498/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00004499void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00004500 Expr **Args, unsigned NumArgs,
4501 OverloadCandidateSet& CandidateSet,
4502 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00004503 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00004504 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4505 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004506 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00004507 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00004508 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004509 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004510 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00004511 CandidateSet, SuppressUserConversions);
4512 else
John McCall9aa472c2010-03-19 07:35:19 +00004513 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00004514 SuppressUserConversions);
4515 } else {
John McCall9aa472c2010-03-19 07:35:19 +00004516 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00004517 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4518 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00004519 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00004520 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00004521 /*FIXME: explicit args */ 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004522 Args[0]->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004523 Args[0]->Classify(Context),
4524 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00004525 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00004526 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00004527 else
John McCall9aa472c2010-03-19 07:35:19 +00004528 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00004529 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00004530 Args, NumArgs, CandidateSet,
4531 SuppressUserConversions);
4532 }
Douglas Gregor364e0212009-06-27 21:05:07 +00004533 }
Douglas Gregor063daf62009-03-13 18:40:31 +00004534}
4535
John McCall314be4e2009-11-17 07:50:12 +00004536/// AddMethodCandidate - Adds a named decl (which is some kind of
4537/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00004538void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004539 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004540 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00004541 Expr **Args, unsigned NumArgs,
4542 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004543 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00004544 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00004545 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00004546
4547 if (isa<UsingShadowDecl>(Decl))
4548 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004549
John McCall314be4e2009-11-17 07:50:12 +00004550 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4551 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4552 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00004553 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4554 /*ExplicitArgs*/ 0,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004555 ObjectType, ObjectClassification, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00004556 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004557 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00004558 } else {
John McCall9aa472c2010-03-19 07:35:19 +00004559 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004560 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004561 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00004562 }
4563}
4564
Douglas Gregor96176b32008-11-18 23:14:02 +00004565/// AddMethodCandidate - Adds the given C++ member function to the set
4566/// of candidate functions, using the given function call arguments
4567/// and the object argument (@c Object). For example, in a call
4568/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4569/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4570/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00004571/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00004572void
John McCall9aa472c2010-03-19 07:35:19 +00004573Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00004574 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004575 Expr::Classification ObjectClassification,
John McCall86820f52010-01-26 01:37:31 +00004576 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00004577 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004578 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00004579 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00004580 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00004581 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004582 assert(!isa<CXXConstructorDecl>(Method) &&
4583 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00004584
Douglas Gregor3f396022009-09-28 04:47:19 +00004585 if (!CandidateSet.isNewCandidate(Method))
4586 return;
4587
Douglas Gregor7edfb692009-11-23 12:27:39 +00004588 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004589 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004590
Douglas Gregor96176b32008-11-18 23:14:02 +00004591 // Add this candidate
4592 CandidateSet.push_back(OverloadCandidate());
4593 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004594 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00004595 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004596 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004597 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004598 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor96176b32008-11-18 23:14:02 +00004599
4600 unsigned NumArgsInProto = Proto->getNumArgs();
4601
4602 // (C++ 13.3.2p2): A candidate function having fewer than m
4603 // parameters is viable only if it has an ellipsis in its parameter
4604 // list (8.3.5).
4605 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4606 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004607 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00004608 return;
4609 }
4610
4611 // (C++ 13.3.2p2): A candidate function having more than m parameters
4612 // is viable only if the (m+1)st parameter has a default argument
4613 // (8.3.6). For the purposes of overload resolution, the
4614 // parameter list is truncated on the right, so that there are
4615 // exactly m parameters.
4616 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4617 if (NumArgs < MinRequiredArgs) {
4618 // Not enough arguments.
4619 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004620 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00004621 return;
4622 }
4623
4624 Candidate.Viable = true;
4625 Candidate.Conversions.resize(NumArgs + 1);
4626
John McCall701c89e2009-12-03 04:06:58 +00004627 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00004628 // The implicit object argument is ignored.
4629 Candidate.IgnoreObjectArgument = true;
4630 else {
4631 // Determine the implicit conversion sequence for the object
4632 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00004633 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004634 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4635 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004636 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004637 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004638 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00004639 return;
4640 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004641 }
4642
4643 // Determine the implicit conversion sequences for each of the
4644 // arguments.
4645 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4646 if (ArgIdx < NumArgsInProto) {
4647 // (C++ 13.3.2p3): for F to be a viable function, there shall
4648 // exist for each argument an implicit conversion sequence
4649 // (13.3.3.1) that converts that argument to the corresponding
4650 // parameter of F.
4651 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004652 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004653 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004654 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004655 /*InOverloadResolution=*/true,
4656 /*AllowObjCWritebackConversion=*/
4657 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00004658 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004659 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004660 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004661 break;
4662 }
4663 } else {
4664 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4665 // argument for which there is no corresponding parameter is
4666 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004667 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00004668 }
4669 }
4670}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004671
Douglas Gregor6b906862009-08-21 00:16:32 +00004672/// \brief Add a C++ member function template as a candidate to the candidate
4673/// set, using template argument deduction to produce an appropriate member
4674/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004675void
Douglas Gregor6b906862009-08-21 00:16:32 +00004676Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00004677 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004678 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00004679 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00004680 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004681 Expr::Classification ObjectClassification,
John McCall701c89e2009-12-03 04:06:58 +00004682 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00004683 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004684 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004685 if (!CandidateSet.isNewCandidate(MethodTmpl))
4686 return;
4687
Douglas Gregor6b906862009-08-21 00:16:32 +00004688 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00004689 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00004690 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00004691 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00004692 // candidate functions in the usual way.113) A given name can refer to one
4693 // or more function templates and also to a set of overloaded non-template
4694 // functions. In such a case, the candidate functions generated from each
4695 // function template are combined with the set of non-template candidate
4696 // functions.
John McCall5769d612010-02-08 23:07:23 +00004697 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00004698 FunctionDecl *Specialization = 0;
4699 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004700 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00004701 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00004702 CandidateSet.push_back(OverloadCandidate());
4703 OverloadCandidate &Candidate = CandidateSet.back();
4704 Candidate.FoundDecl = FoundDecl;
4705 Candidate.Function = MethodTmpl->getTemplatedDecl();
4706 Candidate.Viable = false;
4707 Candidate.FailureKind = ovl_fail_bad_deduction;
4708 Candidate.IsSurrogate = false;
4709 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004710 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004711 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004712 Info);
4713 return;
4714 }
Mike Stump1eb44332009-09-09 15:08:12 +00004715
Douglas Gregor6b906862009-08-21 00:16:32 +00004716 // Add the function template specialization produced by template argument
4717 // deduction as a candidate.
4718 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00004719 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00004720 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00004721 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004722 ActingContext, ObjectType, ObjectClassification,
4723 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00004724}
4725
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004726/// \brief Add a C++ function template specialization as a candidate
4727/// in the candidate set, using template argument deduction to produce
4728/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004729void
Douglas Gregore53060f2009-06-25 22:08:12 +00004730Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00004731 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00004732 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00004733 Expr **Args, unsigned NumArgs,
4734 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004735 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004736 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4737 return;
4738
Douglas Gregore53060f2009-06-25 22:08:12 +00004739 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00004740 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00004741 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00004742 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00004743 // candidate functions in the usual way.113) A given name can refer to one
4744 // or more function templates and also to a set of overloaded non-template
4745 // functions. In such a case, the candidate functions generated from each
4746 // function template are combined with the set of non-template candidate
4747 // functions.
John McCall5769d612010-02-08 23:07:23 +00004748 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00004749 FunctionDecl *Specialization = 0;
4750 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004751 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004752 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00004753 CandidateSet.push_back(OverloadCandidate());
4754 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004755 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00004756 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4757 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004758 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00004759 Candidate.IsSurrogate = false;
4760 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004761 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004762 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004763 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00004764 return;
4765 }
Mike Stump1eb44332009-09-09 15:08:12 +00004766
Douglas Gregore53060f2009-06-25 22:08:12 +00004767 // Add the function template specialization produced by template argument
4768 // deduction as a candidate.
4769 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00004770 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004771 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00004772}
Mike Stump1eb44332009-09-09 15:08:12 +00004773
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004774/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00004775/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004776/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00004777/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004778/// (which may or may not be the same type as the type that the
4779/// conversion function produces).
4780void
4781Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00004782 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004783 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004784 Expr *From, QualType ToType,
4785 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004786 assert(!Conversion->getDescribedFunctionTemplate() &&
4787 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004788 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00004789 if (!CandidateSet.isNewCandidate(Conversion))
4790 return;
4791
Douglas Gregor7edfb692009-11-23 12:27:39 +00004792 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004793 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004794
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004795 // Add this candidate
4796 CandidateSet.push_back(OverloadCandidate());
4797 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004798 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004799 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004800 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004801 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004802 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004803 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004804 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004805 Candidate.Viable = true;
4806 Candidate.Conversions.resize(1);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004807 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004808
Douglas Gregorbca39322010-08-19 15:37:02 +00004809 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004810 // For conversion functions, the function is considered to be a member of
4811 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00004812 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004813 //
4814 // Determine the implicit conversion sequence for the implicit
4815 // object parameter.
4816 QualType ImplicitParamType = From->getType();
4817 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4818 ImplicitParamType = FromPtrType->getPointeeType();
4819 CXXRecordDecl *ConversionContext
4820 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004821
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004822 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004823 = TryObjectArgumentInitialization(*this, From->getType(),
4824 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004825 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004826
John McCall1d318332010-01-12 00:44:57 +00004827 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004828 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004829 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004830 return;
4831 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004832
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004833 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00004834 // derived to base as such conversions are given Conversion Rank. They only
4835 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
4836 QualType FromCanon
4837 = Context.getCanonicalType(From->getType().getUnqualifiedType());
4838 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
4839 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
4840 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00004841 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00004842 return;
4843 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004844
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004845 // To determine what the conversion from the result of calling the
4846 // conversion function to the type we're eventually trying to
4847 // convert to (ToType), we need to synthesize a call to the
4848 // conversion function and attempt copy initialization from it. This
4849 // makes sure that we get the right semantics with respect to
4850 // lvalues/rvalues and the type. Fortunately, we can allocate this
4851 // call on the stack and we don't need its arguments to be
4852 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00004853 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004854 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00004855 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
4856 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00004857 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00004858 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00004859
Richard Smith87c1f1f2011-07-13 22:53:21 +00004860 QualType ConversionType = Conversion->getConversionType();
4861 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00004862 Candidate.Viable = false;
4863 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4864 return;
4865 }
4866
Richard Smith87c1f1f2011-07-13 22:53:21 +00004867 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00004868
Mike Stump1eb44332009-09-09 15:08:12 +00004869 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00004870 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
4871 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00004872 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00004873 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00004874 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00004875 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00004876 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00004877 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00004878 /*InOverloadResolution=*/false,
4879 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00004880
John McCall1d318332010-01-12 00:44:57 +00004881 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004882 case ImplicitConversionSequence::StandardConversion:
4883 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004884
Douglas Gregorc520c842010-04-12 23:42:09 +00004885 // C++ [over.ics.user]p3:
4886 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004887 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00004888 // shall have exact match rank.
4889 if (Conversion->getPrimaryTemplate() &&
4890 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4891 Candidate.Viable = false;
4892 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4893 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004894
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004895 // C++0x [dcl.init.ref]p5:
4896 // In the second case, if the reference is an rvalue reference and
4897 // the second standard conversion sequence of the user-defined
4898 // conversion sequence includes an lvalue-to-rvalue conversion, the
4899 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004900 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00004901 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
4902 Candidate.Viable = false;
4903 Candidate.FailureKind = ovl_fail_bad_final_conversion;
4904 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004905 break;
4906
4907 case ImplicitConversionSequence::BadConversion:
4908 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00004909 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004910 break;
4911
4912 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004913 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004914 "Can only end up with a standard conversion sequence or failure");
4915 }
4916}
4917
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004918/// \brief Adds a conversion function template specialization
4919/// candidate to the overload set, using template argument deduction
4920/// to deduce the template arguments of the conversion function
4921/// template from the type that we are converting to (C++
4922/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00004923void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004924Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00004925 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004926 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004927 Expr *From, QualType ToType,
4928 OverloadCandidateSet &CandidateSet) {
4929 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4930 "Only conversion function templates permitted here");
4931
Douglas Gregor3f396022009-09-28 04:47:19 +00004932 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4933 return;
4934
John McCall5769d612010-02-08 23:07:23 +00004935 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004936 CXXConversionDecl *Specialization = 0;
4937 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00004938 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004939 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00004940 CandidateSet.push_back(OverloadCandidate());
4941 OverloadCandidate &Candidate = CandidateSet.back();
4942 Candidate.FoundDecl = FoundDecl;
4943 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4944 Candidate.Viable = false;
4945 Candidate.FailureKind = ovl_fail_bad_deduction;
4946 Candidate.IsSurrogate = false;
4947 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004948 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004949 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004950 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004951 return;
4952 }
Mike Stump1eb44332009-09-09 15:08:12 +00004953
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004954 // Add the conversion function template specialization produced by
4955 // template argument deduction as a candidate.
4956 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00004957 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00004958 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004959}
4960
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004961/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4962/// converts the given @c Object to a function pointer via the
4963/// conversion function @c Conversion, and then attempts to call it
4964/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4965/// the type of function that we'll eventually be calling.
4966void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00004967 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004968 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00004969 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004970 Expr *Object,
John McCall701c89e2009-12-03 04:06:58 +00004971 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004972 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004973 if (!CandidateSet.isNewCandidate(Conversion))
4974 return;
4975
Douglas Gregor7edfb692009-11-23 12:27:39 +00004976 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004977 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004978
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004979 CandidateSet.push_back(OverloadCandidate());
4980 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004981 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004982 Candidate.Function = 0;
4983 Candidate.Surrogate = Conversion;
4984 Candidate.Viable = true;
4985 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00004986 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004987 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004988 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004989
4990 // Determine the implicit conversion sequence for the implicit
4991 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00004992 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004993 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004994 Object->Classify(Context),
4995 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004996 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004997 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004998 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00004999 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005000 return;
5001 }
5002
5003 // The first conversion is actually a user-defined conversion whose
5004 // first conversion is ObjectInit's standard conversion (which is
5005 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005006 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005007 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005008 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005009 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005010 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005011 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005012 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005013 = Candidate.Conversions[0].UserDefined.Before;
5014 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5015
Mike Stump1eb44332009-09-09 15:08:12 +00005016 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005017 unsigned NumArgsInProto = Proto->getNumArgs();
5018
5019 // (C++ 13.3.2p2): A candidate function having fewer than m
5020 // parameters is viable only if it has an ellipsis in its parameter
5021 // list (8.3.5).
5022 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5023 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005024 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005025 return;
5026 }
5027
5028 // Function types don't have any default arguments, so just check if
5029 // we have enough arguments.
5030 if (NumArgs < NumArgsInProto) {
5031 // Not enough arguments.
5032 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005033 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005034 return;
5035 }
5036
5037 // Determine the implicit conversion sequences for each of the
5038 // arguments.
5039 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5040 if (ArgIdx < NumArgsInProto) {
5041 // (C++ 13.3.2p3): for F to be a viable function, there shall
5042 // exist for each argument an implicit conversion sequence
5043 // (13.3.3.1) that converts that argument to the corresponding
5044 // parameter of F.
5045 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005046 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005047 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005048 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005049 /*InOverloadResolution=*/false,
5050 /*AllowObjCWritebackConversion=*/
5051 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005052 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005053 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005054 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005055 break;
5056 }
5057 } else {
5058 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5059 // argument for which there is no corresponding parameter is
5060 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005061 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005062 }
5063 }
5064}
5065
Douglas Gregor063daf62009-03-13 18:40:31 +00005066/// \brief Add overload candidates for overloaded operators that are
5067/// member functions.
5068///
5069/// Add the overloaded operator candidates that are member functions
5070/// for the operator Op that was used in an operator expression such
5071/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5072/// CandidateSet will store the added overload candidates. (C++
5073/// [over.match.oper]).
5074void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5075 SourceLocation OpLoc,
5076 Expr **Args, unsigned NumArgs,
5077 OverloadCandidateSet& CandidateSet,
5078 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005079 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5080
5081 // C++ [over.match.oper]p3:
5082 // For a unary operator @ with an operand of a type whose
5083 // cv-unqualified version is T1, and for a binary operator @ with
5084 // a left operand of a type whose cv-unqualified version is T1 and
5085 // a right operand of a type whose cv-unqualified version is T2,
5086 // three sets of candidate functions, designated member
5087 // candidates, non-member candidates and built-in candidates, are
5088 // constructed as follows:
5089 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005090
5091 // -- If T1 is a class type, the set of member candidates is the
5092 // result of the qualified lookup of T1::operator@
5093 // (13.3.1.1.1); otherwise, the set of member candidates is
5094 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005095 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005096 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00005097 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005098 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005099
John McCalla24dc2e2009-11-17 02:14:36 +00005100 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5101 LookupQualifiedName(Operators, T1Rec->getDecl());
5102 Operators.suppressDiagnostics();
5103
Mike Stump1eb44332009-09-09 15:08:12 +00005104 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005105 OperEnd = Operators.end();
5106 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005107 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005108 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005109 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005110 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005111 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005112 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005113}
5114
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005115/// AddBuiltinCandidate - Add a candidate for a built-in
5116/// operator. ResultTy and ParamTys are the result and parameter types
5117/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005118/// arguments being passed to the candidate. IsAssignmentOperator
5119/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005120/// operator. NumContextualBoolArguments is the number of arguments
5121/// (at the beginning of the argument list) that will be contextually
5122/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005123void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005124 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005125 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005126 bool IsAssignmentOperator,
5127 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005128 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005129 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005130
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005131 // Add this candidate
5132 CandidateSet.push_back(OverloadCandidate());
5133 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00005134 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005135 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005136 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005137 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005138 Candidate.BuiltinTypes.ResultTy = ResultTy;
5139 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5140 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5141
5142 // Determine the implicit conversion sequences for each of the
5143 // arguments.
5144 Candidate.Viable = true;
5145 Candidate.Conversions.resize(NumArgs);
Douglas Gregordfc331e2011-01-19 23:54:39 +00005146 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005147 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005148 // C++ [over.match.oper]p4:
5149 // For the built-in assignment operators, conversions of the
5150 // left operand are restricted as follows:
5151 // -- no temporaries are introduced to hold the left operand, and
5152 // -- no user-defined conversions are applied to the left
5153 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00005154 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005155 //
5156 // We block these conversions by turning off user-defined
5157 // conversions, since that is the only way that initialization of
5158 // a reference to a non-class type can occur from something that
5159 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005160 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00005161 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005162 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00005163 Candidate.Conversions[ArgIdx]
5164 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005165 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005166 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005167 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00005168 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00005169 /*InOverloadResolution=*/false,
5170 /*AllowObjCWritebackConversion=*/
5171 getLangOptions().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005172 }
John McCall1d318332010-01-12 00:44:57 +00005173 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005174 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005175 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005176 break;
5177 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005178 }
5179}
5180
5181/// BuiltinCandidateTypeSet - A set of types that will be used for the
5182/// candidate operator functions for built-in operators (C++
5183/// [over.built]). The types are separated into pointer types and
5184/// enumeration types.
5185class BuiltinCandidateTypeSet {
5186 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005187 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005188
5189 /// PointerTypes - The set of pointer types that will be used in the
5190 /// built-in candidates.
5191 TypeSet PointerTypes;
5192
Sebastian Redl78eb8742009-04-19 21:53:20 +00005193 /// MemberPointerTypes - The set of member pointer types that will be
5194 /// used in the built-in candidates.
5195 TypeSet MemberPointerTypes;
5196
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005197 /// EnumerationTypes - The set of enumeration types that will be
5198 /// used in the built-in candidates.
5199 TypeSet EnumerationTypes;
5200
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005201 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00005202 /// candidates.
5203 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00005204
5205 /// \brief A flag indicating non-record types are viable candidates
5206 bool HasNonRecordTypes;
5207
5208 /// \brief A flag indicating whether either arithmetic or enumeration types
5209 /// were present in the candidate set.
5210 bool HasArithmeticOrEnumeralTypes;
5211
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005212 /// \brief A flag indicating whether the nullptr type was present in the
5213 /// candidate set.
5214 bool HasNullPtrType;
5215
Douglas Gregor5842ba92009-08-24 15:23:48 +00005216 /// Sema - The semantic analysis instance where we are building the
5217 /// candidate type set.
5218 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00005219
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005220 /// Context - The AST context in which we will build the type sets.
5221 ASTContext &Context;
5222
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005223 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5224 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00005225 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005226
5227public:
5228 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005229 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005230
Mike Stump1eb44332009-09-09 15:08:12 +00005231 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00005232 : HasNonRecordTypes(false),
5233 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005234 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00005235 SemaRef(SemaRef),
5236 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005237
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005238 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00005239 SourceLocation Loc,
5240 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005241 bool AllowExplicitConversions,
5242 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005243
5244 /// pointer_begin - First pointer type found;
5245 iterator pointer_begin() { return PointerTypes.begin(); }
5246
Sebastian Redl78eb8742009-04-19 21:53:20 +00005247 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005248 iterator pointer_end() { return PointerTypes.end(); }
5249
Sebastian Redl78eb8742009-04-19 21:53:20 +00005250 /// member_pointer_begin - First member pointer type found;
5251 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5252
5253 /// member_pointer_end - Past the last member pointer type found;
5254 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5255
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005256 /// enumeration_begin - First enumeration type found;
5257 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5258
Sebastian Redl78eb8742009-04-19 21:53:20 +00005259 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005260 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005261
Douglas Gregor26bcf672010-05-19 03:21:00 +00005262 iterator vector_begin() { return VectorTypes.begin(); }
5263 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00005264
5265 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5266 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005267 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005268};
5269
Sebastian Redl78eb8742009-04-19 21:53:20 +00005270/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005271/// the set of pointer types along with any more-qualified variants of
5272/// that type. For example, if @p Ty is "int const *", this routine
5273/// will add "int const *", "int const volatile *", "int const
5274/// restrict *", and "int const volatile restrict *" to the set of
5275/// pointer types. Returns true if the add of @p Ty itself succeeded,
5276/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00005277///
5278/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00005279bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00005280BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5281 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00005282
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005283 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005284 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005285 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005286
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005287 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00005288 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005289 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005290 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005291 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005292 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005293 buildObjCPtr = true;
5294 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005295 else
David Blaikieb219cfc2011-09-23 05:06:16 +00005296 llvm_unreachable("type was not a pointer type!");
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005297 }
5298 else
5299 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005300
Sebastian Redla9efada2009-11-18 20:39:26 +00005301 // Don't add qualified variants of arrays. For one, they're not allowed
5302 // (the qualifier would sink to the element type), and for another, the
5303 // only overload situation where it matters is subscript or pointer +- int,
5304 // and those shouldn't have qualifier variants anyway.
5305 if (PointeeTy->isArrayType())
5306 return true;
John McCall0953e762009-09-24 19:53:00 +00005307 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00005308 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00005309 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005310 bool hasVolatile = VisibleQuals.hasVolatile();
5311 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005312
John McCall0953e762009-09-24 19:53:00 +00005313 // Iterate through all strict supersets of BaseCVR.
5314 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5315 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005316 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5317 // in the types.
5318 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5319 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00005320 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005321 if (!buildObjCPtr)
5322 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5323 else
5324 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005325 }
5326
5327 return true;
5328}
5329
Sebastian Redl78eb8742009-04-19 21:53:20 +00005330/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5331/// to the set of pointer types along with any more-qualified variants of
5332/// that type. For example, if @p Ty is "int const *", this routine
5333/// will add "int const *", "int const volatile *", "int const
5334/// restrict *", and "int const volatile restrict *" to the set of
5335/// pointer types. Returns true if the add of @p Ty itself succeeded,
5336/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00005337///
5338/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00005339bool
5340BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5341 QualType Ty) {
5342 // Insert this type.
5343 if (!MemberPointerTypes.insert(Ty))
5344 return false;
5345
John McCall0953e762009-09-24 19:53:00 +00005346 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5347 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00005348
John McCall0953e762009-09-24 19:53:00 +00005349 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00005350 // Don't add qualified variants of arrays. For one, they're not allowed
5351 // (the qualifier would sink to the element type), and for another, the
5352 // only overload situation where it matters is subscript or pointer +- int,
5353 // and those shouldn't have qualifier variants anyway.
5354 if (PointeeTy->isArrayType())
5355 return true;
John McCall0953e762009-09-24 19:53:00 +00005356 const Type *ClassTy = PointerTy->getClass();
5357
5358 // Iterate through all strict supersets of the pointee type's CVR
5359 // qualifiers.
5360 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5361 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5362 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005363
John McCall0953e762009-09-24 19:53:00 +00005364 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00005365 MemberPointerTypes.insert(
5366 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00005367 }
5368
5369 return true;
5370}
5371
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005372/// AddTypesConvertedFrom - Add each of the types to which the type @p
5373/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00005374/// primarily interested in pointer types and enumeration types. We also
5375/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005376/// AllowUserConversions is true if we should look at the conversion
5377/// functions of a class type, and AllowExplicitConversions if we
5378/// should also include the explicit conversion functions of a class
5379/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00005380void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005381BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00005382 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005383 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005384 bool AllowExplicitConversions,
5385 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005386 // Only deal with canonical types.
5387 Ty = Context.getCanonicalType(Ty);
5388
5389 // Look through reference types; they aren't part of the type of an
5390 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00005391 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005392 Ty = RefTy->getPointeeType();
5393
John McCall3b657512011-01-19 10:06:00 +00005394 // If we're dealing with an array type, decay to the pointer.
5395 if (Ty->isArrayType())
5396 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5397
5398 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005399 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005400
Chandler Carruth6a577462010-12-13 01:44:01 +00005401 // Flag if we ever add a non-record type.
5402 const RecordType *TyRec = Ty->getAs<RecordType>();
5403 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5404
Chandler Carruth6a577462010-12-13 01:44:01 +00005405 // Flag if we encounter an arithmetic type.
5406 HasArithmeticOrEnumeralTypes =
5407 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5408
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005409 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5410 PointerTypes.insert(Ty);
5411 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005412 // Insert our type, and its more-qualified variants, into the set
5413 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005414 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005415 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00005416 } else if (Ty->isMemberPointerType()) {
5417 // Member pointers are far easier, since the pointee can't be converted.
5418 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5419 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005420 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005421 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00005422 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005423 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005424 // We treat vector types as arithmetic types in many contexts as an
5425 // extension.
5426 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00005427 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005428 } else if (Ty->isNullPtrType()) {
5429 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00005430 } else if (AllowUserConversions && TyRec) {
5431 // No conversion functions in incomplete types.
5432 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5433 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005434
Chandler Carruth6a577462010-12-13 01:44:01 +00005435 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5436 const UnresolvedSetImpl *Conversions
5437 = ClassDecl->getVisibleConversionFunctions();
5438 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5439 E = Conversions->end(); I != E; ++I) {
5440 NamedDecl *D = I.getDecl();
5441 if (isa<UsingShadowDecl>(D))
5442 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005443
Chandler Carruth6a577462010-12-13 01:44:01 +00005444 // Skip conversion function templates; they don't tell us anything
5445 // about which builtin types we can convert to.
5446 if (isa<FunctionTemplateDecl>(D))
5447 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005448
Chandler Carruth6a577462010-12-13 01:44:01 +00005449 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5450 if (AllowExplicitConversions || !Conv->isExplicit()) {
5451 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5452 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005453 }
5454 }
5455 }
5456}
5457
Douglas Gregor19b7b152009-08-24 13:43:27 +00005458/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5459/// the volatile- and non-volatile-qualified assignment operators for the
5460/// given type to the candidate set.
5461static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5462 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00005463 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00005464 unsigned NumArgs,
5465 OverloadCandidateSet &CandidateSet) {
5466 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00005467
Douglas Gregor19b7b152009-08-24 13:43:27 +00005468 // T& operator=(T&, T)
5469 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5470 ParamTypes[1] = T;
5471 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5472 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00005473
Douglas Gregor19b7b152009-08-24 13:43:27 +00005474 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5475 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00005476 ParamTypes[0]
5477 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00005478 ParamTypes[1] = T;
5479 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00005480 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00005481 }
5482}
Mike Stump1eb44332009-09-09 15:08:12 +00005483
Sebastian Redl9994a342009-10-25 17:03:50 +00005484/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5485/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005486static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5487 Qualifiers VRQuals;
5488 const RecordType *TyRec;
5489 if (const MemberPointerType *RHSMPType =
5490 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00005491 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005492 else
5493 TyRec = ArgExpr->getType()->getAs<RecordType>();
5494 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005495 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005496 VRQuals.addVolatile();
5497 VRQuals.addRestrict();
5498 return VRQuals;
5499 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005500
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005501 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00005502 if (!ClassDecl->hasDefinition())
5503 return VRQuals;
5504
John McCalleec51cf2010-01-20 00:46:10 +00005505 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00005506 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005507
John McCalleec51cf2010-01-20 00:46:10 +00005508 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00005509 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00005510 NamedDecl *D = I.getDecl();
5511 if (isa<UsingShadowDecl>(D))
5512 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5513 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005514 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5515 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5516 CanTy = ResTypeRef->getPointeeType();
5517 // Need to go down the pointer/mempointer chain and add qualifiers
5518 // as see them.
5519 bool done = false;
5520 while (!done) {
5521 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5522 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005523 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005524 CanTy->getAs<MemberPointerType>())
5525 CanTy = ResTypeMPtr->getPointeeType();
5526 else
5527 done = true;
5528 if (CanTy.isVolatileQualified())
5529 VRQuals.addVolatile();
5530 if (CanTy.isRestrictQualified())
5531 VRQuals.addRestrict();
5532 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5533 return VRQuals;
5534 }
5535 }
5536 }
5537 return VRQuals;
5538}
John McCall00071ec2010-11-13 05:51:15 +00005539
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005540namespace {
John McCall00071ec2010-11-13 05:51:15 +00005541
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005542/// \brief Helper class to manage the addition of builtin operator overload
5543/// candidates. It provides shared state and utility methods used throughout
5544/// the process, as well as a helper method to add each group of builtin
5545/// operator overloads from the standard to a candidate set.
5546class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00005547 // Common instance state available to all overload candidate addition methods.
5548 Sema &S;
5549 Expr **Args;
5550 unsigned NumArgs;
5551 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00005552 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005553 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00005554 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005555
Chandler Carruth6d695582010-12-12 10:35:00 +00005556 // Define some constants used to index and iterate over the arithemetic types
5557 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00005558 // The "promoted arithmetic types" are the arithmetic
5559 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00005560 static const unsigned FirstIntegralType = 3;
5561 static const unsigned LastIntegralType = 18;
5562 static const unsigned FirstPromotedIntegralType = 3,
5563 LastPromotedIntegralType = 9;
5564 static const unsigned FirstPromotedArithmeticType = 0,
5565 LastPromotedArithmeticType = 9;
5566 static const unsigned NumArithmeticTypes = 18;
5567
Chandler Carruth6d695582010-12-12 10:35:00 +00005568 /// \brief Get the canonical type for a given arithmetic type index.
5569 CanQualType getArithmeticType(unsigned index) {
5570 assert(index < NumArithmeticTypes);
5571 static CanQualType ASTContext::* const
5572 ArithmeticTypes[NumArithmeticTypes] = {
5573 // Start of promoted types.
5574 &ASTContext::FloatTy,
5575 &ASTContext::DoubleTy,
5576 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00005577
Chandler Carruth6d695582010-12-12 10:35:00 +00005578 // Start of integral types.
5579 &ASTContext::IntTy,
5580 &ASTContext::LongTy,
5581 &ASTContext::LongLongTy,
5582 &ASTContext::UnsignedIntTy,
5583 &ASTContext::UnsignedLongTy,
5584 &ASTContext::UnsignedLongLongTy,
5585 // End of promoted types.
5586
5587 &ASTContext::BoolTy,
5588 &ASTContext::CharTy,
5589 &ASTContext::WCharTy,
5590 &ASTContext::Char16Ty,
5591 &ASTContext::Char32Ty,
5592 &ASTContext::SignedCharTy,
5593 &ASTContext::ShortTy,
5594 &ASTContext::UnsignedCharTy,
5595 &ASTContext::UnsignedShortTy,
5596 // End of integral types.
5597 // FIXME: What about complex?
5598 };
5599 return S.Context.*ArithmeticTypes[index];
5600 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005601
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005602 /// \brief Gets the canonical type resulting from the usual arithemetic
5603 /// converions for the given arithmetic types.
5604 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5605 // Accelerator table for performing the usual arithmetic conversions.
5606 // The rules are basically:
5607 // - if either is floating-point, use the wider floating-point
5608 // - if same signedness, use the higher rank
5609 // - if same size, use unsigned of the higher rank
5610 // - use the larger type
5611 // These rules, together with the axiom that higher ranks are
5612 // never smaller, are sufficient to precompute all of these results
5613 // *except* when dealing with signed types of higher rank.
5614 // (we could precompute SLL x UI for all known platforms, but it's
5615 // better not to make any assumptions).
5616 enum PromotedType {
5617 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5618 };
5619 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5620 [LastPromotedArithmeticType] = {
5621 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5622 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5623 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5624 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5625 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5626 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5627 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5628 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5629 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5630 };
5631
5632 assert(L < LastPromotedArithmeticType);
5633 assert(R < LastPromotedArithmeticType);
5634 int Idx = ConversionsTable[L][R];
5635
5636 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00005637 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005638
5639 // Slow path: we need to compare widths.
5640 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00005641 CanQualType LT = getArithmeticType(L),
5642 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005643 unsigned LW = S.Context.getIntWidth(LT),
5644 RW = S.Context.getIntWidth(RT);
5645
5646 // If they're different widths, use the signed type.
5647 if (LW > RW) return LT;
5648 else if (LW < RW) return RT;
5649
5650 // Otherwise, use the unsigned type of the signed type's rank.
5651 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5652 assert(L == SLL || R == SLL);
5653 return S.Context.UnsignedLongLongTy;
5654 }
5655
Chandler Carruth3c69dc42010-12-12 09:22:45 +00005656 /// \brief Helper method to factor out the common pattern of adding overloads
5657 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005658 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5659 bool HasVolatile) {
5660 QualType ParamTypes[2] = {
5661 S.Context.getLValueReferenceType(CandidateTy),
5662 S.Context.IntTy
5663 };
5664
5665 // Non-volatile version.
5666 if (NumArgs == 1)
5667 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5668 else
5669 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5670
5671 // Use a heuristic to reduce number of builtin candidates in the set:
5672 // add volatile version only if there are conversions to a volatile type.
5673 if (HasVolatile) {
5674 ParamTypes[0] =
5675 S.Context.getLValueReferenceType(
5676 S.Context.getVolatileType(CandidateTy));
5677 if (NumArgs == 1)
5678 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5679 else
5680 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5681 }
5682 }
5683
5684public:
5685 BuiltinOperatorOverloadBuilder(
5686 Sema &S, Expr **Args, unsigned NumArgs,
5687 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00005688 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005689 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005690 OverloadCandidateSet &CandidateSet)
5691 : S(S), Args(Args), NumArgs(NumArgs),
5692 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00005693 HasArithmeticOrEnumeralCandidateType(
5694 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005695 CandidateTypes(CandidateTypes),
5696 CandidateSet(CandidateSet) {
5697 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00005698 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005699 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005700 assert(getArithmeticType(LastPromotedIntegralType - 1)
5701 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005702 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005703 assert(getArithmeticType(FirstPromotedArithmeticType)
5704 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005705 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005706 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5707 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005708 "Invalid last promoted arithmetic type");
5709 }
5710
5711 // C++ [over.built]p3:
5712 //
5713 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5714 // is either volatile or empty, there exist candidate operator
5715 // functions of the form
5716 //
5717 // VQ T& operator++(VQ T&);
5718 // T operator++(VQ T&, int);
5719 //
5720 // C++ [over.built]p4:
5721 //
5722 // For every pair (T, VQ), where T is an arithmetic type other
5723 // than bool, and VQ is either volatile or empty, there exist
5724 // candidate operator functions of the form
5725 //
5726 // VQ T& operator--(VQ T&);
5727 // T operator--(VQ T&, int);
5728 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005729 if (!HasArithmeticOrEnumeralCandidateType)
5730 return;
5731
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005732 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5733 Arith < NumArithmeticTypes; ++Arith) {
5734 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00005735 getArithmeticType(Arith),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005736 VisibleTypeConversionsQuals.hasVolatile());
5737 }
5738 }
5739
5740 // C++ [over.built]p5:
5741 //
5742 // For every pair (T, VQ), where T is a cv-qualified or
5743 // cv-unqualified object type, and VQ is either volatile or
5744 // empty, there exist candidate operator functions of the form
5745 //
5746 // T*VQ& operator++(T*VQ&);
5747 // T*VQ& operator--(T*VQ&);
5748 // T* operator++(T*VQ&, int);
5749 // T* operator--(T*VQ&, int);
5750 void addPlusPlusMinusMinusPointerOverloads() {
5751 for (BuiltinCandidateTypeSet::iterator
5752 Ptr = CandidateTypes[0].pointer_begin(),
5753 PtrEnd = CandidateTypes[0].pointer_end();
5754 Ptr != PtrEnd; ++Ptr) {
5755 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005756 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005757 continue;
5758
5759 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5760 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5761 VisibleTypeConversionsQuals.hasVolatile()));
5762 }
5763 }
5764
5765 // C++ [over.built]p6:
5766 // For every cv-qualified or cv-unqualified object type T, there
5767 // exist candidate operator functions of the form
5768 //
5769 // T& operator*(T*);
5770 //
5771 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005772 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005773 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005774 // T& operator*(T*);
5775 void addUnaryStarPointerOverloads() {
5776 for (BuiltinCandidateTypeSet::iterator
5777 Ptr = CandidateTypes[0].pointer_begin(),
5778 PtrEnd = CandidateTypes[0].pointer_end();
5779 Ptr != PtrEnd; ++Ptr) {
5780 QualType ParamTy = *Ptr;
5781 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005782 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5783 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005784
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005785 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5786 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5787 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005788
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005789 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5790 &ParamTy, Args, 1, CandidateSet);
5791 }
5792 }
5793
5794 // C++ [over.built]p9:
5795 // For every promoted arithmetic type T, there exist candidate
5796 // operator functions of the form
5797 //
5798 // T operator+(T);
5799 // T operator-(T);
5800 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005801 if (!HasArithmeticOrEnumeralCandidateType)
5802 return;
5803
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005804 for (unsigned Arith = FirstPromotedArithmeticType;
5805 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005806 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005807 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5808 }
5809
5810 // Extension: We also add these operators for vector types.
5811 for (BuiltinCandidateTypeSet::iterator
5812 Vec = CandidateTypes[0].vector_begin(),
5813 VecEnd = CandidateTypes[0].vector_end();
5814 Vec != VecEnd; ++Vec) {
5815 QualType VecTy = *Vec;
5816 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5817 }
5818 }
5819
5820 // C++ [over.built]p8:
5821 // For every type T, there exist candidate operator functions of
5822 // the form
5823 //
5824 // T* operator+(T*);
5825 void addUnaryPlusPointerOverloads() {
5826 for (BuiltinCandidateTypeSet::iterator
5827 Ptr = CandidateTypes[0].pointer_begin(),
5828 PtrEnd = CandidateTypes[0].pointer_end();
5829 Ptr != PtrEnd; ++Ptr) {
5830 QualType ParamTy = *Ptr;
5831 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
5832 }
5833 }
5834
5835 // C++ [over.built]p10:
5836 // For every promoted integral type T, there exist candidate
5837 // operator functions of the form
5838 //
5839 // T operator~(T);
5840 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005841 if (!HasArithmeticOrEnumeralCandidateType)
5842 return;
5843
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005844 for (unsigned Int = FirstPromotedIntegralType;
5845 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005846 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005847 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
5848 }
5849
5850 // Extension: We also add this operator for vector types.
5851 for (BuiltinCandidateTypeSet::iterator
5852 Vec = CandidateTypes[0].vector_begin(),
5853 VecEnd = CandidateTypes[0].vector_end();
5854 Vec != VecEnd; ++Vec) {
5855 QualType VecTy = *Vec;
5856 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5857 }
5858 }
5859
5860 // C++ [over.match.oper]p16:
5861 // For every pointer to member type T, there exist candidate operator
5862 // functions of the form
5863 //
5864 // bool operator==(T,T);
5865 // bool operator!=(T,T);
5866 void addEqualEqualOrNotEqualMemberPointerOverloads() {
5867 /// Set of (canonical) types that we've already handled.
5868 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5869
5870 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5871 for (BuiltinCandidateTypeSet::iterator
5872 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5873 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5874 MemPtr != MemPtrEnd;
5875 ++MemPtr) {
5876 // Don't add the same builtin candidate twice.
5877 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5878 continue;
5879
5880 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5881 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5882 CandidateSet);
5883 }
5884 }
5885 }
5886
5887 // C++ [over.built]p15:
5888 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005889 // For every T, where T is an enumeration type, a pointer type, or
5890 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005891 //
5892 // bool operator<(T, T);
5893 // bool operator>(T, T);
5894 // bool operator<=(T, T);
5895 // bool operator>=(T, T);
5896 // bool operator==(T, T);
5897 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005898 void addRelationalPointerOrEnumeralOverloads() {
5899 // C++ [over.built]p1:
5900 // If there is a user-written candidate with the same name and parameter
5901 // types as a built-in candidate operator function, the built-in operator
5902 // function is hidden and is not included in the set of candidate
5903 // functions.
5904 //
5905 // The text is actually in a note, but if we don't implement it then we end
5906 // up with ambiguities when the user provides an overloaded operator for
5907 // an enumeration type. Note that only enumeration types have this problem,
5908 // so we track which enumeration types we've seen operators for. Also, the
5909 // only other overloaded operator with enumeration argumenst, operator=,
5910 // cannot be overloaded for enumeration types, so this is the only place
5911 // where we must suppress candidates like this.
5912 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
5913 UserDefinedBinaryOperators;
5914
5915 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5916 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5917 CandidateTypes[ArgIdx].enumeration_end()) {
5918 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5919 CEnd = CandidateSet.end();
5920 C != CEnd; ++C) {
5921 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5922 continue;
5923
5924 QualType FirstParamType =
5925 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5926 QualType SecondParamType =
5927 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5928
5929 // Skip if either parameter isn't of enumeral type.
5930 if (!FirstParamType->isEnumeralType() ||
5931 !SecondParamType->isEnumeralType())
5932 continue;
5933
5934 // Add this operator to the set of known user-defined operators.
5935 UserDefinedBinaryOperators.insert(
5936 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5937 S.Context.getCanonicalType(SecondParamType)));
5938 }
5939 }
5940 }
5941
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005942 /// Set of (canonical) types that we've already handled.
5943 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5944
5945 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5946 for (BuiltinCandidateTypeSet::iterator
5947 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5948 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5949 Ptr != PtrEnd; ++Ptr) {
5950 // Don't add the same builtin candidate twice.
5951 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5952 continue;
5953
5954 QualType ParamTypes[2] = { *Ptr, *Ptr };
5955 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5956 CandidateSet);
5957 }
5958 for (BuiltinCandidateTypeSet::iterator
5959 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5960 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5961 Enum != EnumEnd; ++Enum) {
5962 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5963
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005964 // Don't add the same builtin candidate twice, or if a user defined
5965 // candidate exists.
5966 if (!AddedTypes.insert(CanonType) ||
5967 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5968 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005969 continue;
5970
5971 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00005972 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5973 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005974 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005975
5976 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
5977 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
5978 if (AddedTypes.insert(NullPtrTy) &&
5979 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
5980 NullPtrTy))) {
5981 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
5982 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5983 CandidateSet);
5984 }
5985 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005986 }
5987 }
5988
5989 // C++ [over.built]p13:
5990 //
5991 // For every cv-qualified or cv-unqualified object type T
5992 // there exist candidate operator functions of the form
5993 //
5994 // T* operator+(T*, ptrdiff_t);
5995 // T& operator[](T*, ptrdiff_t); [BELOW]
5996 // T* operator-(T*, ptrdiff_t);
5997 // T* operator+(ptrdiff_t, T*);
5998 // T& operator[](ptrdiff_t, T*); [BELOW]
5999 //
6000 // C++ [over.built]p14:
6001 //
6002 // For every T, where T is a pointer to object type, there
6003 // exist candidate operator functions of the form
6004 //
6005 // ptrdiff_t operator-(T, T);
6006 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6007 /// Set of (canonical) types that we've already handled.
6008 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6009
6010 for (int Arg = 0; Arg < 2; ++Arg) {
6011 QualType AsymetricParamTypes[2] = {
6012 S.Context.getPointerDiffType(),
6013 S.Context.getPointerDiffType(),
6014 };
6015 for (BuiltinCandidateTypeSet::iterator
6016 Ptr = CandidateTypes[Arg].pointer_begin(),
6017 PtrEnd = CandidateTypes[Arg].pointer_end();
6018 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006019 QualType PointeeTy = (*Ptr)->getPointeeType();
6020 if (!PointeeTy->isObjectType())
6021 continue;
6022
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006023 AsymetricParamTypes[Arg] = *Ptr;
6024 if (Arg == 0 || Op == OO_Plus) {
6025 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6026 // T* operator+(ptrdiff_t, T*);
6027 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6028 CandidateSet);
6029 }
6030 if (Op == OO_Minus) {
6031 // ptrdiff_t operator-(T, T);
6032 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6033 continue;
6034
6035 QualType ParamTypes[2] = { *Ptr, *Ptr };
6036 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6037 Args, 2, CandidateSet);
6038 }
6039 }
6040 }
6041 }
6042
6043 // C++ [over.built]p12:
6044 //
6045 // For every pair of promoted arithmetic types L and R, there
6046 // exist candidate operator functions of the form
6047 //
6048 // LR operator*(L, R);
6049 // LR operator/(L, R);
6050 // LR operator+(L, R);
6051 // LR operator-(L, R);
6052 // bool operator<(L, R);
6053 // bool operator>(L, R);
6054 // bool operator<=(L, R);
6055 // bool operator>=(L, R);
6056 // bool operator==(L, R);
6057 // bool operator!=(L, R);
6058 //
6059 // where LR is the result of the usual arithmetic conversions
6060 // between types L and R.
6061 //
6062 // C++ [over.built]p24:
6063 //
6064 // For every pair of promoted arithmetic types L and R, there exist
6065 // candidate operator functions of the form
6066 //
6067 // LR operator?(bool, L, R);
6068 //
6069 // where LR is the result of the usual arithmetic conversions
6070 // between types L and R.
6071 // Our candidates ignore the first parameter.
6072 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006073 if (!HasArithmeticOrEnumeralCandidateType)
6074 return;
6075
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006076 for (unsigned Left = FirstPromotedArithmeticType;
6077 Left < LastPromotedArithmeticType; ++Left) {
6078 for (unsigned Right = FirstPromotedArithmeticType;
6079 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006080 QualType LandR[2] = { getArithmeticType(Left),
6081 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006082 QualType Result =
6083 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006084 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006085 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6086 }
6087 }
6088
6089 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6090 // conditional operator for vector types.
6091 for (BuiltinCandidateTypeSet::iterator
6092 Vec1 = CandidateTypes[0].vector_begin(),
6093 Vec1End = CandidateTypes[0].vector_end();
6094 Vec1 != Vec1End; ++Vec1) {
6095 for (BuiltinCandidateTypeSet::iterator
6096 Vec2 = CandidateTypes[1].vector_begin(),
6097 Vec2End = CandidateTypes[1].vector_end();
6098 Vec2 != Vec2End; ++Vec2) {
6099 QualType LandR[2] = { *Vec1, *Vec2 };
6100 QualType Result = S.Context.BoolTy;
6101 if (!isComparison) {
6102 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6103 Result = *Vec1;
6104 else
6105 Result = *Vec2;
6106 }
6107
6108 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6109 }
6110 }
6111 }
6112
6113 // C++ [over.built]p17:
6114 //
6115 // For every pair of promoted integral types L and R, there
6116 // exist candidate operator functions of the form
6117 //
6118 // LR operator%(L, R);
6119 // LR operator&(L, R);
6120 // LR operator^(L, R);
6121 // LR operator|(L, R);
6122 // L operator<<(L, R);
6123 // L operator>>(L, R);
6124 //
6125 // where LR is the result of the usual arithmetic conversions
6126 // between types L and R.
6127 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006128 if (!HasArithmeticOrEnumeralCandidateType)
6129 return;
6130
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006131 for (unsigned Left = FirstPromotedIntegralType;
6132 Left < LastPromotedIntegralType; ++Left) {
6133 for (unsigned Right = FirstPromotedIntegralType;
6134 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006135 QualType LandR[2] = { getArithmeticType(Left),
6136 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006137 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6138 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006139 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006140 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6141 }
6142 }
6143 }
6144
6145 // C++ [over.built]p20:
6146 //
6147 // For every pair (T, VQ), where T is an enumeration or
6148 // pointer to member type and VQ is either volatile or
6149 // empty, there exist candidate operator functions of the form
6150 //
6151 // VQ T& operator=(VQ T&, T);
6152 void addAssignmentMemberPointerOrEnumeralOverloads() {
6153 /// Set of (canonical) types that we've already handled.
6154 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6155
6156 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6157 for (BuiltinCandidateTypeSet::iterator
6158 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6159 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6160 Enum != EnumEnd; ++Enum) {
6161 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6162 continue;
6163
6164 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6165 CandidateSet);
6166 }
6167
6168 for (BuiltinCandidateTypeSet::iterator
6169 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6170 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6171 MemPtr != MemPtrEnd; ++MemPtr) {
6172 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6173 continue;
6174
6175 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6176 CandidateSet);
6177 }
6178 }
6179 }
6180
6181 // C++ [over.built]p19:
6182 //
6183 // For every pair (T, VQ), where T is any type and VQ is either
6184 // volatile or empty, there exist candidate operator functions
6185 // of the form
6186 //
6187 // T*VQ& operator=(T*VQ&, T*);
6188 //
6189 // C++ [over.built]p21:
6190 //
6191 // For every pair (T, VQ), where T is a cv-qualified or
6192 // cv-unqualified object type and VQ is either volatile or
6193 // empty, there exist candidate operator functions of the form
6194 //
6195 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6196 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6197 void addAssignmentPointerOverloads(bool isEqualOp) {
6198 /// Set of (canonical) types that we've already handled.
6199 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6200
6201 for (BuiltinCandidateTypeSet::iterator
6202 Ptr = CandidateTypes[0].pointer_begin(),
6203 PtrEnd = CandidateTypes[0].pointer_end();
6204 Ptr != PtrEnd; ++Ptr) {
6205 // If this is operator=, keep track of the builtin candidates we added.
6206 if (isEqualOp)
6207 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006208 else if (!(*Ptr)->getPointeeType()->isObjectType())
6209 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006210
6211 // non-volatile version
6212 QualType ParamTypes[2] = {
6213 S.Context.getLValueReferenceType(*Ptr),
6214 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6215 };
6216 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6217 /*IsAssigmentOperator=*/ isEqualOp);
6218
6219 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6220 VisibleTypeConversionsQuals.hasVolatile()) {
6221 // volatile version
6222 ParamTypes[0] =
6223 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6224 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6225 /*IsAssigmentOperator=*/isEqualOp);
6226 }
6227 }
6228
6229 if (isEqualOp) {
6230 for (BuiltinCandidateTypeSet::iterator
6231 Ptr = CandidateTypes[1].pointer_begin(),
6232 PtrEnd = CandidateTypes[1].pointer_end();
6233 Ptr != PtrEnd; ++Ptr) {
6234 // Make sure we don't add the same candidate twice.
6235 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6236 continue;
6237
Chandler Carruth6df868e2010-12-12 08:17:55 +00006238 QualType ParamTypes[2] = {
6239 S.Context.getLValueReferenceType(*Ptr),
6240 *Ptr,
6241 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006242
6243 // non-volatile version
6244 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6245 /*IsAssigmentOperator=*/true);
6246
6247 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6248 VisibleTypeConversionsQuals.hasVolatile()) {
6249 // volatile version
6250 ParamTypes[0] =
6251 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00006252 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6253 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006254 }
6255 }
6256 }
6257 }
6258
6259 // C++ [over.built]p18:
6260 //
6261 // For every triple (L, VQ, R), where L is an arithmetic type,
6262 // VQ is either volatile or empty, and R is a promoted
6263 // arithmetic type, there exist candidate operator functions of
6264 // the form
6265 //
6266 // VQ L& operator=(VQ L&, R);
6267 // VQ L& operator*=(VQ L&, R);
6268 // VQ L& operator/=(VQ L&, R);
6269 // VQ L& operator+=(VQ L&, R);
6270 // VQ L& operator-=(VQ L&, R);
6271 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006272 if (!HasArithmeticOrEnumeralCandidateType)
6273 return;
6274
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006275 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6276 for (unsigned Right = FirstPromotedArithmeticType;
6277 Right < LastPromotedArithmeticType; ++Right) {
6278 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00006279 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006280
6281 // Add this built-in operator as a candidate (VQ is empty).
6282 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006283 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006284 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6285 /*IsAssigmentOperator=*/isEqualOp);
6286
6287 // Add this built-in operator as a candidate (VQ is 'volatile').
6288 if (VisibleTypeConversionsQuals.hasVolatile()) {
6289 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006290 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006291 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006292 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6293 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006294 /*IsAssigmentOperator=*/isEqualOp);
6295 }
6296 }
6297 }
6298
6299 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6300 for (BuiltinCandidateTypeSet::iterator
6301 Vec1 = CandidateTypes[0].vector_begin(),
6302 Vec1End = CandidateTypes[0].vector_end();
6303 Vec1 != Vec1End; ++Vec1) {
6304 for (BuiltinCandidateTypeSet::iterator
6305 Vec2 = CandidateTypes[1].vector_begin(),
6306 Vec2End = CandidateTypes[1].vector_end();
6307 Vec2 != Vec2End; ++Vec2) {
6308 QualType ParamTypes[2];
6309 ParamTypes[1] = *Vec2;
6310 // Add this built-in operator as a candidate (VQ is empty).
6311 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6312 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6313 /*IsAssigmentOperator=*/isEqualOp);
6314
6315 // Add this built-in operator as a candidate (VQ is 'volatile').
6316 if (VisibleTypeConversionsQuals.hasVolatile()) {
6317 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6318 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006319 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6320 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006321 /*IsAssigmentOperator=*/isEqualOp);
6322 }
6323 }
6324 }
6325 }
6326
6327 // C++ [over.built]p22:
6328 //
6329 // For every triple (L, VQ, R), where L is an integral type, VQ
6330 // is either volatile or empty, and R is a promoted integral
6331 // type, there exist candidate operator functions of the form
6332 //
6333 // VQ L& operator%=(VQ L&, R);
6334 // VQ L& operator<<=(VQ L&, R);
6335 // VQ L& operator>>=(VQ L&, R);
6336 // VQ L& operator&=(VQ L&, R);
6337 // VQ L& operator^=(VQ L&, R);
6338 // VQ L& operator|=(VQ L&, R);
6339 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006340 if (!HasArithmeticOrEnumeralCandidateType)
6341 return;
6342
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006343 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6344 for (unsigned Right = FirstPromotedIntegralType;
6345 Right < LastPromotedIntegralType; ++Right) {
6346 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00006347 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006348
6349 // Add this built-in operator as a candidate (VQ is empty).
6350 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006351 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006352 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6353 if (VisibleTypeConversionsQuals.hasVolatile()) {
6354 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00006355 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006356 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6357 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6358 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6359 CandidateSet);
6360 }
6361 }
6362 }
6363 }
6364
6365 // C++ [over.operator]p23:
6366 //
6367 // There also exist candidate operator functions of the form
6368 //
6369 // bool operator!(bool);
6370 // bool operator&&(bool, bool);
6371 // bool operator||(bool, bool);
6372 void addExclaimOverload() {
6373 QualType ParamTy = S.Context.BoolTy;
6374 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6375 /*IsAssignmentOperator=*/false,
6376 /*NumContextualBoolArguments=*/1);
6377 }
6378 void addAmpAmpOrPipePipeOverload() {
6379 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6380 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6381 /*IsAssignmentOperator=*/false,
6382 /*NumContextualBoolArguments=*/2);
6383 }
6384
6385 // C++ [over.built]p13:
6386 //
6387 // For every cv-qualified or cv-unqualified object type T there
6388 // exist candidate operator functions of the form
6389 //
6390 // T* operator+(T*, ptrdiff_t); [ABOVE]
6391 // T& operator[](T*, ptrdiff_t);
6392 // T* operator-(T*, ptrdiff_t); [ABOVE]
6393 // T* operator+(ptrdiff_t, T*); [ABOVE]
6394 // T& operator[](ptrdiff_t, T*);
6395 void addSubscriptOverloads() {
6396 for (BuiltinCandidateTypeSet::iterator
6397 Ptr = CandidateTypes[0].pointer_begin(),
6398 PtrEnd = CandidateTypes[0].pointer_end();
6399 Ptr != PtrEnd; ++Ptr) {
6400 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6401 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006402 if (!PointeeType->isObjectType())
6403 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006404
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006405 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6406
6407 // T& operator[](T*, ptrdiff_t)
6408 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6409 }
6410
6411 for (BuiltinCandidateTypeSet::iterator
6412 Ptr = CandidateTypes[1].pointer_begin(),
6413 PtrEnd = CandidateTypes[1].pointer_end();
6414 Ptr != PtrEnd; ++Ptr) {
6415 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6416 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006417 if (!PointeeType->isObjectType())
6418 continue;
6419
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006420 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6421
6422 // T& operator[](ptrdiff_t, T*)
6423 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6424 }
6425 }
6426
6427 // C++ [over.built]p11:
6428 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6429 // C1 is the same type as C2 or is a derived class of C2, T is an object
6430 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6431 // there exist candidate operator functions of the form
6432 //
6433 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6434 //
6435 // where CV12 is the union of CV1 and CV2.
6436 void addArrowStarOverloads() {
6437 for (BuiltinCandidateTypeSet::iterator
6438 Ptr = CandidateTypes[0].pointer_begin(),
6439 PtrEnd = CandidateTypes[0].pointer_end();
6440 Ptr != PtrEnd; ++Ptr) {
6441 QualType C1Ty = (*Ptr);
6442 QualType C1;
6443 QualifierCollector Q1;
6444 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6445 if (!isa<RecordType>(C1))
6446 continue;
6447 // heuristic to reduce number of builtin candidates in the set.
6448 // Add volatile/restrict version only if there are conversions to a
6449 // volatile/restrict type.
6450 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6451 continue;
6452 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6453 continue;
6454 for (BuiltinCandidateTypeSet::iterator
6455 MemPtr = CandidateTypes[1].member_pointer_begin(),
6456 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6457 MemPtr != MemPtrEnd; ++MemPtr) {
6458 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6459 QualType C2 = QualType(mptr->getClass(), 0);
6460 C2 = C2.getUnqualifiedType();
6461 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6462 break;
6463 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6464 // build CV12 T&
6465 QualType T = mptr->getPointeeType();
6466 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6467 T.isVolatileQualified())
6468 continue;
6469 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6470 T.isRestrictQualified())
6471 continue;
6472 T = Q1.apply(S.Context, T);
6473 QualType ResultTy = S.Context.getLValueReferenceType(T);
6474 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6475 }
6476 }
6477 }
6478
6479 // Note that we don't consider the first argument, since it has been
6480 // contextually converted to bool long ago. The candidates below are
6481 // therefore added as binary.
6482 //
6483 // C++ [over.built]p25:
6484 // For every type T, where T is a pointer, pointer-to-member, or scoped
6485 // enumeration type, there exist candidate operator functions of the form
6486 //
6487 // T operator?(bool, T, T);
6488 //
6489 void addConditionalOperatorOverloads() {
6490 /// Set of (canonical) types that we've already handled.
6491 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6492
6493 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6494 for (BuiltinCandidateTypeSet::iterator
6495 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6496 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6497 Ptr != PtrEnd; ++Ptr) {
6498 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6499 continue;
6500
6501 QualType ParamTypes[2] = { *Ptr, *Ptr };
6502 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6503 }
6504
6505 for (BuiltinCandidateTypeSet::iterator
6506 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6507 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6508 MemPtr != MemPtrEnd; ++MemPtr) {
6509 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6510 continue;
6511
6512 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6513 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6514 }
6515
6516 if (S.getLangOptions().CPlusPlus0x) {
6517 for (BuiltinCandidateTypeSet::iterator
6518 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6519 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6520 Enum != EnumEnd; ++Enum) {
6521 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6522 continue;
6523
6524 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6525 continue;
6526
6527 QualType ParamTypes[2] = { *Enum, *Enum };
6528 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6529 }
6530 }
6531 }
6532 }
6533};
6534
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006535} // end anonymous namespace
6536
6537/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6538/// operator overloads to the candidate set (C++ [over.built]), based
6539/// on the operator @p Op and the arguments given. For example, if the
6540/// operator is a binary '+', this routine might add "int
6541/// operator+(int, int)" to cover integer addition.
6542void
6543Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6544 SourceLocation OpLoc,
6545 Expr **Args, unsigned NumArgs,
6546 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006547 // Find all of the types that the arguments can convert to, but only
6548 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00006549 // that make use of these types. Also record whether we encounter non-record
6550 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006551 Qualifiers VisibleTypeConversionsQuals;
6552 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00006553 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6554 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00006555
6556 bool HasNonRecordCandidateType = false;
6557 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006558 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00006559 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6560 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6561 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6562 OpLoc,
6563 true,
6564 (Op == OO_Exclaim ||
6565 Op == OO_AmpAmp ||
6566 Op == OO_PipePipe),
6567 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00006568 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6569 CandidateTypes[ArgIdx].hasNonRecordTypes();
6570 HasArithmeticOrEnumeralCandidateType =
6571 HasArithmeticOrEnumeralCandidateType ||
6572 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00006573 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006574
Chandler Carruth6a577462010-12-13 01:44:01 +00006575 // Exit early when no non-record types have been added to the candidate set
6576 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00006577 //
6578 // We can't exit early for !, ||, or &&, since there we have always have
6579 // 'bool' overloads.
6580 if (!HasNonRecordCandidateType &&
6581 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00006582 return;
6583
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006584 // Setup an object to manage the common state for building overloads.
6585 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6586 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006587 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006588 CandidateTypes, CandidateSet);
6589
6590 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006591 switch (Op) {
6592 case OO_None:
6593 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00006594 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006595
Chandler Carruthabb71842010-12-12 08:51:33 +00006596 case OO_New:
6597 case OO_Delete:
6598 case OO_Array_New:
6599 case OO_Array_Delete:
6600 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00006601 llvm_unreachable(
6602 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00006603
6604 case OO_Comma:
6605 case OO_Arrow:
6606 // C++ [over.match.oper]p3:
6607 // -- For the operator ',', the unary operator '&', or the
6608 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00006609 break;
6610
6611 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00006612 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006613 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00006614 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00006615
6616 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00006617 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006618 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00006619 } else {
6620 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6621 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6622 }
Douglas Gregor74253732008-11-19 15:42:04 +00006623 break;
6624
Chandler Carruthabb71842010-12-12 08:51:33 +00006625 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00006626 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00006627 OpBuilder.addUnaryStarPointerOverloads();
6628 else
6629 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6630 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006631
Chandler Carruthabb71842010-12-12 08:51:33 +00006632 case OO_Slash:
6633 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00006634 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006635
6636 case OO_PlusPlus:
6637 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006638 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6639 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00006640 break;
6641
Douglas Gregor19b7b152009-08-24 13:43:27 +00006642 case OO_EqualEqual:
6643 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006644 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00006645 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00006646
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006647 case OO_Less:
6648 case OO_Greater:
6649 case OO_LessEqual:
6650 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006651 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00006652 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6653 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006654
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006655 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006656 case OO_Caret:
6657 case OO_Pipe:
6658 case OO_LessLess:
6659 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006660 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006661 break;
6662
Chandler Carruthabb71842010-12-12 08:51:33 +00006663 case OO_Amp: // '&' is either unary or binary
6664 if (NumArgs == 1)
6665 // C++ [over.match.oper]p3:
6666 // -- For the operator ',', the unary operator '&', or the
6667 // operator '->', the built-in candidates set is empty.
6668 break;
6669
6670 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6671 break;
6672
6673 case OO_Tilde:
6674 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6675 break;
6676
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006677 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006678 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00006679 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006680
6681 case OO_PlusEqual:
6682 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006683 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006684 // Fall through.
6685
6686 case OO_StarEqual:
6687 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006688 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006689 break;
6690
6691 case OO_PercentEqual:
6692 case OO_LessLessEqual:
6693 case OO_GreaterGreaterEqual:
6694 case OO_AmpEqual:
6695 case OO_CaretEqual:
6696 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006697 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006698 break;
6699
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006700 case OO_Exclaim:
6701 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00006702 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006703
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006704 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006705 case OO_PipePipe:
6706 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006707 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006708
6709 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006710 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006711 break;
6712
6713 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006714 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006715 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006716
6717 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006718 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00006719 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6720 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006721 }
6722}
6723
Douglas Gregorfa047642009-02-04 00:32:51 +00006724/// \brief Add function candidates found via argument-dependent lookup
6725/// to the set of overloading candidates.
6726///
6727/// This routine performs argument-dependent name lookup based on the
6728/// given function name (which may also be an operator name) and adds
6729/// all of the overload candidates found by ADL to the overload
6730/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00006731void
Douglas Gregorfa047642009-02-04 00:32:51 +00006732Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00006733 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00006734 Expr **Args, unsigned NumArgs,
Douglas Gregor67714232011-03-03 02:41:12 +00006735 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006736 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00006737 bool PartialOverloading,
6738 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00006739 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00006740
John McCalla113e722010-01-26 06:04:06 +00006741 // FIXME: This approach for uniquing ADL results (and removing
6742 // redundant candidates from the set) relies on pointer-equality,
6743 // which means we need to key off the canonical decl. However,
6744 // always going back to the canonical decl might not get us the
6745 // right set of default arguments. What default arguments are
6746 // we supposed to consider on ADL candidates, anyway?
6747
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006748 // FIXME: Pass in the explicit template arguments?
Richard Smithad762fc2011-04-14 22:09:26 +00006749 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6750 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00006751
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006752 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006753 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6754 CandEnd = CandidateSet.end();
6755 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00006756 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00006757 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00006758 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00006759 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00006760 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006761
6762 // For each of the ADL candidates we found, add it to the overload
6763 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00006764 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00006765 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00006766 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00006767 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006768 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006769
John McCall9aa472c2010-03-19 07:35:19 +00006770 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006771 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006772 } else
John McCall6e266892010-01-26 03:27:55 +00006773 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00006774 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00006775 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00006776 }
Douglas Gregorfa047642009-02-04 00:32:51 +00006777}
6778
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006779/// isBetterOverloadCandidate - Determines whether the first overload
6780/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00006781bool
John McCall120d63c2010-08-24 20:38:10 +00006782isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00006783 const OverloadCandidate &Cand1,
6784 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006785 SourceLocation Loc,
6786 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006787 // Define viable functions to be better candidates than non-viable
6788 // functions.
6789 if (!Cand2.Viable)
6790 return Cand1.Viable;
6791 else if (!Cand1.Viable)
6792 return false;
6793
Douglas Gregor88a35142008-12-22 05:46:06 +00006794 // C++ [over.match.best]p1:
6795 //
6796 // -- if F is a static member function, ICS1(F) is defined such
6797 // that ICS1(F) is neither better nor worse than ICS1(G) for
6798 // any function G, and, symmetrically, ICS1(G) is neither
6799 // better nor worse than ICS1(F).
6800 unsigned StartArg = 0;
6801 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6802 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006803
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006804 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00006805 // A viable function F1 is defined to be a better function than another
6806 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006807 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006808 unsigned NumArgs = Cand1.Conversions.size();
6809 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6810 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006811 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00006812 switch (CompareImplicitConversionSequences(S,
6813 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006814 Cand2.Conversions[ArgIdx])) {
6815 case ImplicitConversionSequence::Better:
6816 // Cand1 has a better conversion sequence.
6817 HasBetterConversion = true;
6818 break;
6819
6820 case ImplicitConversionSequence::Worse:
6821 // Cand1 can't be better than Cand2.
6822 return false;
6823
6824 case ImplicitConversionSequence::Indistinguishable:
6825 // Do nothing.
6826 break;
6827 }
6828 }
6829
Mike Stump1eb44332009-09-09 15:08:12 +00006830 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006831 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006832 if (HasBetterConversion)
6833 return true;
6834
Mike Stump1eb44332009-09-09 15:08:12 +00006835 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006836 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00006837 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006838 Cand2.Function && Cand2.Function->getPrimaryTemplate())
6839 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00006840
6841 // -- F1 and F2 are function template specializations, and the function
6842 // template for F1 is more specialized than the template for F2
6843 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006844 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00006845 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00006846 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006847 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00006848 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
6849 Cand2.Function->getPrimaryTemplate(),
6850 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006851 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00006852 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00006853 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00006854 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00006855 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006856
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006857 // -- the context is an initialization by user-defined conversion
6858 // (see 8.5, 13.3.1.5) and the standard conversion sequence
6859 // from the return type of F1 to the destination type (i.e.,
6860 // the type of the entity being initialized) is a better
6861 // conversion sequence than the standard conversion sequence
6862 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006863 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00006864 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006865 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00006866 switch (CompareStandardConversionSequences(S,
6867 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00006868 Cand2.FinalConversion)) {
6869 case ImplicitConversionSequence::Better:
6870 // Cand1 has a better conversion sequence.
6871 return true;
6872
6873 case ImplicitConversionSequence::Worse:
6874 // Cand1 can't be better than Cand2.
6875 return false;
6876
6877 case ImplicitConversionSequence::Indistinguishable:
6878 // Do nothing
6879 break;
6880 }
6881 }
6882
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006883 return false;
6884}
6885
Mike Stump1eb44332009-09-09 15:08:12 +00006886/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00006887/// within an overload candidate set.
6888///
6889/// \param CandidateSet the set of candidate functions.
6890///
6891/// \param Loc the location of the function name (or operator symbol) for
6892/// which overload resolution occurs.
6893///
Mike Stump1eb44332009-09-09 15:08:12 +00006894/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00006895/// function, Best points to the candidate function found.
6896///
6897/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00006898OverloadingResult
6899OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00006900 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00006901 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006902 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00006903 Best = end();
6904 for (iterator Cand = begin(); Cand != end(); ++Cand) {
6905 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006906 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006907 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006908 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006909 }
6910
6911 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00006912 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006913 return OR_No_Viable_Function;
6914
6915 // Make sure that this function is better than every other viable
6916 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00006917 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00006918 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006919 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006920 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006921 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00006922 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006923 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00006924 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006925 }
Mike Stump1eb44332009-09-09 15:08:12 +00006926
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006927 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006928 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00006929 (Best->Function->isDeleted() ||
6930 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00006931 return OR_Deleted;
6932
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006933 return OR_Success;
6934}
6935
John McCall3c80f572010-01-12 02:15:36 +00006936namespace {
6937
6938enum OverloadCandidateKind {
6939 oc_function,
6940 oc_method,
6941 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00006942 oc_function_template,
6943 oc_method_template,
6944 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00006945 oc_implicit_default_constructor,
6946 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00006947 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006948 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00006949 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00006950 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00006951};
6952
John McCall220ccbf2010-01-13 00:25:19 +00006953OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6954 FunctionDecl *Fn,
6955 std::string &Description) {
6956 bool isTemplate = false;
6957
6958 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6959 isTemplate = true;
6960 Description = S.getTemplateArgumentBindingsText(
6961 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6962 }
John McCallb1622a12010-01-06 09:43:14 +00006963
6964 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00006965 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00006966 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00006967
Sebastian Redlf677ea32011-02-05 19:23:19 +00006968 if (Ctor->getInheritedConstructor())
6969 return oc_implicit_inherited_constructor;
6970
Sean Hunt82713172011-05-25 23:16:36 +00006971 if (Ctor->isDefaultConstructor())
6972 return oc_implicit_default_constructor;
6973
6974 if (Ctor->isMoveConstructor())
6975 return oc_implicit_move_constructor;
6976
6977 assert(Ctor->isCopyConstructor() &&
6978 "unexpected sort of implicit constructor");
6979 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00006980 }
6981
6982 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6983 // This actually gets spelled 'candidate function' for now, but
6984 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00006985 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00006986 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00006987
Sean Hunt82713172011-05-25 23:16:36 +00006988 if (Meth->isMoveAssignmentOperator())
6989 return oc_implicit_move_assignment;
6990
Douglas Gregor3e9438b2010-09-27 22:37:28 +00006991 assert(Meth->isCopyAssignmentOperator()
John McCallb1622a12010-01-06 09:43:14 +00006992 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00006993 return oc_implicit_copy_assignment;
6994 }
6995
John McCall220ccbf2010-01-13 00:25:19 +00006996 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00006997}
6998
Sebastian Redlf677ea32011-02-05 19:23:19 +00006999void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7000 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7001 if (!Ctor) return;
7002
7003 Ctor = Ctor->getInheritedConstructor();
7004 if (!Ctor) return;
7005
7006 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7007}
7008
John McCall3c80f572010-01-12 02:15:36 +00007009} // end anonymous namespace
7010
7011// Notes the location of an overload candidate.
7012void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCall220ccbf2010-01-13 00:25:19 +00007013 std::string FnDesc;
7014 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
7015 Diag(Fn->getLocation(), diag::note_ovl_candidate)
7016 << (unsigned) K << FnDesc;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007017 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007018}
7019
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007020//Notes the location of all overload candidates designated through
7021// OverloadedExpr
7022void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr) {
7023 assert(OverloadedExpr->getType() == Context.OverloadTy);
7024
7025 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7026 OverloadExpr *OvlExpr = Ovl.Expression;
7027
7028 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7029 IEnd = OvlExpr->decls_end();
7030 I != IEnd; ++I) {
7031 if (FunctionTemplateDecl *FunTmpl =
7032 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
7033 NoteOverloadCandidate(FunTmpl->getTemplatedDecl());
7034 } else if (FunctionDecl *Fun
7035 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
7036 NoteOverloadCandidate(Fun);
7037 }
7038 }
7039}
7040
John McCall1d318332010-01-12 00:44:57 +00007041/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7042/// "lead" diagnostic; it will be given two arguments, the source and
7043/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00007044void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7045 Sema &S,
7046 SourceLocation CaretLoc,
7047 const PartialDiagnostic &PDiag) const {
7048 S.Diag(CaretLoc, PDiag)
7049 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00007050 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00007051 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7052 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00007053 }
John McCall81201622010-01-08 04:41:39 +00007054}
7055
John McCall1d318332010-01-12 00:44:57 +00007056namespace {
7057
John McCalladbb8f82010-01-13 09:16:55 +00007058void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7059 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7060 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00007061 assert(Cand->Function && "for now, candidate must be a function");
7062 FunctionDecl *Fn = Cand->Function;
7063
7064 // There's a conversion slot for the object argument if this is a
7065 // non-constructor method. Note that 'I' corresponds the
7066 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00007067 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00007068 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00007069 if (I == 0)
7070 isObjectArgument = true;
7071 else
7072 I--;
John McCall220ccbf2010-01-13 00:25:19 +00007073 }
7074
John McCall220ccbf2010-01-13 00:25:19 +00007075 std::string FnDesc;
7076 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7077
John McCalladbb8f82010-01-13 09:16:55 +00007078 Expr *FromExpr = Conv.Bad.FromExpr;
7079 QualType FromTy = Conv.Bad.getFromType();
7080 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00007081
John McCall5920dbb2010-02-02 02:42:52 +00007082 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00007083 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00007084 Expr *E = FromExpr->IgnoreParens();
7085 if (isa<UnaryOperator>(E))
7086 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00007087 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00007088
7089 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7090 << (unsigned) FnKind << FnDesc
7091 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7092 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007093 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00007094 return;
7095 }
7096
John McCall258b2032010-01-23 08:10:49 +00007097 // Do some hand-waving analysis to see if the non-viability is due
7098 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00007099 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7100 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7101 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7102 CToTy = RT->getPointeeType();
7103 else {
7104 // TODO: detect and diagnose the full richness of const mismatches.
7105 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7106 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7107 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7108 }
7109
7110 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7111 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7112 // It is dumb that we have to do this here.
7113 while (isa<ArrayType>(CFromTy))
7114 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7115 while (isa<ArrayType>(CToTy))
7116 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7117
7118 Qualifiers FromQs = CFromTy.getQualifiers();
7119 Qualifiers ToQs = CToTy.getQualifiers();
7120
7121 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7122 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7123 << (unsigned) FnKind << FnDesc
7124 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7125 << FromTy
7126 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7127 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007128 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007129 return;
7130 }
7131
John McCallf85e1932011-06-15 23:02:42 +00007132 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00007133 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00007134 << (unsigned) FnKind << FnDesc
7135 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7136 << FromTy
7137 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7138 << (unsigned) isObjectArgument << I+1;
7139 MaybeEmitInheritedConstructorNote(S, Fn);
7140 return;
7141 }
7142
Douglas Gregor028ea4b2011-04-26 23:16:46 +00007143 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7144 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7145 << (unsigned) FnKind << FnDesc
7146 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7147 << FromTy
7148 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7149 << (unsigned) isObjectArgument << I+1;
7150 MaybeEmitInheritedConstructorNote(S, Fn);
7151 return;
7152 }
7153
John McCall651f3ee2010-01-14 03:28:57 +00007154 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7155 assert(CVR && "unexpected qualifiers mismatch");
7156
7157 if (isObjectArgument) {
7158 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7159 << (unsigned) FnKind << FnDesc
7160 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7161 << FromTy << (CVR - 1);
7162 } else {
7163 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7164 << (unsigned) FnKind << FnDesc
7165 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7166 << FromTy << (CVR - 1) << I+1;
7167 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00007168 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007169 return;
7170 }
7171
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00007172 // Special diagnostic for failure to convert an initializer list, since
7173 // telling the user that it has type void is not useful.
7174 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7175 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7176 << (unsigned) FnKind << FnDesc
7177 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7178 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7179 MaybeEmitInheritedConstructorNote(S, Fn);
7180 return;
7181 }
7182
John McCall258b2032010-01-23 08:10:49 +00007183 // Diagnose references or pointers to incomplete types differently,
7184 // since it's far from impossible that the incompleteness triggered
7185 // the failure.
7186 QualType TempFromTy = FromTy.getNonReferenceType();
7187 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7188 TempFromTy = PTy->getPointeeType();
7189 if (TempFromTy->isIncompleteType()) {
7190 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7191 << (unsigned) FnKind << FnDesc
7192 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7193 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007194 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00007195 return;
7196 }
7197
Douglas Gregor85789812010-06-30 23:01:39 +00007198 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007199 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00007200 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7201 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7202 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7203 FromPtrTy->getPointeeType()) &&
7204 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7205 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007206 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00007207 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007208 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00007209 }
7210 } else if (const ObjCObjectPointerType *FromPtrTy
7211 = FromTy->getAs<ObjCObjectPointerType>()) {
7212 if (const ObjCObjectPointerType *ToPtrTy
7213 = ToTy->getAs<ObjCObjectPointerType>())
7214 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7215 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7216 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7217 FromPtrTy->getPointeeType()) &&
7218 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007219 BaseToDerivedConversion = 2;
7220 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7221 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7222 !FromTy->isIncompleteType() &&
7223 !ToRefTy->getPointeeType()->isIncompleteType() &&
7224 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7225 BaseToDerivedConversion = 3;
7226 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007227
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007228 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007229 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007230 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00007231 << (unsigned) FnKind << FnDesc
7232 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007233 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007234 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007235 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00007236 return;
7237 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007238
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00007239 if (isa<ObjCObjectPointerType>(CFromTy) &&
7240 isa<PointerType>(CToTy)) {
7241 Qualifiers FromQs = CFromTy.getQualifiers();
7242 Qualifiers ToQs = CToTy.getQualifiers();
7243 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7244 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7245 << (unsigned) FnKind << FnDesc
7246 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7247 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7248 MaybeEmitInheritedConstructorNote(S, Fn);
7249 return;
7250 }
7251 }
7252
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007253 // Emit the generic diagnostic and, optionally, add the hints to it.
7254 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7255 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00007256 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007257 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7258 << (unsigned) (Cand->Fix.Kind);
7259
7260 // If we can fix the conversion, suggest the FixIts.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007261 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007262 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7263 HI != HE; ++HI)
7264 FDiag << *HI;
7265 S.Diag(Fn->getLocation(), FDiag);
7266
Sebastian Redlf677ea32011-02-05 19:23:19 +00007267 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00007268}
7269
7270void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7271 unsigned NumFormalArgs) {
7272 // TODO: treat calls to a missing default constructor as a special case
7273
7274 FunctionDecl *Fn = Cand->Function;
7275 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7276
7277 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007278
Douglas Gregor439d3c32011-05-05 00:13:13 +00007279 // With invalid overloaded operators, it's possible that we think we
7280 // have an arity mismatch when it fact it looks like we have the
7281 // right number of arguments, because only overloaded operators have
7282 // the weird behavior of overloading member and non-member functions.
7283 // Just don't report anything.
7284 if (Fn->isInvalidDecl() &&
7285 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7286 return;
7287
John McCalladbb8f82010-01-13 09:16:55 +00007288 // at least / at most / exactly
7289 unsigned mode, modeCount;
7290 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00007291 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7292 (Cand->FailureKind == ovl_fail_bad_deduction &&
7293 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007294 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00007295 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00007296 mode = 0; // "at least"
7297 else
7298 mode = 2; // "exactly"
7299 modeCount = MinParams;
7300 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00007301 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7302 (Cand->FailureKind == ovl_fail_bad_deduction &&
7303 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00007304 if (MinParams != FnTy->getNumArgs())
7305 mode = 1; // "at most"
7306 else
7307 mode = 2; // "exactly"
7308 modeCount = FnTy->getNumArgs();
7309 }
7310
7311 std::string Description;
7312 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7313
7314 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007315 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregora18592e2010-05-08 18:13:28 +00007316 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007317 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00007318}
7319
John McCall342fec42010-02-01 18:53:26 +00007320/// Diagnose a failed template-argument deduction.
7321void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7322 Expr **Args, unsigned NumArgs) {
7323 FunctionDecl *Fn = Cand->Function; // pattern
7324
Douglas Gregora9333192010-05-08 17:41:32 +00007325 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00007326 NamedDecl *ParamD;
7327 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7328 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7329 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00007330 switch (Cand->DeductionFailure.Result) {
7331 case Sema::TDK_Success:
7332 llvm_unreachable("TDK_success while diagnosing bad deduction");
7333
7334 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00007335 assert(ParamD && "no parameter found for incomplete deduction result");
7336 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7337 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007338 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00007339 return;
7340 }
7341
John McCall57e97782010-08-05 09:05:08 +00007342 case Sema::TDK_Underqualified: {
7343 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7344 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7345
7346 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7347
7348 // Param will have been canonicalized, but it should just be a
7349 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00007350 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00007351 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00007352 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00007353 assert(S.Context.hasSameType(Param, NonCanonParam));
7354
7355 // Arg has also been canonicalized, but there's nothing we can do
7356 // about that. It also doesn't matter as much, because it won't
7357 // have any template parameters in it (because deduction isn't
7358 // done on dependent types).
7359 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7360
7361 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7362 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007363 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00007364 return;
7365 }
7366
7367 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00007368 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00007369 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00007370 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00007371 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00007372 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00007373 which = 1;
7374 else {
Douglas Gregora9333192010-05-08 17:41:32 +00007375 which = 2;
7376 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007377
Douglas Gregora9333192010-05-08 17:41:32 +00007378 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007379 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00007380 << *Cand->DeductionFailure.getFirstArg()
7381 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007382 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00007383 return;
7384 }
Douglas Gregora18592e2010-05-08 18:13:28 +00007385
Douglas Gregorf1a84452010-05-08 19:15:54 +00007386 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007387 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00007388 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007389 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00007390 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7391 << ParamD->getDeclName();
7392 else {
7393 int index = 0;
7394 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7395 index = TTP->getIndex();
7396 else if (NonTypeTemplateParmDecl *NTTP
7397 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7398 index = NTTP->getIndex();
7399 else
7400 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007401 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00007402 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7403 << (index + 1);
7404 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00007405 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00007406 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007407
Douglas Gregora18592e2010-05-08 18:13:28 +00007408 case Sema::TDK_TooManyArguments:
7409 case Sema::TDK_TooFewArguments:
7410 DiagnoseArityMismatch(S, Cand, NumArgs);
7411 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00007412
7413 case Sema::TDK_InstantiationDepth:
7414 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007415 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00007416 return;
7417
7418 case Sema::TDK_SubstitutionFailure: {
7419 std::string ArgString;
7420 if (TemplateArgumentList *Args
7421 = Cand->DeductionFailure.getTemplateArgumentList())
7422 ArgString = S.getTemplateArgumentBindingsText(
7423 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7424 *Args);
7425 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7426 << ArgString;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007427 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00007428 return;
7429 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007430
John McCall342fec42010-02-01 18:53:26 +00007431 // TODO: diagnose these individually, then kill off
7432 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00007433 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00007434 case Sema::TDK_FailedOverloadResolution:
7435 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007436 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00007437 return;
7438 }
7439}
7440
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00007441/// CUDA: diagnose an invalid call across targets.
7442void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7443 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7444 FunctionDecl *Callee = Cand->Function;
7445
7446 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7447 CalleeTarget = S.IdentifyCUDATarget(Callee);
7448
7449 std::string FnDesc;
7450 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7451
7452 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7453 << (unsigned) FnKind << CalleeTarget << CallerTarget;
7454}
7455
John McCall342fec42010-02-01 18:53:26 +00007456/// Generates a 'note' diagnostic for an overload candidate. We've
7457/// already generated a primary error at the call site.
7458///
7459/// It really does need to be a single diagnostic with its caret
7460/// pointed at the candidate declaration. Yes, this creates some
7461/// major challenges of technical writing. Yes, this makes pointing
7462/// out problems with specific arguments quite awkward. It's still
7463/// better than generating twenty screens of text for every failed
7464/// overload.
7465///
7466/// It would be great to be able to express per-candidate problems
7467/// more richly for those diagnostic clients that cared, but we'd
7468/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00007469void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7470 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00007471 FunctionDecl *Fn = Cand->Function;
7472
John McCall81201622010-01-08 04:41:39 +00007473 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007474 if (Cand->Viable && (Fn->isDeleted() ||
7475 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00007476 std::string FnDesc;
7477 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00007478
7479 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00007480 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007481 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00007482 return;
John McCall81201622010-01-08 04:41:39 +00007483 }
7484
John McCall220ccbf2010-01-13 00:25:19 +00007485 // We don't really have anything else to say about viable candidates.
7486 if (Cand->Viable) {
7487 S.NoteOverloadCandidate(Fn);
7488 return;
7489 }
John McCall1d318332010-01-12 00:44:57 +00007490
John McCalladbb8f82010-01-13 09:16:55 +00007491 switch (Cand->FailureKind) {
7492 case ovl_fail_too_many_arguments:
7493 case ovl_fail_too_few_arguments:
7494 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00007495
John McCalladbb8f82010-01-13 09:16:55 +00007496 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00007497 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7498
John McCall717e8912010-01-23 05:17:32 +00007499 case ovl_fail_trivial_conversion:
7500 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00007501 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00007502 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00007503
John McCallb1bdc622010-02-25 01:37:24 +00007504 case ovl_fail_bad_conversion: {
7505 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7506 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00007507 if (Cand->Conversions[I].isBad())
7508 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007509
John McCalladbb8f82010-01-13 09:16:55 +00007510 // FIXME: this currently happens when we're called from SemaInit
7511 // when user-conversion overload fails. Figure out how to handle
7512 // those conditions and diagnose them well.
7513 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00007514 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00007515
7516 case ovl_fail_bad_target:
7517 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00007518 }
John McCalla1d7d622010-01-08 00:58:21 +00007519}
7520
7521void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7522 // Desugar the type of the surrogate down to a function type,
7523 // retaining as many typedefs as possible while still showing
7524 // the function type (and, therefore, its parameter types).
7525 QualType FnType = Cand->Surrogate->getConversionType();
7526 bool isLValueReference = false;
7527 bool isRValueReference = false;
7528 bool isPointer = false;
7529 if (const LValueReferenceType *FnTypeRef =
7530 FnType->getAs<LValueReferenceType>()) {
7531 FnType = FnTypeRef->getPointeeType();
7532 isLValueReference = true;
7533 } else if (const RValueReferenceType *FnTypeRef =
7534 FnType->getAs<RValueReferenceType>()) {
7535 FnType = FnTypeRef->getPointeeType();
7536 isRValueReference = true;
7537 }
7538 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7539 FnType = FnTypePtr->getPointeeType();
7540 isPointer = true;
7541 }
7542 // Desugar down to a function type.
7543 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7544 // Reconstruct the pointer/reference as appropriate.
7545 if (isPointer) FnType = S.Context.getPointerType(FnType);
7546 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7547 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7548
7549 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7550 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007551 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00007552}
7553
7554void NoteBuiltinOperatorCandidate(Sema &S,
7555 const char *Opc,
7556 SourceLocation OpLoc,
7557 OverloadCandidate *Cand) {
7558 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7559 std::string TypeStr("operator");
7560 TypeStr += Opc;
7561 TypeStr += "(";
7562 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7563 if (Cand->Conversions.size() == 1) {
7564 TypeStr += ")";
7565 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7566 } else {
7567 TypeStr += ", ";
7568 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7569 TypeStr += ")";
7570 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7571 }
7572}
7573
7574void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7575 OverloadCandidate *Cand) {
7576 unsigned NoOperands = Cand->Conversions.size();
7577 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7578 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00007579 if (ICS.isBad()) break; // all meaningless after first invalid
7580 if (!ICS.isAmbiguous()) continue;
7581
John McCall120d63c2010-08-24 20:38:10 +00007582 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007583 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00007584 }
7585}
7586
John McCall1b77e732010-01-15 23:32:50 +00007587SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7588 if (Cand->Function)
7589 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00007590 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00007591 return Cand->Surrogate->getLocation();
7592 return SourceLocation();
7593}
7594
Benjamin Kramerafc5b152011-09-10 21:52:04 +00007595static unsigned
7596RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00007597 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007598 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00007599 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00007600
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007601 case Sema::TDK_Incomplete:
7602 return 1;
7603
7604 case Sema::TDK_Underqualified:
7605 case Sema::TDK_Inconsistent:
7606 return 2;
7607
7608 case Sema::TDK_SubstitutionFailure:
7609 case Sema::TDK_NonDeducedMismatch:
7610 return 3;
7611
7612 case Sema::TDK_InstantiationDepth:
7613 case Sema::TDK_FailedOverloadResolution:
7614 return 4;
7615
7616 case Sema::TDK_InvalidExplicitArguments:
7617 return 5;
7618
7619 case Sema::TDK_TooManyArguments:
7620 case Sema::TDK_TooFewArguments:
7621 return 6;
7622 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00007623 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007624}
7625
John McCallbf65c0b2010-01-12 00:48:53 +00007626struct CompareOverloadCandidatesForDisplay {
7627 Sema &S;
7628 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00007629
7630 bool operator()(const OverloadCandidate *L,
7631 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00007632 // Fast-path this check.
7633 if (L == R) return false;
7634
John McCall81201622010-01-08 04:41:39 +00007635 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00007636 if (L->Viable) {
7637 if (!R->Viable) return true;
7638
7639 // TODO: introduce a tri-valued comparison for overload
7640 // candidates. Would be more worthwhile if we had a sort
7641 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00007642 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7643 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00007644 } else if (R->Viable)
7645 return false;
John McCall81201622010-01-08 04:41:39 +00007646
John McCall1b77e732010-01-15 23:32:50 +00007647 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00007648
John McCall1b77e732010-01-15 23:32:50 +00007649 // Criteria by which we can sort non-viable candidates:
7650 if (!L->Viable) {
7651 // 1. Arity mismatches come after other candidates.
7652 if (L->FailureKind == ovl_fail_too_many_arguments ||
7653 L->FailureKind == ovl_fail_too_few_arguments)
7654 return false;
7655 if (R->FailureKind == ovl_fail_too_many_arguments ||
7656 R->FailureKind == ovl_fail_too_few_arguments)
7657 return true;
John McCall81201622010-01-08 04:41:39 +00007658
John McCall717e8912010-01-23 05:17:32 +00007659 // 2. Bad conversions come first and are ordered by the number
7660 // of bad conversions and quality of good conversions.
7661 if (L->FailureKind == ovl_fail_bad_conversion) {
7662 if (R->FailureKind != ovl_fail_bad_conversion)
7663 return true;
7664
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007665 // The conversion that can be fixed with a smaller number of changes,
7666 // comes first.
7667 unsigned numLFixes = L->Fix.NumConversionsFixed;
7668 unsigned numRFixes = R->Fix.NumConversionsFixed;
7669 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7670 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00007671 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007672 if (numLFixes < numRFixes)
7673 return true;
7674 else
7675 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00007676 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007677
John McCall717e8912010-01-23 05:17:32 +00007678 // If there's any ordering between the defined conversions...
7679 // FIXME: this might not be transitive.
7680 assert(L->Conversions.size() == R->Conversions.size());
7681
7682 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00007683 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7684 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00007685 switch (CompareImplicitConversionSequences(S,
7686 L->Conversions[I],
7687 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00007688 case ImplicitConversionSequence::Better:
7689 leftBetter++;
7690 break;
7691
7692 case ImplicitConversionSequence::Worse:
7693 leftBetter--;
7694 break;
7695
7696 case ImplicitConversionSequence::Indistinguishable:
7697 break;
7698 }
7699 }
7700 if (leftBetter > 0) return true;
7701 if (leftBetter < 0) return false;
7702
7703 } else if (R->FailureKind == ovl_fail_bad_conversion)
7704 return false;
7705
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007706 if (L->FailureKind == ovl_fail_bad_deduction) {
7707 if (R->FailureKind != ovl_fail_bad_deduction)
7708 return true;
7709
7710 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7711 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00007712 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00007713 } else if (R->FailureKind == ovl_fail_bad_deduction)
7714 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007715
John McCall1b77e732010-01-15 23:32:50 +00007716 // TODO: others?
7717 }
7718
7719 // Sort everything else by location.
7720 SourceLocation LLoc = GetLocationForCandidate(L);
7721 SourceLocation RLoc = GetLocationForCandidate(R);
7722
7723 // Put candidates without locations (e.g. builtins) at the end.
7724 if (LLoc.isInvalid()) return false;
7725 if (RLoc.isInvalid()) return true;
7726
7727 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00007728 }
7729};
7730
John McCall717e8912010-01-23 05:17:32 +00007731/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007732/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00007733void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7734 Expr **Args, unsigned NumArgs) {
7735 assert(!Cand->Viable);
7736
7737 // Don't do anything on failures other than bad conversion.
7738 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7739
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007740 // We only want the FixIts if all the arguments can be corrected.
7741 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00007742 // Use a implicit copy initialization to check conversion fixes.
7743 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007744
John McCall717e8912010-01-23 05:17:32 +00007745 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00007746 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00007747 unsigned ConvCount = Cand->Conversions.size();
7748 while (true) {
7749 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7750 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007751 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00007752 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00007753 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007754 }
John McCall717e8912010-01-23 05:17:32 +00007755 }
7756
7757 if (ConvIdx == ConvCount)
7758 return;
7759
John McCallb1bdc622010-02-25 01:37:24 +00007760 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7761 "remaining conversion is initialized?");
7762
Douglas Gregor23ef6c02010-04-16 17:45:54 +00007763 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00007764 // operation somehow.
7765 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00007766
7767 const FunctionProtoType* Proto;
7768 unsigned ArgIdx = ConvIdx;
7769
7770 if (Cand->IsSurrogate) {
7771 QualType ConvType
7772 = Cand->Surrogate->getConversionType().getNonReferenceType();
7773 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7774 ConvType = ConvPtrType->getPointeeType();
7775 Proto = ConvType->getAs<FunctionProtoType>();
7776 ArgIdx--;
7777 } else if (Cand->Function) {
7778 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7779 if (isa<CXXMethodDecl>(Cand->Function) &&
7780 !isa<CXXConstructorDecl>(Cand->Function))
7781 ArgIdx--;
7782 } else {
7783 // Builtin binary operator with a bad first conversion.
7784 assert(ConvCount <= 3);
7785 for (; ConvIdx != ConvCount; ++ConvIdx)
7786 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00007787 = TryCopyInitialization(S, Args[ConvIdx],
7788 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007789 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00007790 /*InOverloadResolution*/ true,
7791 /*AllowObjCWritebackConversion=*/
7792 S.getLangOptions().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00007793 return;
7794 }
7795
7796 // Fill in the rest of the conversions.
7797 unsigned NumArgsInProto = Proto->getNumArgs();
7798 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007799 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00007800 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00007801 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007802 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00007803 /*InOverloadResolution=*/true,
7804 /*AllowObjCWritebackConversion=*/
7805 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007806 // Store the FixIt in the candidate if it exists.
7807 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00007808 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007809 }
John McCall717e8912010-01-23 05:17:32 +00007810 else
7811 Cand->Conversions[ConvIdx].setEllipsis();
7812 }
7813}
7814
John McCalla1d7d622010-01-08 00:58:21 +00007815} // end anonymous namespace
7816
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007817/// PrintOverloadCandidates - When overload resolution fails, prints
7818/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00007819/// set.
John McCall120d63c2010-08-24 20:38:10 +00007820void OverloadCandidateSet::NoteCandidates(Sema &S,
7821 OverloadCandidateDisplayKind OCD,
7822 Expr **Args, unsigned NumArgs,
7823 const char *Opc,
7824 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00007825 // Sort the candidates by viability and position. Sorting directly would
7826 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007827 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00007828 if (OCD == OCD_AllCandidates) Cands.reserve(size());
7829 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00007830 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00007831 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00007832 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00007833 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007834 if (Cand->Function || Cand->IsSurrogate)
7835 Cands.push_back(Cand);
7836 // Otherwise, this a non-viable builtin candidate. We do not, in general,
7837 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00007838 }
7839 }
7840
John McCallbf65c0b2010-01-12 00:48:53 +00007841 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00007842 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007843
John McCall1d318332010-01-12 00:44:57 +00007844 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00007845
Chris Lattner5f9e2722011-07-23 10:55:15 +00007846 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikied6471f72011-09-25 23:23:43 +00007847 const DiagnosticsEngine::OverloadsShown ShowOverloads =
7848 S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007849 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00007850 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
7851 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00007852
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007853 // Set an arbitrary limit on the number of candidate functions we'll spam
7854 // the user with. FIXME: This limit should depend on details of the
7855 // candidate list.
David Blaikied6471f72011-09-25 23:23:43 +00007856 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007857 break;
7858 }
7859 ++CandsShown;
7860
John McCalla1d7d622010-01-08 00:58:21 +00007861 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00007862 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00007863 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00007864 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007865 else {
7866 assert(Cand->Viable &&
7867 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00007868 // Generally we only see ambiguities including viable builtin
7869 // operators if overload resolution got screwed up by an
7870 // ambiguous user-defined conversion.
7871 //
7872 // FIXME: It's quite possible for different conversions to see
7873 // different ambiguities, though.
7874 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00007875 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00007876 ReportedAmbiguousConversions = true;
7877 }
John McCalla1d7d622010-01-08 00:58:21 +00007878
John McCall1d318332010-01-12 00:44:57 +00007879 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00007880 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00007881 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007882 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00007883
7884 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00007885 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007886}
7887
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007888// [PossiblyAFunctionType] --> [Return]
7889// NonFunctionType --> NonFunctionType
7890// R (A) --> R(A)
7891// R (*)(A) --> R (A)
7892// R (&)(A) --> R (A)
7893// R (S::*)(A) --> R (A)
7894QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
7895 QualType Ret = PossiblyAFunctionType;
7896 if (const PointerType *ToTypePtr =
7897 PossiblyAFunctionType->getAs<PointerType>())
7898 Ret = ToTypePtr->getPointeeType();
7899 else if (const ReferenceType *ToTypeRef =
7900 PossiblyAFunctionType->getAs<ReferenceType>())
7901 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00007902 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007903 PossiblyAFunctionType->getAs<MemberPointerType>())
7904 Ret = MemTypePtr->getPointeeType();
7905 Ret =
7906 Context.getCanonicalType(Ret).getUnqualifiedType();
7907 return Ret;
7908}
Douglas Gregor904eed32008-11-10 20:40:00 +00007909
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007910// A helper class to help with address of function resolution
7911// - allows us to avoid passing around all those ugly parameters
7912class AddressOfFunctionResolver
7913{
7914 Sema& S;
7915 Expr* SourceExpr;
7916 const QualType& TargetType;
7917 QualType TargetFunctionType; // Extracted function type from target type
7918
7919 bool Complain;
7920 //DeclAccessPair& ResultFunctionAccessPair;
7921 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007922
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007923 bool TargetTypeIsNonStaticMemberFunction;
7924 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007925
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007926 OverloadExpr::FindResult OvlExprInfo;
7927 OverloadExpr *OvlExpr;
7928 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00007929 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007930
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007931public:
7932 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
7933 const QualType& TargetType, bool Complain)
7934 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
7935 Complain(Complain), Context(S.getASTContext()),
7936 TargetTypeIsNonStaticMemberFunction(
7937 !!TargetType->getAs<MemberPointerType>()),
7938 FoundNonTemplateFunction(false),
7939 OvlExprInfo(OverloadExpr::find(SourceExpr)),
7940 OvlExpr(OvlExprInfo.Expression)
7941 {
7942 ExtractUnqualifiedFunctionTypeFromTargetType();
7943
7944 if (!TargetFunctionType->isFunctionType()) {
7945 if (OvlExpr->hasExplicitTemplateArgs()) {
7946 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00007947 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007948 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00007949
7950 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
7951 if (!Method->isStatic()) {
7952 // If the target type is a non-function type and the function
7953 // found is a non-static member function, pretend as if that was
7954 // the target, it's the only possible type to end up with.
7955 TargetTypeIsNonStaticMemberFunction = true;
7956
7957 // And skip adding the function if its not in the proper form.
7958 // We'll diagnose this due to an empty set of functions.
7959 if (!OvlExprInfo.HasFormOfMemberPointer)
7960 return;
7961 }
7962 }
7963
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007964 Matches.push_back(std::make_pair(dap,Fn));
7965 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00007966 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007967 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00007968 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007969
7970 if (OvlExpr->hasExplicitTemplateArgs())
7971 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00007972
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007973 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
7974 // C++ [over.over]p4:
7975 // If more than one function is selected, [...]
7976 if (Matches.size() > 1) {
7977 if (FoundNonTemplateFunction)
7978 EliminateAllTemplateMatches();
7979 else
7980 EliminateAllExceptMostSpecializedTemplate();
7981 }
7982 }
7983 }
7984
7985private:
7986 bool isTargetTypeAFunction() const {
7987 return TargetFunctionType->isFunctionType();
7988 }
7989
7990 // [ToType] [Return]
7991
7992 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
7993 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
7994 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
7995 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
7996 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
7997 }
7998
7999 // return true if any matching specializations were found
8000 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8001 const DeclAccessPair& CurAccessFunPair) {
8002 if (CXXMethodDecl *Method
8003 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8004 // Skip non-static function templates when converting to pointer, and
8005 // static when converting to member pointer.
8006 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8007 return false;
8008 }
8009 else if (TargetTypeIsNonStaticMemberFunction)
8010 return false;
8011
8012 // C++ [over.over]p2:
8013 // If the name is a function template, template argument deduction is
8014 // done (14.8.2.2), and if the argument deduction succeeds, the
8015 // resulting template argument list is used to generate a single
8016 // function template specialization, which is added to the set of
8017 // overloaded functions considered.
8018 FunctionDecl *Specialization = 0;
8019 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8020 if (Sema::TemplateDeductionResult Result
8021 = S.DeduceTemplateArguments(FunctionTemplate,
8022 &OvlExplicitTemplateArgs,
8023 TargetFunctionType, Specialization,
8024 Info)) {
8025 // FIXME: make a note of the failed deduction for diagnostics.
8026 (void)Result;
8027 return false;
8028 }
8029
8030 // Template argument deduction ensures that we have an exact match.
8031 // This function template specicalization works.
8032 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8033 assert(TargetFunctionType
8034 == Context.getCanonicalType(Specialization->getType()));
8035 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8036 return true;
8037 }
8038
8039 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8040 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00008041 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00008042 // Skip non-static functions when converting to pointer, and static
8043 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008044 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8045 return false;
8046 }
8047 else if (TargetTypeIsNonStaticMemberFunction)
8048 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00008049
Chandler Carruthbd647292009-12-29 06:17:27 +00008050 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008051 if (S.getLangOptions().CUDA)
8052 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8053 if (S.CheckCUDATarget(Caller, FunDecl))
8054 return false;
8055
Douglas Gregor43c79c22009-12-09 00:47:37 +00008056 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008057 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8058 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00008059 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8060 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008061 Matches.push_back(std::make_pair(CurAccessFunPair,
8062 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00008063 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008064 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00008065 }
Mike Stump1eb44332009-09-09 15:08:12 +00008066 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008067
8068 return false;
8069 }
8070
8071 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8072 bool Ret = false;
8073
8074 // If the overload expression doesn't have the form of a pointer to
8075 // member, don't try to convert it to a pointer-to-member type.
8076 if (IsInvalidFormOfPointerToMemberFunction())
8077 return false;
8078
8079 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8080 E = OvlExpr->decls_end();
8081 I != E; ++I) {
8082 // Look through any using declarations to find the underlying function.
8083 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8084
8085 // C++ [over.over]p3:
8086 // Non-member functions and static member functions match
8087 // targets of type "pointer-to-function" or "reference-to-function."
8088 // Nonstatic member functions match targets of
8089 // type "pointer-to-member-function."
8090 // Note that according to DR 247, the containing class does not matter.
8091 if (FunctionTemplateDecl *FunctionTemplate
8092 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8093 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8094 Ret = true;
8095 }
8096 // If we have explicit template arguments supplied, skip non-templates.
8097 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8098 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8099 Ret = true;
8100 }
8101 assert(Ret || Matches.empty());
8102 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00008103 }
8104
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008105 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00008106 // [...] and any given function template specialization F1 is
8107 // eliminated if the set contains a second function template
8108 // specialization whose function template is more specialized
8109 // than the function template of F1 according to the partial
8110 // ordering rules of 14.5.5.2.
8111
8112 // The algorithm specified above is quadratic. We instead use a
8113 // two-pass algorithm (similar to the one used to identify the
8114 // best viable function in an overload set) that identifies the
8115 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00008116
8117 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8118 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8119 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008120
John McCallc373d482010-01-27 01:50:18 +00008121 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008122 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8123 TPOC_Other, 0, SourceExpr->getLocStart(),
8124 S.PDiag(),
8125 S.PDiag(diag::err_addr_ovl_ambiguous)
8126 << Matches[0].second->getDeclName(),
8127 S.PDiag(diag::note_ovl_candidate)
8128 << (unsigned) oc_function_template,
8129 Complain);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008130
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008131 if (Result != MatchesCopy.end()) {
8132 // Make it the first and only element
8133 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8134 Matches[0].second = cast<FunctionDecl>(*Result);
8135 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00008136 }
8137 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008138
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008139 void EliminateAllTemplateMatches() {
8140 // [...] any function template specializations in the set are
8141 // eliminated if the set also contains a non-template function, [...]
8142 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8143 if (Matches[I].second->getPrimaryTemplate() == 0)
8144 ++I;
8145 else {
8146 Matches[I] = Matches[--N];
8147 Matches.set_size(N);
8148 }
8149 }
8150 }
8151
8152public:
8153 void ComplainNoMatchesFound() const {
8154 assert(Matches.empty());
8155 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8156 << OvlExpr->getName() << TargetFunctionType
8157 << OvlExpr->getSourceRange();
8158 S.NoteAllOverloadCandidates(OvlExpr);
8159 }
8160
8161 bool IsInvalidFormOfPointerToMemberFunction() const {
8162 return TargetTypeIsNonStaticMemberFunction &&
8163 !OvlExprInfo.HasFormOfMemberPointer;
8164 }
8165
8166 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8167 // TODO: Should we condition this on whether any functions might
8168 // have matched, or is it more appropriate to do that in callers?
8169 // TODO: a fixit wouldn't hurt.
8170 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8171 << TargetType << OvlExpr->getSourceRange();
8172 }
8173
8174 void ComplainOfInvalidConversion() const {
8175 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8176 << OvlExpr->getName() << TargetType;
8177 }
8178
8179 void ComplainMultipleMatchesFound() const {
8180 assert(Matches.size() > 1);
8181 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8182 << OvlExpr->getName()
8183 << OvlExpr->getSourceRange();
8184 S.NoteAllOverloadCandidates(OvlExpr);
8185 }
8186
8187 int getNumMatches() const { return Matches.size(); }
8188
8189 FunctionDecl* getMatchingFunctionDecl() const {
8190 if (Matches.size() != 1) return 0;
8191 return Matches[0].second;
8192 }
8193
8194 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8195 if (Matches.size() != 1) return 0;
8196 return &Matches[0].first;
8197 }
8198};
8199
8200/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8201/// an overloaded function (C++ [over.over]), where @p From is an
8202/// expression with overloaded function type and @p ToType is the type
8203/// we're trying to resolve to. For example:
8204///
8205/// @code
8206/// int f(double);
8207/// int f(int);
8208///
8209/// int (*pfd)(double) = f; // selects f(double)
8210/// @endcode
8211///
8212/// This routine returns the resulting FunctionDecl if it could be
8213/// resolved, and NULL otherwise. When @p Complain is true, this
8214/// routine will emit diagnostics if there is an error.
8215FunctionDecl *
8216Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr, QualType TargetType,
8217 bool Complain,
8218 DeclAccessPair &FoundResult) {
8219
8220 assert(AddressOfExpr->getType() == Context.OverloadTy);
8221
8222 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType, Complain);
8223 int NumMatches = Resolver.getNumMatches();
8224 FunctionDecl* Fn = 0;
8225 if ( NumMatches == 0 && Complain) {
8226 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8227 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8228 else
8229 Resolver.ComplainNoMatchesFound();
8230 }
8231 else if (NumMatches > 1 && Complain)
8232 Resolver.ComplainMultipleMatchesFound();
8233 else if (NumMatches == 1) {
8234 Fn = Resolver.getMatchingFunctionDecl();
8235 assert(Fn);
8236 FoundResult = *Resolver.getMatchingFunctionAccessPair();
8237 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00008238 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008239 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00008240 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008241
8242 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00008243}
8244
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008245/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00008246/// resolve that overloaded function expression down to a single function.
8247///
8248/// This routine can only resolve template-ids that refer to a single function
8249/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008250/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00008251/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00008252FunctionDecl *
8253Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8254 bool Complain,
8255 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00008256 // C++ [over.over]p1:
8257 // [...] [Note: any redundant set of parentheses surrounding the
8258 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00008259 // C++ [over.over]p1:
8260 // [...] The overloaded function name can be preceded by the &
8261 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008262
Douglas Gregor4b52e252009-12-21 23:17:24 +00008263 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00008264 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00008265 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00008266
8267 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00008268 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008269
Douglas Gregor4b52e252009-12-21 23:17:24 +00008270 // Look through all of the overloaded functions, searching for one
8271 // whose type matches exactly.
8272 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00008273 for (UnresolvedSetIterator I = ovl->decls_begin(),
8274 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00008275 // C++0x [temp.arg.explicit]p3:
8276 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008277 // where deduction is not done, if a template argument list is
8278 // specified and it, along with any default template arguments,
8279 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00008280 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00008281 FunctionTemplateDecl *FunctionTemplate
8282 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008283
Douglas Gregor4b52e252009-12-21 23:17:24 +00008284 // C++ [over.over]p2:
8285 // If the name is a function template, template argument deduction is
8286 // done (14.8.2.2), and if the argument deduction succeeds, the
8287 // resulting template argument list is used to generate a single
8288 // function template specialization, which is added to the set of
8289 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00008290 FunctionDecl *Specialization = 0;
John McCall864c0412011-04-26 20:42:42 +00008291 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00008292 if (TemplateDeductionResult Result
8293 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8294 Specialization, Info)) {
8295 // FIXME: make a note of the failed deduction for diagnostics.
8296 (void)Result;
8297 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008298 }
8299
John McCall864c0412011-04-26 20:42:42 +00008300 assert(Specialization && "no specialization and no error?");
8301
Douglas Gregor4b52e252009-12-21 23:17:24 +00008302 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008303 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008304 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00008305 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8306 << ovl->getName();
8307 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008308 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00008309 return 0;
John McCall864c0412011-04-26 20:42:42 +00008310 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008311
John McCall864c0412011-04-26 20:42:42 +00008312 Matched = Specialization;
8313 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00008314 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008315
Douglas Gregor4b52e252009-12-21 23:17:24 +00008316 return Matched;
8317}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008318
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008319
8320
8321
John McCall6dbba4f2011-10-11 23:14:30 +00008322// Resolve and fix an overloaded expression that can be resolved
8323// because it identifies a single function template specialization.
8324//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008325// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00008326//
8327// Return true if it was logically possible to so resolve the
8328// expression, regardless of whether or not it succeeded. Always
8329// returns true if 'complain' is set.
8330bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8331 ExprResult &SrcExpr, bool doFunctionPointerConverion,
8332 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008333 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00008334 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00008335 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008336
John McCall6dbba4f2011-10-11 23:14:30 +00008337 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008338
John McCall864c0412011-04-26 20:42:42 +00008339 DeclAccessPair found;
8340 ExprResult SingleFunctionExpression;
8341 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8342 ovl.Expression, /*complain*/ false, &found)) {
John McCall6dbba4f2011-10-11 23:14:30 +00008343 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8344 SrcExpr = ExprError();
8345 return true;
8346 }
John McCall864c0412011-04-26 20:42:42 +00008347
8348 // It is only correct to resolve to an instance method if we're
8349 // resolving a form that's permitted to be a pointer to member.
8350 // Otherwise we'll end up making a bound member expression, which
8351 // is illegal in all the contexts we resolve like this.
8352 if (!ovl.HasFormOfMemberPointer &&
8353 isa<CXXMethodDecl>(fn) &&
8354 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00008355 if (!complain) return false;
8356
8357 Diag(ovl.Expression->getExprLoc(),
8358 diag::err_bound_member_function)
8359 << 0 << ovl.Expression->getSourceRange();
8360
8361 // TODO: I believe we only end up here if there's a mix of
8362 // static and non-static candidates (otherwise the expression
8363 // would have 'bound member' type, not 'overload' type).
8364 // Ideally we would note which candidate was chosen and why
8365 // the static candidates were rejected.
8366 SrcExpr = ExprError();
8367 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008368 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00008369
John McCall864c0412011-04-26 20:42:42 +00008370 // Fix the expresion to refer to 'fn'.
8371 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00008372 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00008373
8374 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00008375 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00008376 SingleFunctionExpression =
8377 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00008378 if (SingleFunctionExpression.isInvalid()) {
8379 SrcExpr = ExprError();
8380 return true;
8381 }
8382 }
John McCall864c0412011-04-26 20:42:42 +00008383 }
8384
8385 if (!SingleFunctionExpression.isUsable()) {
8386 if (complain) {
8387 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8388 << ovl.Expression->getName()
8389 << DestTypeForComplaining
8390 << OpRangeForComplaining
8391 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00008392 NoteAllOverloadCandidates(SrcExpr.get());
8393
8394 SrcExpr = ExprError();
8395 return true;
8396 }
8397
8398 return false;
John McCall864c0412011-04-26 20:42:42 +00008399 }
8400
John McCall6dbba4f2011-10-11 23:14:30 +00008401 SrcExpr = SingleFunctionExpression;
8402 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008403}
8404
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008405/// \brief Add a single candidate to the overload set.
8406static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00008407 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00008408 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008409 Expr **Args, unsigned NumArgs,
8410 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00008411 bool PartialOverloading,
8412 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00008413 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00008414 if (isa<UsingShadowDecl>(Callee))
8415 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8416
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008417 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00008418 if (ExplicitTemplateArgs) {
8419 assert(!KnownValid && "Explicit template arguments?");
8420 return;
8421 }
John McCall9aa472c2010-03-19 07:35:19 +00008422 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00008423 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008424 return;
John McCallba135432009-11-21 08:51:07 +00008425 }
8426
8427 if (FunctionTemplateDecl *FuncTemplate
8428 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00008429 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8430 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00008431 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00008432 return;
8433 }
8434
Richard Smith2ced0442011-06-26 22:19:54 +00008435 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008436}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008437
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008438/// \brief Add the overload candidates named by callee and/or found by argument
8439/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00008440void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008441 Expr **Args, unsigned NumArgs,
8442 OverloadCandidateSet &CandidateSet,
8443 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00008444
8445#ifndef NDEBUG
8446 // Verify that ArgumentDependentLookup is consistent with the rules
8447 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008448 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008449 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8450 // and let Y be the lookup set produced by argument dependent
8451 // lookup (defined as follows). If X contains
8452 //
8453 // -- a declaration of a class member, or
8454 //
8455 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00008456 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008457 //
8458 // -- a declaration that is neither a function or a function
8459 // template
8460 //
8461 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00008462
John McCall3b4294e2009-12-16 12:17:52 +00008463 if (ULE->requiresADL()) {
8464 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8465 E = ULE->decls_end(); I != E; ++I) {
8466 assert(!(*I)->getDeclContext()->isRecord());
8467 assert(isa<UsingShadowDecl>(*I) ||
8468 !(*I)->getDeclContext()->isFunctionOrMethod());
8469 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00008470 }
8471 }
8472#endif
8473
John McCall3b4294e2009-12-16 12:17:52 +00008474 // It would be nice to avoid this copy.
8475 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00008476 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00008477 if (ULE->hasExplicitTemplateArgs()) {
8478 ULE->copyTemplateArgumentsInto(TABuffer);
8479 ExplicitTemplateArgs = &TABuffer;
8480 }
8481
8482 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8483 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00008484 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008485 Args, NumArgs, CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00008486 PartialOverloading, /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00008487
John McCall3b4294e2009-12-16 12:17:52 +00008488 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00008489 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8490 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008491 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008492 CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00008493 PartialOverloading,
8494 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008495}
John McCall578b69b2009-12-16 08:11:27 +00008496
Richard Smithf50e88a2011-06-05 22:42:48 +00008497/// Attempt to recover from an ill-formed use of a non-dependent name in a
8498/// template, where the non-dependent name was declared after the template
8499/// was defined. This is common in code written for a compilers which do not
8500/// correctly implement two-stage name lookup.
8501///
8502/// Returns true if a viable candidate was found and a diagnostic was issued.
8503static bool
8504DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8505 const CXXScopeSpec &SS, LookupResult &R,
8506 TemplateArgumentListInfo *ExplicitTemplateArgs,
8507 Expr **Args, unsigned NumArgs) {
8508 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8509 return false;
8510
8511 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8512 SemaRef.LookupQualifiedName(R, DC);
8513
8514 if (!R.empty()) {
8515 R.suppressDiagnostics();
8516
8517 if (isa<CXXRecordDecl>(DC)) {
8518 // Don't diagnose names we find in classes; we get much better
8519 // diagnostics for these from DiagnoseEmptyLookup.
8520 R.clear();
8521 return false;
8522 }
8523
8524 OverloadCandidateSet Candidates(FnLoc);
8525 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8526 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8527 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith2ced0442011-06-26 22:19:54 +00008528 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00008529
8530 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00008531 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008532 // No viable functions. Don't bother the user with notes for functions
8533 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00008534 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00008535 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00008536 }
Richard Smithf50e88a2011-06-05 22:42:48 +00008537
8538 // Find the namespaces where ADL would have looked, and suggest
8539 // declaring the function there instead.
8540 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8541 Sema::AssociatedClassSet AssociatedClasses;
8542 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8543 AssociatedNamespaces,
8544 AssociatedClasses);
8545 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00008546 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00008547 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008548 for (Sema::AssociatedNamespaceSet::iterator
8549 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00008550 end = AssociatedNamespaces.end(); it != end; ++it) {
8551 if (!Std->Encloses(*it))
8552 SuggestedNamespaces.insert(*it);
8553 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00008554 } else {
8555 // Lacking the 'std::' namespace, use all of the associated namespaces.
8556 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00008557 }
8558
8559 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8560 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00008561 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008562 SemaRef.Diag(Best->Function->getLocation(),
8563 diag::note_not_found_by_two_phase_lookup)
8564 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00008565 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008566 SemaRef.Diag(Best->Function->getLocation(),
8567 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00008568 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00008569 } else {
8570 // FIXME: It would be useful to list the associated namespaces here,
8571 // but the diagnostics infrastructure doesn't provide a way to produce
8572 // a localized representation of a list of items.
8573 SemaRef.Diag(Best->Function->getLocation(),
8574 diag::note_not_found_by_two_phase_lookup)
8575 << R.getLookupName() << 2;
8576 }
8577
8578 // Try to recover by calling this function.
8579 return true;
8580 }
8581
8582 R.clear();
8583 }
8584
8585 return false;
8586}
8587
8588/// Attempt to recover from ill-formed use of a non-dependent operator in a
8589/// template, where the non-dependent operator was declared after the template
8590/// was defined.
8591///
8592/// Returns true if a viable candidate was found and a diagnostic was issued.
8593static bool
8594DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8595 SourceLocation OpLoc,
8596 Expr **Args, unsigned NumArgs) {
8597 DeclarationName OpName =
8598 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8599 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8600 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8601 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8602}
8603
John McCall578b69b2009-12-16 08:11:27 +00008604/// Attempts to recover from a call where no functions were found.
8605///
8606/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00008607static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00008608BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00008609 UnresolvedLookupExpr *ULE,
8610 SourceLocation LParenLoc,
8611 Expr **Args, unsigned NumArgs,
Richard Smithf50e88a2011-06-05 22:42:48 +00008612 SourceLocation RParenLoc,
8613 bool EmptyLookup) {
John McCall578b69b2009-12-16 08:11:27 +00008614
8615 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00008616 SS.Adopt(ULE->getQualifierLoc());
John McCall578b69b2009-12-16 08:11:27 +00008617
John McCall3b4294e2009-12-16 12:17:52 +00008618 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00008619 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00008620 if (ULE->hasExplicitTemplateArgs()) {
8621 ULE->copyTemplateArgumentsInto(TABuffer);
8622 ExplicitTemplateArgs = &TABuffer;
8623 }
8624
John McCall578b69b2009-12-16 08:11:27 +00008625 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8626 Sema::LookupOrdinaryName);
Richard Smithf50e88a2011-06-05 22:42:48 +00008627 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8628 ExplicitTemplateArgs, Args, NumArgs) &&
8629 (!EmptyLookup ||
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00008630 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00008631 ExplicitTemplateArgs, Args, NumArgs)))
John McCallf312b1e2010-08-26 23:41:50 +00008632 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00008633
John McCall3b4294e2009-12-16 12:17:52 +00008634 assert(!R.empty() && "lookup results empty despite recovery");
8635
8636 // Build an implicit member call if appropriate. Just drop the
8637 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00008638 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00008639 if ((*R.begin())->isCXXClassMember())
Chandler Carruth6df868e2010-12-12 08:17:55 +00008640 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8641 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00008642 else if (ExplicitTemplateArgs)
8643 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8644 else
8645 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8646
8647 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008648 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00008649
8650 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00008651 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00008652 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00008653 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00008654 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00008655}
Douglas Gregord7a95972010-06-08 17:35:15 +00008656
Douglas Gregorf6b89692008-11-26 05:54:23 +00008657/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00008658/// (which eventually refers to the declaration Func) and the call
8659/// arguments Args/NumArgs, attempt to resolve the function call down
8660/// to a specific function. If overload resolution succeeds, returns
8661/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00008662/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00008663/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00008664ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00008665Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00008666 SourceLocation LParenLoc,
8667 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00008668 SourceLocation RParenLoc,
8669 Expr *ExecConfig) {
John McCall3b4294e2009-12-16 12:17:52 +00008670#ifndef NDEBUG
8671 if (ULE->requiresADL()) {
8672 // To do ADL, we must have found an unqualified name.
8673 assert(!ULE->getQualifier() && "qualified name with ADL");
8674
8675 // We don't perform ADL for implicit declarations of builtins.
8676 // Verify that this was correctly set up.
8677 FunctionDecl *F;
8678 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8679 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8680 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00008681 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008682
John McCall3b4294e2009-12-16 12:17:52 +00008683 // We don't perform ADL in C.
8684 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00008685 } else
8686 assert(!ULE->isStdAssociatedNamespace() &&
8687 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00008688#endif
8689
John McCall5acb0c92011-10-17 18:40:02 +00008690 UnbridgedCastsSet UnbridgedCasts;
8691 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
8692 return ExprError();
8693
John McCall5769d612010-02-08 23:07:23 +00008694 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00008695
John McCall3b4294e2009-12-16 12:17:52 +00008696 // Add the functions denoted by the callee to the set of candidate
8697 // functions, including those from argument-dependent lookup.
8698 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00008699
8700 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00008701 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8702 // out if it fails.
Francois Pichet0f74d1e2011-09-07 00:14:57 +00008703 if (CandidateSet.empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00008704 // In Microsoft mode, if we are inside a template class member function then
8705 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00008706 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00008707 // classes.
Francois Pichetef04ecf2011-11-11 00:12:11 +00008708 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Sebastian Redl14b0c192011-09-24 17:48:00 +00008709 isa<CXXMethodDecl>(CurContext)) {
8710 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8711 Context.DependentTy, VK_RValue,
8712 RParenLoc);
8713 CE->setTypeDependent(true);
8714 return Owned(CE);
8715 }
Douglas Gregor1aae80b2010-04-14 20:27:54 +00008716 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smithf50e88a2011-06-05 22:42:48 +00008717 RParenLoc, /*EmptyLookup=*/true);
Francois Pichet0f74d1e2011-09-07 00:14:57 +00008718 }
John McCall578b69b2009-12-16 08:11:27 +00008719
John McCall5acb0c92011-10-17 18:40:02 +00008720 UnbridgedCasts.restore();
8721
Douglas Gregorf6b89692008-11-26 05:54:23 +00008722 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008723 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00008724 case OR_Success: {
8725 FunctionDecl *FDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00008726 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00008727 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall5acb0c92011-10-17 18:40:02 +00008728 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00008729 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00008730 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8731 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00008732 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00008733
Richard Smithf50e88a2011-06-05 22:42:48 +00008734 case OR_No_Viable_Function: {
8735 // Try to recover by looking for viable functions which the user might
8736 // have meant to call.
8737 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8738 Args, NumArgs, RParenLoc,
8739 /*EmptyLookup=*/false);
8740 if (!Recovery.isInvalid())
8741 return Recovery;
8742
Chris Lattner4330d652009-02-17 07:29:20 +00008743 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00008744 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00008745 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008746 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00008747 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00008748 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00008749
8750 case OR_Ambiguous:
8751 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00008752 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008753 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00008754 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008755
8756 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00008757 {
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00008758 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8759 << Best->Function->isDeleted()
8760 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00008761 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00008762 << Fn->getSourceRange();
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00008763 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00008764
8765 // We emitted an error for the unvailable/deleted function call but keep
8766 // the call in the AST.
8767 FunctionDecl *FDecl = Best->Function;
8768 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
8769 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
8770 RParenLoc, ExecConfig);
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00008771 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008772 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00008773 }
8774
Douglas Gregorff331c12010-07-25 18:17:45 +00008775 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00008776 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00008777}
8778
John McCall6e266892010-01-26 03:27:55 +00008779static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00008780 return Functions.size() > 1 ||
8781 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8782}
8783
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008784/// \brief Create a unary operation that may resolve to an overloaded
8785/// operator.
8786///
8787/// \param OpLoc The location of the operator itself (e.g., '*').
8788///
8789/// \param OpcIn The UnaryOperator::Opcode that describes this
8790/// operator.
8791///
8792/// \param Functions The set of non-member functions that will be
8793/// considered by overload resolution. The caller needs to build this
8794/// set based on the context using, e.g.,
8795/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8796/// set should not contain any member functions; those will be added
8797/// by CreateOverloadedUnaryOp().
8798///
8799/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00008800ExprResult
John McCall6e266892010-01-26 03:27:55 +00008801Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8802 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00008803 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008804 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008805
8806 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8807 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8808 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00008809 // TODO: provide better source location info.
8810 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008811
John McCall5acb0c92011-10-17 18:40:02 +00008812 if (checkPlaceholderForOverload(*this, Input))
8813 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00008814
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008815 Expr *Args[2] = { Input, 0 };
8816 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00008817
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008818 // For post-increment and post-decrement, add the implicit '0' as
8819 // the second argument, so that we know this is a post-increment or
8820 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00008821 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008822 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00008823 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
8824 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008825 NumArgs = 2;
8826 }
8827
8828 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00008829 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00008830 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008831 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00008832 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008833 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00008834 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008835
John McCallc373d482010-01-27 01:50:18 +00008836 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00008837 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00008838 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00008839 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00008840 /*ADL*/ true, IsOverloaded(Fns),
8841 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008842 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00008843 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008844 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00008845 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008846 OpLoc));
8847 }
8848
8849 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00008850 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008851
8852 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00008853 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008854
8855 // Add operator candidates that are member functions.
8856 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
8857
John McCall6e266892010-01-26 03:27:55 +00008858 // Add candidates from ADL.
8859 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00008860 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00008861 /*ExplicitTemplateArgs*/ 0,
8862 CandidateSet);
8863
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008864 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00008865 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008866
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008867 bool HadMultipleCandidates = (CandidateSet.size() > 1);
8868
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008869 // Perform overload resolution.
8870 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008871 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008872 case OR_Success: {
8873 // We found a built-in operator or an overloaded operator.
8874 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00008875
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008876 if (FnDecl) {
8877 // We matched an overloaded operator. Build a call to that
8878 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00008879
Chandler Carruth25ca4212011-02-25 19:41:05 +00008880 MarkDeclarationReferenced(OpLoc, FnDecl);
8881
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008882 // Convert the arguments.
8883 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00008884 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00008885
John Wiegley429bb272011-04-08 18:41:53 +00008886 ExprResult InputRes =
8887 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
8888 Best->FoundDecl, Method);
8889 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008890 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00008891 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008892 } else {
8893 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00008894 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00008895 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00008896 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00008897 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008898 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00008899 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00008900 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008901 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00008902 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008903 }
8904
John McCallb697e082010-05-06 18:15:07 +00008905 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
8906
John McCallf89e55a2010-11-18 06:31:45 +00008907 // Determine the result type.
8908 QualType ResultTy = FnDecl->getResultType();
8909 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8910 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00008911
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008912 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00008913 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
8914 HadMultipleCandidates);
John Wiegley429bb272011-04-08 18:41:53 +00008915 if (FnExpr.isInvalid())
8916 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00008917
Eli Friedman4c3b8962009-11-18 03:58:17 +00008918 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00008919 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00008920 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00008921 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00008922
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008923 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00008924 FnDecl))
8925 return ExprError();
8926
John McCall9ae2f072010-08-23 23:25:46 +00008927 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008928 } else {
8929 // We matched a built-in operator. Convert the arguments, then
8930 // break out so that we will build the appropriate built-in
8931 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00008932 ExprResult InputRes =
8933 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
8934 Best->Conversions[0], AA_Passing);
8935 if (InputRes.isInvalid())
8936 return ExprError();
8937 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008938 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008939 }
John Wiegley429bb272011-04-08 18:41:53 +00008940 }
8941
8942 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +00008943 // This is an erroneous use of an operator which can be overloaded by
8944 // a non-member function. Check for non-member operators which were
8945 // defined too late to be candidates.
8946 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
8947 // FIXME: Recover by calling the found function.
8948 return ExprError();
8949
John Wiegley429bb272011-04-08 18:41:53 +00008950 // No viable function; fall through to handling this as a
8951 // built-in operator, which will produce an error message for us.
8952 break;
8953
8954 case OR_Ambiguous:
8955 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8956 << UnaryOperator::getOpcodeStr(Opc)
8957 << Input->getType()
8958 << Input->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00008959 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley429bb272011-04-08 18:41:53 +00008960 UnaryOperator::getOpcodeStr(Opc), OpLoc);
8961 return ExprError();
8962
8963 case OR_Deleted:
8964 Diag(OpLoc, diag::err_ovl_deleted_oper)
8965 << Best->Function->isDeleted()
8966 << UnaryOperator::getOpcodeStr(Opc)
8967 << getDeletedOrUnavailableSuffix(Best->Function)
8968 << Input->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00008969 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
8970 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00008971 return ExprError();
8972 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008973
8974 // Either we found no viable overloaded operator or we matched a
8975 // built-in operator. In either case, fall through to trying to
8976 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00008977 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008978}
8979
Douglas Gregor063daf62009-03-13 18:40:31 +00008980/// \brief Create a binary operation that may resolve to an overloaded
8981/// operator.
8982///
8983/// \param OpLoc The location of the operator itself (e.g., '+').
8984///
8985/// \param OpcIn The BinaryOperator::Opcode that describes this
8986/// operator.
8987///
8988/// \param Functions The set of non-member functions that will be
8989/// considered by overload resolution. The caller needs to build this
8990/// set based on the context using, e.g.,
8991/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8992/// set should not contain any member functions; those will be added
8993/// by CreateOverloadedBinOp().
8994///
8995/// \param LHS Left-hand argument.
8996/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00008997ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00008998Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00008999 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00009000 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00009001 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00009002 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009003 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00009004
9005 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9006 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9007 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9008
9009 // If either side is type-dependent, create an appropriate dependent
9010 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009011 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00009012 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009013 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009014 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00009015 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009016 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00009017 Context.DependentTy,
9018 VK_RValue, OK_Ordinary,
9019 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009020
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009021 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9022 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009023 VK_LValue,
9024 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009025 Context.DependentTy,
9026 Context.DependentTy,
9027 OpLoc));
9028 }
John McCall6e266892010-01-26 03:27:55 +00009029
9030 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00009031 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00009032 // TODO: provide better source location info in DNLoc component.
9033 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00009034 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +00009035 = UnresolvedLookupExpr::Create(Context, NamingClass,
9036 NestedNameSpecifierLoc(), OpNameInfo,
9037 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009038 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00009039 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00009040 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00009041 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009042 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00009043 OpLoc));
9044 }
9045
John McCall5acb0c92011-10-17 18:40:02 +00009046 // Always do placeholder-like conversions on the RHS.
9047 if (checkPlaceholderForOverload(*this, Args[1]))
9048 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009049
John McCall3c3b7f92011-10-25 17:37:35 +00009050 // Do placeholder-like conversion on the LHS; note that we should
9051 // not get here with a PseudoObject LHS.
9052 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +00009053 if (checkPlaceholderForOverload(*this, Args[0]))
9054 return ExprError();
9055
Sebastian Redl275c2b42009-11-18 23:10:33 +00009056 // If this is the assignment operator, we only perform overload resolution
9057 // if the left-hand side is a class or enumeration type. This is actually
9058 // a hack. The standard requires that we do overload resolution between the
9059 // various built-in candidates, but as DR507 points out, this can lead to
9060 // problems. So we do it this way, which pretty much follows what GCC does.
9061 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00009062 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009063 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00009064
John McCall0e800c92010-12-04 08:14:53 +00009065 // If this is the .* operator, which is not overloadable, just
9066 // create a built-in binary operator.
9067 if (Opc == BO_PtrMemD)
9068 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9069
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009070 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009071 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009072
9073 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00009074 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00009075
9076 // Add operator candidates that are member functions.
9077 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9078
John McCall6e266892010-01-26 03:27:55 +00009079 // Add candidates from ADL.
9080 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9081 Args, 2,
9082 /*ExplicitTemplateArgs*/ 0,
9083 CandidateSet);
9084
Douglas Gregor063daf62009-03-13 18:40:31 +00009085 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009086 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00009087
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009088 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9089
Douglas Gregor063daf62009-03-13 18:40:31 +00009090 // Perform overload resolution.
9091 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009092 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00009093 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00009094 // We found a built-in operator or an overloaded operator.
9095 FunctionDecl *FnDecl = Best->Function;
9096
9097 if (FnDecl) {
9098 // We matched an overloaded operator. Build a call to that
9099 // operator.
9100
Chandler Carruth25ca4212011-02-25 19:41:05 +00009101 MarkDeclarationReferenced(OpLoc, FnDecl);
9102
Douglas Gregor063daf62009-03-13 18:40:31 +00009103 // Convert the arguments.
9104 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00009105 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00009106 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009107
Chandler Carruth6df868e2010-12-12 08:17:55 +00009108 ExprResult Arg1 =
9109 PerformCopyInitialization(
9110 InitializedEntity::InitializeParameter(Context,
9111 FnDecl->getParamDecl(0)),
9112 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009113 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009114 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009115
John Wiegley429bb272011-04-08 18:41:53 +00009116 ExprResult Arg0 =
9117 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9118 Best->FoundDecl, Method);
9119 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009120 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009121 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009122 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00009123 } else {
9124 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +00009125 ExprResult Arg0 = PerformCopyInitialization(
9126 InitializedEntity::InitializeParameter(Context,
9127 FnDecl->getParamDecl(0)),
9128 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009129 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009130 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009131
Chandler Carruth6df868e2010-12-12 08:17:55 +00009132 ExprResult Arg1 =
9133 PerformCopyInitialization(
9134 InitializedEntity::InitializeParameter(Context,
9135 FnDecl->getParamDecl(1)),
9136 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009137 if (Arg1.isInvalid())
9138 return ExprError();
9139 Args[0] = LHS = Arg0.takeAs<Expr>();
9140 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00009141 }
9142
John McCallb697e082010-05-06 18:15:07 +00009143 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9144
John McCallf89e55a2010-11-18 06:31:45 +00009145 // Determine the result type.
9146 QualType ResultTy = FnDecl->getResultType();
9147 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9148 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00009149
9150 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009151 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9152 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009153 if (FnExpr.isInvalid())
9154 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +00009155
John McCall9ae2f072010-08-23 23:25:46 +00009156 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009157 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009158 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009159
9160 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00009161 FnDecl))
9162 return ExprError();
9163
John McCall9ae2f072010-08-23 23:25:46 +00009164 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00009165 } else {
9166 // We matched a built-in operator. Convert the arguments, then
9167 // break out so that we will build the appropriate built-in
9168 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009169 ExprResult ArgsRes0 =
9170 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9171 Best->Conversions[0], AA_Passing);
9172 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009173 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009174 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00009175
John Wiegley429bb272011-04-08 18:41:53 +00009176 ExprResult ArgsRes1 =
9177 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9178 Best->Conversions[1], AA_Passing);
9179 if (ArgsRes1.isInvalid())
9180 return ExprError();
9181 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00009182 break;
9183 }
9184 }
9185
Douglas Gregor33074752009-09-30 21:46:01 +00009186 case OR_No_Viable_Function: {
9187 // C++ [over.match.oper]p9:
9188 // If the operator is the operator , [...] and there are no
9189 // viable functions, then the operator is assumed to be the
9190 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00009191 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00009192 break;
9193
Chandler Carruth6df868e2010-12-12 08:17:55 +00009194 // For class as left operand for assignment or compound assigment
9195 // operator do not fall through to handling in built-in, but report that
9196 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00009197 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009198 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00009199 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00009200 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9201 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009202 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00009203 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +00009204 // This is an erroneous use of an operator which can be overloaded by
9205 // a non-member function. Check for non-member operators which were
9206 // defined too late to be candidates.
9207 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9208 // FIXME: Recover by calling the found function.
9209 return ExprError();
9210
Douglas Gregor33074752009-09-30 21:46:01 +00009211 // No viable function; try to create a built-in operation, which will
9212 // produce an error. Then, show the non-viable candidates.
9213 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00009214 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009215 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +00009216 "C++ binary operator overloading is missing candidates!");
9217 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00009218 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9219 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00009220 return move(Result);
9221 }
Douglas Gregor063daf62009-03-13 18:40:31 +00009222
9223 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00009224 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +00009225 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00009226 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009227 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009228 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9229 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009230 return ExprError();
9231
9232 case OR_Deleted:
9233 Diag(OpLoc, diag::err_ovl_deleted_oper)
9234 << Best->Function->isDeleted()
9235 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009236 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009237 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00009238 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9239 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009240 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00009241 }
Douglas Gregor063daf62009-03-13 18:40:31 +00009242
Douglas Gregor33074752009-09-30 21:46:01 +00009243 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009244 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00009245}
9246
John McCall60d7b3a2010-08-24 06:29:42 +00009247ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00009248Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9249 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009250 Expr *Base, Expr *Idx) {
9251 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00009252 DeclarationName OpName =
9253 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9254
9255 // If either side is type-dependent, create an appropriate dependent
9256 // expression.
9257 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9258
John McCallc373d482010-01-27 01:50:18 +00009259 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00009260 // CHECKME: no 'operator' keyword?
9261 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9262 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00009263 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009264 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009265 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009266 /*ADL*/ true, /*Overloaded*/ false,
9267 UnresolvedSetIterator(),
9268 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00009269 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00009270
Sebastian Redlf322ed62009-10-29 20:17:01 +00009271 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9272 Args, 2,
9273 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009274 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +00009275 RLoc));
9276 }
9277
John McCall5acb0c92011-10-17 18:40:02 +00009278 // Handle placeholders on both operands.
9279 if (checkPlaceholderForOverload(*this, Args[0]))
9280 return ExprError();
9281 if (checkPlaceholderForOverload(*this, Args[1]))
9282 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009283
Sebastian Redlf322ed62009-10-29 20:17:01 +00009284 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009285 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009286
9287 // Subscript can only be overloaded as a member function.
9288
9289 // Add operator candidates that are member functions.
9290 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9291
9292 // Add builtin operator candidates.
9293 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9294
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009295 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9296
Sebastian Redlf322ed62009-10-29 20:17:01 +00009297 // Perform overload resolution.
9298 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009299 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00009300 case OR_Success: {
9301 // We found a built-in operator or an overloaded operator.
9302 FunctionDecl *FnDecl = Best->Function;
9303
9304 if (FnDecl) {
9305 // We matched an overloaded operator. Build a call to that
9306 // operator.
9307
Chandler Carruth25ca4212011-02-25 19:41:05 +00009308 MarkDeclarationReferenced(LLoc, FnDecl);
9309
John McCall9aa472c2010-03-19 07:35:19 +00009310 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009311 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00009312
Sebastian Redlf322ed62009-10-29 20:17:01 +00009313 // Convert the arguments.
9314 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +00009315 ExprResult Arg0 =
9316 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9317 Best->FoundDecl, Method);
9318 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +00009319 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009320 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +00009321
Anders Carlsson38f88ab2010-01-29 18:37:50 +00009322 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00009323 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00009324 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009325 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +00009326 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009327 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +00009328 Owned(Args[1]));
9329 if (InputInit.isInvalid())
9330 return ExprError();
9331
9332 Args[1] = InputInit.takeAs<Expr>();
9333
Sebastian Redlf322ed62009-10-29 20:17:01 +00009334 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +00009335 QualType ResultTy = FnDecl->getResultType();
9336 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9337 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009338
9339 // Build the actual expression node.
Douglas Gregor5b8968c2011-07-15 16:25:15 +00009340 DeclarationNameLoc LocInfo;
9341 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9342 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009343 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9344 HadMultipleCandidates,
9345 LLoc, LocInfo);
John Wiegley429bb272011-04-08 18:41:53 +00009346 if (FnExpr.isInvalid())
9347 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00009348
John McCall9ae2f072010-08-23 23:25:46 +00009349 CXXOperatorCallExpr *TheCall =
9350 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +00009351 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +00009352 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009353
John McCall9ae2f072010-08-23 23:25:46 +00009354 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00009355 FnDecl))
9356 return ExprError();
9357
John McCall9ae2f072010-08-23 23:25:46 +00009358 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009359 } else {
9360 // We matched a built-in operator. Convert the arguments, then
9361 // break out so that we will build the appropriate built-in
9362 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009363 ExprResult ArgsRes0 =
9364 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9365 Best->Conversions[0], AA_Passing);
9366 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +00009367 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009368 Args[0] = ArgsRes0.take();
9369
9370 ExprResult ArgsRes1 =
9371 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9372 Best->Conversions[1], AA_Passing);
9373 if (ArgsRes1.isInvalid())
9374 return ExprError();
9375 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +00009376
9377 break;
9378 }
9379 }
9380
9381 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00009382 if (CandidateSet.empty())
9383 Diag(LLoc, diag::err_ovl_no_oper)
9384 << Args[0]->getType() << /*subscript*/ 0
9385 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9386 else
9387 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9388 << Args[0]->getType()
9389 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009390 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9391 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00009392 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00009393 }
9394
9395 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00009396 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009397 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +00009398 << Args[0]->getType() << Args[1]->getType()
9399 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009400 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9401 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009402 return ExprError();
9403
9404 case OR_Deleted:
9405 Diag(LLoc, diag::err_ovl_deleted_oper)
9406 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009407 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +00009408 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009409 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9410 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009411 return ExprError();
9412 }
9413
9414 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00009415 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009416}
9417
Douglas Gregor88a35142008-12-22 05:46:06 +00009418/// BuildCallToMemberFunction - Build a call to a member
9419/// function. MemExpr is the expression that refers to the member
9420/// function (and includes the object parameter), Args/NumArgs are the
9421/// arguments to the function call (not including the object
9422/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +00009423/// expression refers to a non-static member function or an overloaded
9424/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +00009425ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00009426Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9427 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +00009428 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +00009429 assert(MemExprE->getType() == Context.BoundMemberTy ||
9430 MemExprE->getType() == Context.OverloadTy);
9431
Douglas Gregor88a35142008-12-22 05:46:06 +00009432 // Dig out the member expression. This holds both the object
9433 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00009434 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009435
John McCall864c0412011-04-26 20:42:42 +00009436 // Determine whether this is a call to a pointer-to-member function.
9437 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9438 assert(op->getType() == Context.BoundMemberTy);
9439 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9440
9441 QualType fnType =
9442 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9443
9444 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9445 QualType resultType = proto->getCallResultType(Context);
9446 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9447
9448 // Check that the object type isn't more qualified than the
9449 // member function we're calling.
9450 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9451
9452 QualType objectType = op->getLHS()->getType();
9453 if (op->getOpcode() == BO_PtrMemI)
9454 objectType = objectType->castAs<PointerType>()->getPointeeType();
9455 Qualifiers objectQuals = objectType.getQualifiers();
9456
9457 Qualifiers difference = objectQuals - funcQuals;
9458 difference.removeObjCGCAttr();
9459 difference.removeAddressSpace();
9460 if (difference) {
9461 std::string qualsString = difference.getAsString();
9462 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9463 << fnType.getUnqualifiedType()
9464 << qualsString
9465 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9466 }
9467
9468 CXXMemberCallExpr *call
9469 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9470 resultType, valueKind, RParenLoc);
9471
9472 if (CheckCallReturnType(proto->getResultType(),
9473 op->getRHS()->getSourceRange().getBegin(),
9474 call, 0))
9475 return ExprError();
9476
9477 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9478 return ExprError();
9479
9480 return MaybeBindToTemporary(call);
9481 }
9482
John McCall5acb0c92011-10-17 18:40:02 +00009483 UnbridgedCastsSet UnbridgedCasts;
9484 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9485 return ExprError();
9486
John McCall129e2df2009-11-30 22:42:35 +00009487 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00009488 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00009489 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00009490 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00009491 if (isa<MemberExpr>(NakedMemExpr)) {
9492 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00009493 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00009494 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00009495 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +00009496 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +00009497 } else {
9498 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00009499 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009500
John McCall701c89e2009-12-03 04:06:58 +00009501 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009502 Expr::Classification ObjectClassification
9503 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9504 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +00009505
Douglas Gregor88a35142008-12-22 05:46:06 +00009506 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00009507 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00009508
John McCallaa81e162009-12-01 22:10:20 +00009509 // FIXME: avoid copy.
9510 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9511 if (UnresExpr->hasExplicitTemplateArgs()) {
9512 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9513 TemplateArgs = &TemplateArgsBuffer;
9514 }
9515
John McCall129e2df2009-11-30 22:42:35 +00009516 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9517 E = UnresExpr->decls_end(); I != E; ++I) {
9518
John McCall701c89e2009-12-03 04:06:58 +00009519 NamedDecl *Func = *I;
9520 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9521 if (isa<UsingShadowDecl>(Func))
9522 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9523
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009524
Francois Pichetdbee3412011-01-18 05:04:39 +00009525 // Microsoft supports direct constructor calls.
Francois Pichet62ec1f22011-09-17 17:15:52 +00009526 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichetdbee3412011-01-18 05:04:39 +00009527 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9528 CandidateSet);
9529 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00009530 // If explicit template arguments were provided, we can't call a
9531 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00009532 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00009533 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009534
John McCall9aa472c2010-03-19 07:35:19 +00009535 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009536 ObjectClassification,
9537 Args, NumArgs, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009538 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00009539 } else {
John McCall129e2df2009-11-30 22:42:35 +00009540 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00009541 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009542 ObjectType, ObjectClassification,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009543 Args, NumArgs, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +00009544 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00009545 }
Douglas Gregordec06662009-08-21 18:42:58 +00009546 }
Mike Stump1eb44332009-09-09 15:08:12 +00009547
John McCall129e2df2009-11-30 22:42:35 +00009548 DeclarationName DeclName = UnresExpr->getMemberName();
9549
John McCall5acb0c92011-10-17 18:40:02 +00009550 UnbridgedCasts.restore();
9551
Douglas Gregor88a35142008-12-22 05:46:06 +00009552 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009553 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +00009554 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00009555 case OR_Success:
9556 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009557 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +00009558 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00009559 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009560 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00009561 break;
9562
9563 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00009564 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00009565 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00009566 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009567 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00009568 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00009569 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00009570
9571 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00009572 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00009573 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009574 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00009575 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00009576 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009577
9578 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00009579 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009580 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009581 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009582 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009583 << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009584 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009585 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00009586 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00009587 }
9588
John McCall6bb80172010-03-30 21:47:33 +00009589 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00009590
John McCallaa81e162009-12-01 22:10:20 +00009591 // If overload resolution picked a static member, build a
9592 // non-member call based on that function.
9593 if (Method->isStatic()) {
9594 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9595 Args, NumArgs, RParenLoc);
9596 }
9597
John McCall129e2df2009-11-30 22:42:35 +00009598 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00009599 }
9600
John McCallf89e55a2010-11-18 06:31:45 +00009601 QualType ResultType = Method->getResultType();
9602 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9603 ResultType = ResultType.getNonLValueExprType(Context);
9604
Douglas Gregor88a35142008-12-22 05:46:06 +00009605 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009606 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +00009607 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +00009608 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00009609
Anders Carlssoneed3e692009-10-10 00:06:20 +00009610 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009611 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00009612 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00009613 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009614
Douglas Gregor88a35142008-12-22 05:46:06 +00009615 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00009616 // We only need to do this if there was actually an overload; otherwise
9617 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +00009618 if (!Method->isStatic()) {
9619 ExprResult ObjectArg =
9620 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9621 FoundDecl, Method);
9622 if (ObjectArg.isInvalid())
9623 return ExprError();
9624 MemExpr->setBase(ObjectArg.take());
9625 }
Douglas Gregor88a35142008-12-22 05:46:06 +00009626
9627 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +00009628 const FunctionProtoType *Proto =
9629 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00009630 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00009631 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00009632 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00009633
John McCall9ae2f072010-08-23 23:25:46 +00009634 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00009635 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00009636
Anders Carlsson2174d4c2011-05-06 14:25:31 +00009637 if ((isa<CXXConstructorDecl>(CurContext) ||
9638 isa<CXXDestructorDecl>(CurContext)) &&
9639 TheCall->getMethodDecl()->isPure()) {
9640 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9641
Chandler Carruthae198062011-06-27 08:31:58 +00009642 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +00009643 Diag(MemExpr->getLocStart(),
9644 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9645 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9646 << MD->getParent()->getDeclName();
9647
9648 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +00009649 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +00009650 }
John McCall9ae2f072010-08-23 23:25:46 +00009651 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00009652}
9653
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009654/// BuildCallToObjectOfClassType - Build a call to an object of class
9655/// type (C++ [over.call.object]), which can end up invoking an
9656/// overloaded function call operator (@c operator()) or performing a
9657/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +00009658ExprResult
John Wiegley429bb272011-04-08 18:41:53 +00009659Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +00009660 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009661 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009662 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +00009663 if (checkPlaceholderForOverload(*this, Obj))
9664 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009665 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +00009666
9667 UnbridgedCastsSet UnbridgedCasts;
9668 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9669 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009670
John Wiegley429bb272011-04-08 18:41:53 +00009671 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9672 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00009673
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009674 // C++ [over.call.object]p1:
9675 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00009676 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009677 // candidate functions includes at least the function call
9678 // operators of T. The function call operators of T are obtained by
9679 // ordinary lookup of the name operator() in the context of
9680 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00009681 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00009682 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00009683
John Wiegley429bb272011-04-08 18:41:53 +00009684 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00009685 PDiag(diag::err_incomplete_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00009686 << Object.get()->getSourceRange()))
Douglas Gregor593564b2009-11-15 07:48:03 +00009687 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009688
John McCalla24dc2e2009-11-17 02:14:36 +00009689 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9690 LookupQualifiedName(R, Record->getDecl());
9691 R.suppressDiagnostics();
9692
Douglas Gregor593564b2009-11-15 07:48:03 +00009693 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00009694 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +00009695 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9696 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00009697 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00009698 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009699
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009700 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +00009701 // In addition, for each (non-explicit in C++0x) conversion function
9702 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009703 //
9704 // operator conversion-type-id () cv-qualifier;
9705 //
9706 // where cv-qualifier is the same cv-qualification as, or a
9707 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00009708 // denotes the type "pointer to function of (P1,...,Pn) returning
9709 // R", or the type "reference to pointer to function of
9710 // (P1,...,Pn) returning R", or the type "reference to function
9711 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009712 // is also considered as a candidate function. Similarly,
9713 // surrogate call functions are added to the set of candidate
9714 // functions for each conversion function declared in an
9715 // accessible base class provided the function is not hidden
9716 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00009717 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00009718 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00009719 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00009720 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00009721 NamedDecl *D = *I;
9722 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9723 if (isa<UsingShadowDecl>(D))
9724 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009725
Douglas Gregor4a27d702009-10-21 06:18:39 +00009726 // Skip over templated conversion functions; they aren't
9727 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00009728 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00009729 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009730
John McCall701c89e2009-12-03 04:06:58 +00009731 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +00009732 if (!Conv->isExplicit()) {
9733 // Strip the reference type (if any) and then the pointer type (if
9734 // any) to get down to what might be a function type.
9735 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9736 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9737 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +00009738
Douglas Gregorbf6e3172011-07-23 18:59:35 +00009739 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9740 {
9741 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9742 Object.get(), Args, NumArgs, CandidateSet);
9743 }
9744 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009745 }
Mike Stump1eb44332009-09-09 15:08:12 +00009746
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009747 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9748
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009749 // Perform overload resolution.
9750 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +00009751 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +00009752 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009753 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009754 // Overload resolution succeeded; we'll build the appropriate call
9755 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009756 break;
9757
9758 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00009759 if (CandidateSet.empty())
John Wiegley429bb272011-04-08 18:41:53 +00009760 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9761 << Object.get()->getType() << /*call*/ 1
9762 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +00009763 else
John Wiegley429bb272011-04-08 18:41:53 +00009764 Diag(Object.get()->getSourceRange().getBegin(),
John McCall1eb3e102010-01-07 02:04:15 +00009765 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00009766 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009767 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009768 break;
9769
9770 case OR_Ambiguous:
John Wiegley429bb272011-04-08 18:41:53 +00009771 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009772 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00009773 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009774 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009775 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009776
9777 case OR_Deleted:
John Wiegley429bb272011-04-08 18:41:53 +00009778 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009779 diag::err_ovl_deleted_object_call)
9780 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +00009781 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009782 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +00009783 << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009784 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009785 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009786 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009787
Douglas Gregorff331c12010-07-25 18:17:45 +00009788 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009789 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009790
John McCall5acb0c92011-10-17 18:40:02 +00009791 UnbridgedCasts.restore();
9792
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009793 if (Best->Function == 0) {
9794 // Since there is no function declaration, this is one of the
9795 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00009796 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009797 = cast<CXXConversionDecl>(
9798 Best->Conversions[0].UserDefined.ConversionFunction);
9799
John Wiegley429bb272011-04-08 18:41:53 +00009800 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009801 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00009802
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009803 // We selected one of the surrogate functions that converts the
9804 // object parameter to a function pointer. Perform the conversion
9805 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009806
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00009807 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00009808 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009809 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
9810 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00009811 if (Call.isInvalid())
9812 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009813
Douglas Gregorf2ae5262011-01-20 00:18:04 +00009814 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +00009815 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009816 }
9817
Chandler Carruth25ca4212011-02-25 19:41:05 +00009818 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +00009819 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009820 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00009821
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009822 // We found an overloaded operator(). Build a CXXOperatorCallExpr
9823 // that calls this method, using Object for the implicit object
9824 // parameter and passing along the remaining arguments.
9825 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +00009826 const FunctionProtoType *Proto =
9827 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009828
9829 unsigned NumArgsInProto = Proto->getNumArgs();
9830 unsigned NumArgsToCheck = NumArgs;
9831
9832 // Build the full argument list for the method call (the
9833 // implicit object parameter is placed at the beginning of the
9834 // list).
9835 Expr **MethodArgs;
9836 if (NumArgs < NumArgsInProto) {
9837 NumArgsToCheck = NumArgsInProto;
9838 MethodArgs = new Expr*[NumArgsInProto + 1];
9839 } else {
9840 MethodArgs = new Expr*[NumArgs + 1];
9841 }
John Wiegley429bb272011-04-08 18:41:53 +00009842 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009843 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
9844 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +00009845
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009846 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
9847 HadMultipleCandidates);
John Wiegley429bb272011-04-08 18:41:53 +00009848 if (NewFn.isInvalid())
9849 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009850
9851 // Once we've built TheCall, all of the expressions are properly
9852 // owned.
John McCallf89e55a2010-11-18 06:31:45 +00009853 QualType ResultTy = Method->getResultType();
9854 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9855 ResultTy = ResultTy.getNonLValueExprType(Context);
9856
John McCall9ae2f072010-08-23 23:25:46 +00009857 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009858 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +00009859 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +00009860 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009861 delete [] MethodArgs;
9862
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009863 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +00009864 Method))
9865 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009866
Douglas Gregor518fda12009-01-13 05:10:00 +00009867 // We may have default arguments. If so, we need to allocate more
9868 // slots in the call for them.
9869 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +00009870 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +00009871 else if (NumArgs > NumArgsInProto)
9872 NumArgsToCheck = NumArgsInProto;
9873
Chris Lattner312531a2009-04-12 08:11:20 +00009874 bool IsError = false;
9875
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009876 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +00009877 ExprResult ObjRes =
9878 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
9879 Best->FoundDecl, Method);
9880 if (ObjRes.isInvalid())
9881 IsError = true;
9882 else
9883 Object = move(ObjRes);
9884 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +00009885
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009886 // Check the argument types.
9887 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009888 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +00009889 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009890 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +00009891
Douglas Gregor518fda12009-01-13 05:10:00 +00009892 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +00009893
John McCall60d7b3a2010-08-24 06:29:42 +00009894 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +00009895 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009896 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +00009897 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +00009898 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009899
Anders Carlsson3faa4862010-01-29 18:43:53 +00009900 IsError |= InputInit.isInvalid();
9901 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00009902 } else {
John McCall60d7b3a2010-08-24 06:29:42 +00009903 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +00009904 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
9905 if (DefArg.isInvalid()) {
9906 IsError = true;
9907 break;
9908 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009909
Douglas Gregord47c47d2009-11-09 19:27:57 +00009910 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +00009911 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009912
9913 TheCall->setArg(i + 1, Arg);
9914 }
9915
9916 // If this is a variadic call, handle args passed through "...".
9917 if (Proto->isVariadic()) {
9918 // Promote the arguments (C99 6.5.2.2p7).
9919 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +00009920 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
9921 IsError |= Arg.isInvalid();
9922 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009923 }
9924 }
9925
Chris Lattner312531a2009-04-12 08:11:20 +00009926 if (IsError) return true;
9927
John McCall9ae2f072010-08-23 23:25:46 +00009928 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +00009929 return true;
9930
John McCall182f7092010-08-24 06:09:16 +00009931 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009932}
9933
Douglas Gregor8ba10742008-11-20 16:27:02 +00009934/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +00009935/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +00009936/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +00009937ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00009938Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +00009939 assert(Base->getType()->isRecordType() &&
9940 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +00009941
John McCall5acb0c92011-10-17 18:40:02 +00009942 if (checkPlaceholderForOverload(*this, Base))
9943 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009944
John McCall5769d612010-02-08 23:07:23 +00009945 SourceLocation Loc = Base->getExprLoc();
9946
Douglas Gregor8ba10742008-11-20 16:27:02 +00009947 // C++ [over.ref]p1:
9948 //
9949 // [...] An expression x->m is interpreted as (x.operator->())->m
9950 // for a class object x of type T if T::operator->() exists and if
9951 // the operator is selected as the best match function by the
9952 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +00009953 DeclarationName OpName =
9954 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +00009955 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +00009956 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009957
John McCall5769d612010-02-08 23:07:23 +00009958 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +00009959 PDiag(diag::err_typecheck_incomplete_tag)
9960 << Base->getSourceRange()))
9961 return ExprError();
9962
John McCalla24dc2e2009-11-17 02:14:36 +00009963 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
9964 LookupQualifiedName(R, BaseRecord->getDecl());
9965 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +00009966
9967 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +00009968 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009969 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
9970 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +00009971 }
Douglas Gregor8ba10742008-11-20 16:27:02 +00009972
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009973 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9974
Douglas Gregor8ba10742008-11-20 16:27:02 +00009975 // Perform overload resolution.
9976 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009977 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +00009978 case OR_Success:
9979 // Overload resolution succeeded; we'll build the call below.
9980 break;
9981
9982 case OR_No_Viable_Function:
9983 if (CandidateSet.empty())
9984 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009985 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +00009986 else
9987 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009988 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009989 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009990 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +00009991
9992 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00009993 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9994 << "->" << Base->getType() << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009995 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +00009996 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009997
9998 case OR_Deleted:
9999 Diag(OpLoc, diag::err_ovl_deleted_oper)
10000 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010001 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010002 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010003 << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010004 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010005 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010006 }
10007
Chandler Carruth25ca4212011-02-25 19:41:05 +000010008 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000010009 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010010 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000010011
Douglas Gregor8ba10742008-11-20 16:27:02 +000010012 // Convert the object parameter.
10013 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010014 ExprResult BaseResult =
10015 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10016 Best->FoundDecl, Method);
10017 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010018 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010019 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000010020
Douglas Gregor8ba10742008-11-20 16:27:02 +000010021 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010022 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
10023 HadMultipleCandidates);
John Wiegley429bb272011-04-08 18:41:53 +000010024 if (FnExpr.isInvalid())
10025 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010026
John McCallf89e55a2010-11-18 06:31:45 +000010027 QualType ResultTy = Method->getResultType();
10028 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10029 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000010030 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010031 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000010032 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +000010033
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010034 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010035 Method))
10036 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000010037
10038 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000010039}
10040
Douglas Gregor904eed32008-11-10 20:40:00 +000010041/// FixOverloadedFunctionReference - E is an expression that refers to
10042/// a C++ overloaded function (possibly with some parentheses and
10043/// perhaps a '&' around it). We have resolved the overloaded function
10044/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000010045/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000010046Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000010047 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000010048 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000010049 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10050 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000010051 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010052 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010053
Douglas Gregor699ee522009-11-20 19:42:02 +000010054 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010055 }
10056
Douglas Gregor699ee522009-11-20 19:42:02 +000010057 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000010058 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10059 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010060 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000010061 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000010062 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000010063 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000010064 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010065 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010066
10067 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000010068 ICE->getCastKind(),
10069 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000010070 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010071 }
10072
Douglas Gregor699ee522009-11-20 19:42:02 +000010073 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000010074 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000010075 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000010076 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10077 if (Method->isStatic()) {
10078 // Do nothing: static member functions aren't any different
10079 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000010080 } else {
John McCallf7a1a742009-11-24 19:00:30 +000010081 // Fix the sub expression, which really has to be an
10082 // UnresolvedLookupExpr holding an overloaded member function
10083 // or template.
John McCall6bb80172010-03-30 21:47:33 +000010084 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10085 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000010086 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010087 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000010088
John McCallba135432009-11-21 08:51:07 +000010089 assert(isa<DeclRefExpr>(SubExpr)
10090 && "fixed to something other than a decl ref");
10091 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10092 && "fixed to a member ref with no nested name qualifier");
10093
10094 // We have taken the address of a pointer to member
10095 // function. Perform the computation here so that we get the
10096 // appropriate pointer to member type.
10097 QualType ClassType
10098 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10099 QualType MemPtrType
10100 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10101
John McCallf89e55a2010-11-18 06:31:45 +000010102 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10103 VK_RValue, OK_Ordinary,
10104 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000010105 }
10106 }
John McCall6bb80172010-03-30 21:47:33 +000010107 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10108 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000010109 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010110 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010111
John McCall2de56d12010-08-25 11:45:40 +000010112 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000010113 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000010114 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000010115 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010116 }
John McCallba135432009-11-21 08:51:07 +000010117
10118 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000010119 // FIXME: avoid copy.
10120 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000010121 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000010122 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10123 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000010124 }
10125
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010126 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10127 ULE->getQualifierLoc(),
10128 Fn,
10129 ULE->getNameLoc(),
10130 Fn->getType(),
10131 VK_LValue,
10132 Found.getDecl(),
10133 TemplateArgs);
10134 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10135 return DRE;
John McCallba135432009-11-21 08:51:07 +000010136 }
10137
John McCall129e2df2009-11-30 22:42:35 +000010138 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000010139 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000010140 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10141 if (MemExpr->hasExplicitTemplateArgs()) {
10142 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10143 TemplateArgs = &TemplateArgsBuffer;
10144 }
John McCalld5532b62009-11-23 01:53:49 +000010145
John McCallaa81e162009-12-01 22:10:20 +000010146 Expr *Base;
10147
John McCallf89e55a2010-11-18 06:31:45 +000010148 // If we're filling in a static method where we used to have an
10149 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000010150 if (MemExpr->isImplicitAccess()) {
10151 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010152 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10153 MemExpr->getQualifierLoc(),
10154 Fn,
10155 MemExpr->getMemberLoc(),
10156 Fn->getType(),
10157 VK_LValue,
10158 Found.getDecl(),
10159 TemplateArgs);
10160 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10161 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000010162 } else {
10163 SourceLocation Loc = MemExpr->getMemberLoc();
10164 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000010165 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregor828a1972010-01-07 23:12:05 +000010166 Base = new (Context) CXXThisExpr(Loc,
10167 MemExpr->getBaseType(),
10168 /*isImplicit=*/true);
10169 }
John McCallaa81e162009-12-01 22:10:20 +000010170 } else
John McCall3fa5cae2010-10-26 07:05:15 +000010171 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000010172
John McCallf5307512011-04-27 00:36:17 +000010173 ExprValueKind valueKind;
10174 QualType type;
10175 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10176 valueKind = VK_LValue;
10177 type = Fn->getType();
10178 } else {
10179 valueKind = VK_RValue;
10180 type = Context.BoundMemberTy;
10181 }
10182
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010183 MemberExpr *ME = MemberExpr::Create(Context, Base,
10184 MemExpr->isArrow(),
10185 MemExpr->getQualifierLoc(),
10186 Fn,
10187 Found,
10188 MemExpr->getMemberNameInfo(),
10189 TemplateArgs,
10190 type, valueKind, OK_Ordinary);
10191 ME->setHadMultipleCandidates(true);
10192 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000010193 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010194
John McCall3fa5cae2010-10-26 07:05:15 +000010195 llvm_unreachable("Invalid reference to overloaded function");
10196 return E;
Douglas Gregor904eed32008-11-10 20:40:00 +000010197}
10198
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010199ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000010200 DeclAccessPair Found,
10201 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000010202 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000010203}
10204
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000010205} // end namespace clang