blob: cf8df57eb3ae983bf90063b4aaf884cf8f2d9e66 [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
Richard Trieu6efd4c52011-11-23 22:32:32 +00002166enum {
2167 ft_default,
2168 ft_different_class,
2169 ft_parameter_arity,
2170 ft_parameter_mismatch,
2171 ft_return_type,
2172 ft_qualifer_mismatch
2173};
2174
2175/// HandleFunctionTypeMismatch - Gives diagnostic information for differeing
2176/// function types. Catches different number of parameter, mismatch in
2177/// parameter types, and different return types.
2178void Sema::HandleFunctionTypeMismatch(PartialDiagnostic &PDiag,
2179 QualType FromType, QualType ToType) {
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002180 // If either type is not valid, include no extra info.
2181 if (FromType.isNull() || ToType.isNull()) {
2182 PDiag << ft_default;
2183 return;
2184 }
2185
Richard Trieu6efd4c52011-11-23 22:32:32 +00002186 // Get the function type from the pointers.
2187 if (FromType->isMemberPointerType() && ToType->isMemberPointerType()) {
2188 const MemberPointerType *FromMember = FromType->getAs<MemberPointerType>(),
2189 *ToMember = ToType->getAs<MemberPointerType>();
2190 if (FromMember->getClass() != ToMember->getClass()) {
2191 PDiag << ft_different_class << QualType(ToMember->getClass(), 0)
2192 << QualType(FromMember->getClass(), 0);
2193 return;
2194 }
2195 FromType = FromMember->getPointeeType();
2196 ToType = ToMember->getPointeeType();
Richard Trieu6efd4c52011-11-23 22:32:32 +00002197 }
2198
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002199 if (FromType->isPointerType())
2200 FromType = FromType->getPointeeType();
2201 if (ToType->isPointerType())
2202 ToType = ToType->getPointeeType();
2203
2204 // Remove references.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002205 FromType = FromType.getNonReferenceType();
2206 ToType = ToType.getNonReferenceType();
2207
Richard Trieu6efd4c52011-11-23 22:32:32 +00002208 // Don't print extra info for non-specialized template functions.
2209 if (FromType->isInstantiationDependentType() &&
2210 !FromType->getAs<TemplateSpecializationType>()) {
2211 PDiag << ft_default;
2212 return;
2213 }
2214
Richard Trieua6dc7ef2011-12-13 23:19:45 +00002215 // No extra info for same types.
2216 if (Context.hasSameType(FromType, ToType)) {
2217 PDiag << ft_default;
2218 return;
2219 }
2220
Richard Trieu6efd4c52011-11-23 22:32:32 +00002221 const FunctionProtoType *FromFunction = FromType->getAs<FunctionProtoType>(),
2222 *ToFunction = ToType->getAs<FunctionProtoType>();
2223
2224 // Both types need to be function types.
2225 if (!FromFunction || !ToFunction) {
2226 PDiag << ft_default;
2227 return;
2228 }
2229
2230 if (FromFunction->getNumArgs() != ToFunction->getNumArgs()) {
2231 PDiag << ft_parameter_arity << ToFunction->getNumArgs()
2232 << FromFunction->getNumArgs();
2233 return;
2234 }
2235
2236 // Handle different parameter types.
2237 unsigned ArgPos;
2238 if (!FunctionArgTypesAreEqual(FromFunction, ToFunction, &ArgPos)) {
2239 PDiag << ft_parameter_mismatch << ArgPos + 1
2240 << ToFunction->getArgType(ArgPos)
2241 << FromFunction->getArgType(ArgPos);
2242 return;
2243 }
2244
2245 // Handle different return type.
2246 if (!Context.hasSameType(FromFunction->getResultType(),
2247 ToFunction->getResultType())) {
2248 PDiag << ft_return_type << ToFunction->getResultType()
2249 << FromFunction->getResultType();
2250 return;
2251 }
2252
2253 unsigned FromQuals = FromFunction->getTypeQuals(),
2254 ToQuals = ToFunction->getTypeQuals();
2255 if (FromQuals != ToQuals) {
2256 PDiag << ft_qualifer_mismatch << ToQuals << FromQuals;
2257 return;
2258 }
2259
2260 // Unable to find a difference, so add no extra info.
2261 PDiag << ft_default;
2262}
2263
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002264/// FunctionArgTypesAreEqual - This routine checks two function proto types
Douglas Gregordec1cc42011-12-15 17:15:07 +00002265/// for equality of their argument types. Caller has already checked that
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002266/// they have same number of arguments. This routine assumes that Objective-C
2267/// pointer types which only differ in their protocol qualifiers are equal.
Richard Trieu6efd4c52011-11-23 22:32:32 +00002268/// If the parameters are different, ArgPos will have the the parameter index
2269/// of the first different parameter.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002270bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
Richard Trieu6efd4c52011-11-23 22:32:32 +00002271 const FunctionProtoType *NewType,
2272 unsigned *ArgPos) {
2273 if (!getLangOptions().ObjC1) {
2274 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2275 N = NewType->arg_type_begin(),
2276 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2277 if (!Context.hasSameType(*O, *N)) {
2278 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
2279 return false;
2280 }
2281 }
2282 return true;
2283 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002284
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002285 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
2286 N = NewType->arg_type_begin(),
2287 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
2288 QualType ToType = (*O);
2289 QualType FromType = (*N);
Richard Trieu6efd4c52011-11-23 22:32:32 +00002290 if (!Context.hasSameType(ToType, FromType)) {
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002291 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
2292 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth0ee93de2010-05-06 00:15:06 +00002293 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
2294 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
2295 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
2296 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002297 continue;
2298 }
John McCallc12c5bb2010-05-15 11:32:37 +00002299 else if (const ObjCObjectPointerType *PTTo =
2300 ToType->getAs<ObjCObjectPointerType>()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002301 if (const ObjCObjectPointerType *PTFr =
John McCallc12c5bb2010-05-15 11:32:37 +00002302 FromType->getAs<ObjCObjectPointerType>())
Douglas Gregordec1cc42011-12-15 17:15:07 +00002303 if (Context.hasSameUnqualifiedType(
2304 PTTo->getObjectType()->getBaseType(),
2305 PTFr->getObjectType()->getBaseType()))
John McCallc12c5bb2010-05-15 11:32:37 +00002306 continue;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002307 }
Richard Trieu6efd4c52011-11-23 22:32:32 +00002308 if (ArgPos) *ArgPos = O - OldType->arg_type_begin();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002309 return false;
Fariborz Jahaniand8d34412010-05-03 21:06:18 +00002310 }
2311 }
2312 return true;
2313}
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002314
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002315/// CheckPointerConversion - Check the pointer conversion from the
2316/// expression From to the type ToType. This routine checks for
Sebastian Redl9cc11e72009-07-25 15:41:38 +00002317/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002318/// conversions for which IsPointerConversion has already returned
2319/// true. It returns true and produces a diagnostic if there was an
2320/// error, or returns false otherwise.
Anders Carlsson61faec12009-09-12 04:46:44 +00002321bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002322 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002323 CXXCastPath& BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002324 bool IgnoreBaseAccess) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002325 QualType FromType = From->getType();
Argyrios Kyrtzidisb3358722010-09-28 14:54:11 +00002326 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002327
John McCalldaa8e4e2010-11-15 09:13:47 +00002328 Kind = CK_BitCast;
2329
Chandler Carruth88f0aed2011-04-09 07:32:05 +00002330 if (!IsCStyleOrFunctionalCast &&
2331 Context.hasSameUnqualifiedType(From->getType(), Context.BoolTy) &&
2332 From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull))
2333 DiagRuntimeBehavior(From->getExprLoc(), From,
Chandler Carruthb6006692011-04-09 07:48:17 +00002334 PDiag(diag::warn_impcast_bool_to_null_pointer)
2335 << ToType << From->getSourceRange());
Douglas Gregord7a95972010-06-08 17:35:15 +00002336
John McCall1d9b3b22011-09-09 05:25:32 +00002337 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
2338 if (const PointerType *FromPtrType = FromType->getAs<PointerType>()) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002339 QualType FromPointeeType = FromPtrType->getPointeeType(),
2340 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregordda78892008-12-18 23:43:31 +00002341
Douglas Gregor5fccd362010-03-03 23:55:11 +00002342 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
2343 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002344 // We must have a derived-to-base conversion. Check an
2345 // ambiguous or inaccessible conversion.
Anders Carlsson61faec12009-09-12 04:46:44 +00002346 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
2347 From->getExprLoc(),
Anders Carlsson5cf86ba2010-04-24 19:06:50 +00002348 From->getSourceRange(), &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002349 IgnoreBaseAccess))
Anders Carlsson61faec12009-09-12 04:46:44 +00002350 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002351
Anders Carlsson61faec12009-09-12 04:46:44 +00002352 // The conversion was successful.
John McCall2de56d12010-08-25 11:45:40 +00002353 Kind = CK_DerivedToBase;
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002354 }
2355 }
John McCall1d9b3b22011-09-09 05:25:32 +00002356 } else if (const ObjCObjectPointerType *ToPtrType =
2357 ToType->getAs<ObjCObjectPointerType>()) {
2358 if (const ObjCObjectPointerType *FromPtrType =
2359 FromType->getAs<ObjCObjectPointerType>()) {
Steve Naroff14108da2009-07-10 23:34:53 +00002360 // Objective-C++ conversions are always okay.
2361 // FIXME: We should have a different class of conversions for the
2362 // Objective-C++ implicit conversions.
Steve Naroffde2e22d2009-07-15 18:40:39 +00002363 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff14108da2009-07-10 23:34:53 +00002364 return false;
John McCall1d9b3b22011-09-09 05:25:32 +00002365 } else if (FromType->isBlockPointerType()) {
2366 Kind = CK_BlockPointerToObjCPointerCast;
2367 } else {
2368 Kind = CK_CPointerToObjCPointerCast;
John McCalldaa8e4e2010-11-15 09:13:47 +00002369 }
John McCall1d9b3b22011-09-09 05:25:32 +00002370 } else if (ToType->isBlockPointerType()) {
2371 if (!FromType->isBlockPointerType())
2372 Kind = CK_AnyPointerToBlockPointerCast;
Steve Naroff14108da2009-07-10 23:34:53 +00002373 }
John McCalldaa8e4e2010-11-15 09:13:47 +00002374
2375 // We shouldn't fall into this case unless it's valid for other
2376 // reasons.
2377 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
2378 Kind = CK_NullToPointer;
2379
Douglas Gregor94b1dd22008-10-24 04:54:22 +00002380 return false;
2381}
2382
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002383/// IsMemberPointerConversion - Determines whether the conversion of the
2384/// expression From, which has the (possibly adjusted) type FromType, can be
2385/// converted to the type ToType via a member pointer conversion (C++ 4.11).
2386/// If so, returns true and places the converted type (that might differ from
2387/// ToType in its cv-qualifiers at some level) into ConvertedType.
2388bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002389 QualType ToType,
Douglas Gregorce940492009-09-25 04:25:58 +00002390 bool InOverloadResolution,
2391 QualType &ConvertedType) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002392 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002393 if (!ToTypePtr)
2394 return false;
2395
2396 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregorce940492009-09-25 04:25:58 +00002397 if (From->isNullPointerConstant(Context,
2398 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
2399 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002400 ConvertedType = ToType;
2401 return true;
2402 }
2403
2404 // Otherwise, both types have to be member pointers.
Ted Kremenek6217b802009-07-29 21:53:49 +00002405 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002406 if (!FromTypePtr)
2407 return false;
2408
2409 // A pointer to member of B can be converted to a pointer to member of D,
2410 // where D is derived from B (C++ 4.11p2).
2411 QualType FromClass(FromTypePtr->getClass(), 0);
2412 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002413
Douglas Gregorcfddf7b2010-12-21 21:40:41 +00002414 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
2415 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
2416 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002417 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
2418 ToClass.getTypePtr());
2419 return true;
2420 }
2421
2422 return false;
2423}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002424
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002425/// CheckMemberPointerConversion - Check the member pointer conversion from the
2426/// expression From to the type ToType. This routine checks for ambiguous or
John McCall6b2accb2010-02-10 09:31:12 +00002427/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002428/// for which IsMemberPointerConversion has already returned true. It returns
2429/// true and produces a diagnostic if there was an error, or returns false
2430/// otherwise.
Mike Stump1eb44332009-09-09 15:08:12 +00002431bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCall2de56d12010-08-25 11:45:40 +00002432 CastKind &Kind,
John McCallf871d0c2010-08-07 06:22:56 +00002433 CXXCastPath &BasePath,
Sebastian Redla82e4ae2009-11-14 21:15:49 +00002434 bool IgnoreBaseAccess) {
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002435 QualType FromType = From->getType();
Ted Kremenek6217b802009-07-29 21:53:49 +00002436 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002437 if (!FromPtrType) {
2438 // This must be a null pointer to member pointer conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002439 assert(From->isNullPointerConstant(Context,
Douglas Gregorce940492009-09-25 04:25:58 +00002440 Expr::NPC_ValueDependentIsNull) &&
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002441 "Expr must be null pointer constant!");
John McCall2de56d12010-08-25 11:45:40 +00002442 Kind = CK_NullToMemberPointer;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002443 return false;
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002444 }
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002445
Ted Kremenek6217b802009-07-29 21:53:49 +00002446 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redl21593ac2009-01-28 18:33:18 +00002447 assert(ToPtrType && "No member pointer cast has a target type "
2448 "that is not a member pointer.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002449
Sebastian Redl21593ac2009-01-28 18:33:18 +00002450 QualType FromClass = QualType(FromPtrType->getClass(), 0);
2451 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002452
Sebastian Redl21593ac2009-01-28 18:33:18 +00002453 // FIXME: What about dependent types?
2454 assert(FromClass->isRecordType() && "Pointer into non-class.");
2455 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002456
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002457 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregora8f32e02009-10-06 17:59:45 +00002458 /*DetectVirtual=*/true);
Sebastian Redl21593ac2009-01-28 18:33:18 +00002459 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
2460 assert(DerivationOkay &&
2461 "Should not have been called if derivation isn't OK.");
2462 (void)DerivationOkay;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002463
Sebastian Redl21593ac2009-01-28 18:33:18 +00002464 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
2465 getUnqualifiedType())) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002466 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2467 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
2468 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
2469 return true;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002470 }
Sebastian Redl21593ac2009-01-28 18:33:18 +00002471
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002472 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redl21593ac2009-01-28 18:33:18 +00002473 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
2474 << FromClass << ToClass << QualType(VBase, 0)
2475 << From->getSourceRange();
2476 return true;
2477 }
2478
John McCall6b2accb2010-02-10 09:31:12 +00002479 if (!IgnoreBaseAccess)
John McCall58e6f342010-03-16 05:22:47 +00002480 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
2481 Paths.front(),
2482 diag::err_downcast_from_inaccessible_base);
John McCall6b2accb2010-02-10 09:31:12 +00002483
Anders Carlsson27a5b9b2009-08-22 23:33:40 +00002484 // Must be a base to derived member conversion.
Anders Carlssonf9d68e12010-04-24 19:36:51 +00002485 BuildBasePathArray(Paths, BasePath);
John McCall2de56d12010-08-25 11:45:40 +00002486 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl4433aaf2009-01-25 19:43:20 +00002487 return false;
2488}
2489
Douglas Gregor98cd5992008-10-21 23:43:52 +00002490/// IsQualificationConversion - Determines whether the conversion from
2491/// an rvalue of type FromType to ToType is a qualification conversion
2492/// (C++ 4.4).
John McCallf85e1932011-06-15 23:02:42 +00002493///
2494/// \param ObjCLifetimeConversion Output parameter that will be set to indicate
2495/// when the qualification conversion involves a change in the Objective-C
2496/// object lifetime.
Mike Stump1eb44332009-09-09 15:08:12 +00002497bool
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002498Sema::IsQualificationConversion(QualType FromType, QualType ToType,
John McCallf85e1932011-06-15 23:02:42 +00002499 bool CStyle, bool &ObjCLifetimeConversion) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002500 FromType = Context.getCanonicalType(FromType);
2501 ToType = Context.getCanonicalType(ToType);
John McCallf85e1932011-06-15 23:02:42 +00002502 ObjCLifetimeConversion = false;
2503
Douglas Gregor98cd5992008-10-21 23:43:52 +00002504 // If FromType and ToType are the same type, this is not a
2505 // qualification conversion.
Sebastian Redl22c92402010-02-03 19:36:07 +00002506 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor98cd5992008-10-21 23:43:52 +00002507 return false;
Sebastian Redl21593ac2009-01-28 18:33:18 +00002508
Douglas Gregor98cd5992008-10-21 23:43:52 +00002509 // (C++ 4.4p4):
2510 // A conversion can add cv-qualifiers at levels other than the first
2511 // in multi-level pointers, subject to the following rules: [...]
2512 bool PreviousToQualsIncludeConst = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002513 bool UnwrappedAnyPointer = false;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002514 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor98cd5992008-10-21 23:43:52 +00002515 // Within each iteration of the loop, we check the qualifiers to
2516 // determine if this still looks like a qualification
2517 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00002518 // pointers or pointers-to-members and do it all again
Douglas Gregor98cd5992008-10-21 23:43:52 +00002519 // until there are no more pointers or pointers-to-members left to
2520 // unwrap.
Douglas Gregor57373262008-10-22 14:17:15 +00002521 UnwrappedAnyPointer = true;
Douglas Gregor98cd5992008-10-21 23:43:52 +00002522
Douglas Gregor621c92a2011-04-25 18:40:17 +00002523 Qualifiers FromQuals = FromType.getQualifiers();
2524 Qualifiers ToQuals = ToType.getQualifiers();
2525
John McCallf85e1932011-06-15 23:02:42 +00002526 // Objective-C ARC:
2527 // Check Objective-C lifetime conversions.
2528 if (FromQuals.getObjCLifetime() != ToQuals.getObjCLifetime() &&
2529 UnwrappedAnyPointer) {
2530 if (ToQuals.compatiblyIncludesObjCLifetime(FromQuals)) {
2531 ObjCLifetimeConversion = true;
2532 FromQuals.removeObjCLifetime();
2533 ToQuals.removeObjCLifetime();
2534 } else {
2535 // Qualification conversions cannot cast between different
2536 // Objective-C lifetime qualifiers.
2537 return false;
2538 }
2539 }
2540
Douglas Gregor377e1bd2011-05-08 06:09:53 +00002541 // Allow addition/removal of GC attributes but not changing GC attributes.
2542 if (FromQuals.getObjCGCAttr() != ToQuals.getObjCGCAttr() &&
2543 (!FromQuals.hasObjCGCAttr() || !ToQuals.hasObjCGCAttr())) {
2544 FromQuals.removeObjCGCAttr();
2545 ToQuals.removeObjCGCAttr();
2546 }
2547
Douglas Gregor98cd5992008-10-21 23:43:52 +00002548 // -- for every j > 0, if const is in cv 1,j then const is in cv
2549 // 2,j, and similarly for volatile.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002550 if (!CStyle && !ToQuals.compatiblyIncludes(FromQuals))
Douglas Gregor98cd5992008-10-21 23:43:52 +00002551 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002552
Douglas Gregor98cd5992008-10-21 23:43:52 +00002553 // -- if the cv 1,j and cv 2,j are different, then const is in
2554 // every cv for 0 < k < j.
Douglas Gregor621c92a2011-04-25 18:40:17 +00002555 if (!CStyle && FromQuals.getCVRQualifiers() != ToQuals.getCVRQualifiers()
Douglas Gregor57373262008-10-22 14:17:15 +00002556 && !PreviousToQualsIncludeConst)
Douglas Gregor98cd5992008-10-21 23:43:52 +00002557 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002558
Douglas Gregor98cd5992008-10-21 23:43:52 +00002559 // Keep track of whether all prior cv-qualifiers in the "to" type
2560 // include const.
Mike Stump1eb44332009-09-09 15:08:12 +00002561 PreviousToQualsIncludeConst
Douglas Gregor621c92a2011-04-25 18:40:17 +00002562 = PreviousToQualsIncludeConst && ToQuals.hasConst();
Douglas Gregor57373262008-10-22 14:17:15 +00002563 }
Douglas Gregor98cd5992008-10-21 23:43:52 +00002564
2565 // We are left with FromType and ToType being the pointee types
2566 // after unwrapping the original FromType and ToType the same number
2567 // of types. If we unwrapped any pointers, and if FromType and
2568 // ToType have the same unqualified type (since we checked
2569 // qualifiers above), then this is a qualification conversion.
Douglas Gregora4923eb2009-11-16 21:35:15 +00002570 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor98cd5992008-10-21 23:43:52 +00002571}
2572
Douglas Gregor734d9862009-01-30 23:27:23 +00002573/// Determines whether there is a user-defined conversion sequence
2574/// (C++ [over.ics.user]) that converts expression From to the type
2575/// ToType. If such a conversion exists, User will contain the
2576/// user-defined conversion sequence that performs such a conversion
2577/// and this routine will return true. Otherwise, this routine returns
2578/// false and User is unspecified.
2579///
Douglas Gregor734d9862009-01-30 23:27:23 +00002580/// \param AllowExplicit true if the conversion should consider C++0x
2581/// "explicit" conversion functions as well as non-explicit conversion
2582/// functions (C++0x [class.conv.fct]p2).
John McCall120d63c2010-08-24 20:38:10 +00002583static OverloadingResult
2584IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2585 UserDefinedConversionSequence& User,
2586 OverloadCandidateSet& CandidateSet,
2587 bool AllowExplicit) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002588 // Whether we will only visit constructors.
2589 bool ConstructorsOnly = false;
2590
2591 // If the type we are conversion to is a class type, enumerate its
2592 // constructors.
Ted Kremenek6217b802009-07-29 21:53:49 +00002593 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002594 // C++ [over.match.ctor]p1:
2595 // When objects of class type are direct-initialized (8.5), or
2596 // copy-initialized from an expression of the same or a
2597 // derived class type (8.5), overload resolution selects the
2598 // constructor. [...] For copy-initialization, the candidate
2599 // functions are all the converting constructors (12.3.1) of
2600 // that class. The argument list is the expression-list within
2601 // the parentheses of the initializer.
John McCall120d63c2010-08-24 20:38:10 +00002602 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002603 (From->getType()->getAs<RecordType>() &&
John McCall120d63c2010-08-24 20:38:10 +00002604 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002605 ConstructorsOnly = true;
2606
Argyrios Kyrtzidise36bca62011-04-22 17:45:37 +00002607 S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag());
2608 // RequireCompleteType may have returned true due to some invalid decl
2609 // during template instantiation, but ToType may be complete enough now
2610 // to try to recover.
2611 if (ToType->isIncompleteType()) {
Douglas Gregor393896f2009-11-05 13:06:35 +00002612 // We're not going to find any constructors.
2613 } else if (CXXRecordDecl *ToRecordDecl
2614 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002615 DeclContext::lookup_iterator Con, ConEnd;
John McCall120d63c2010-08-24 20:38:10 +00002616 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002617 Con != ConEnd; ++Con) {
John McCall9aa472c2010-03-19 07:35:19 +00002618 NamedDecl *D = *Con;
2619 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2620
Douglas Gregordec06662009-08-21 18:42:58 +00002621 // Find the constructor (which may be a template).
2622 CXXConstructorDecl *Constructor = 0;
2623 FunctionTemplateDecl *ConstructorTmpl
John McCall9aa472c2010-03-19 07:35:19 +00002624 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregordec06662009-08-21 18:42:58 +00002625 if (ConstructorTmpl)
Mike Stump1eb44332009-09-09 15:08:12 +00002626 Constructor
Douglas Gregordec06662009-08-21 18:42:58 +00002627 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2628 else
John McCall9aa472c2010-03-19 07:35:19 +00002629 Constructor = cast<CXXConstructorDecl>(D);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002630
Fariborz Jahanian52ab92b2009-08-06 17:22:51 +00002631 if (!Constructor->isInvalidDecl() &&
Anders Carlssonfaccd722009-08-28 16:57:08 +00002632 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregordec06662009-08-21 18:42:58 +00002633 if (ConstructorTmpl)
John McCall120d63c2010-08-24 20:38:10 +00002634 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2635 /*ExplicitArgs*/ 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002636 &From, 1, CandidateSet,
John McCall120d63c2010-08-24 20:38:10 +00002637 /*SuppressUserConversions=*/
2638 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002639 else
Fariborz Jahanian249cead2009-10-01 20:39:51 +00002640 // Allow one user-defined conversion when user specifies a
2641 // From->ToType conversion via an static cast (c-style, etc).
John McCall120d63c2010-08-24 20:38:10 +00002642 S.AddOverloadCandidate(Constructor, FoundDecl,
2643 &From, 1, CandidateSet,
2644 /*SuppressUserConversions=*/
2645 !ConstructorsOnly);
Douglas Gregordec06662009-08-21 18:42:58 +00002646 }
Douglas Gregorc1efaec2009-02-28 01:32:25 +00002647 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002648 }
2649 }
2650
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002651 // Enumerate conversion functions, if we're allowed to.
2652 if (ConstructorsOnly) {
John McCall120d63c2010-08-24 20:38:10 +00002653 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2654 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor5842ba92009-08-24 15:23:48 +00002655 // No conversion functions from incomplete types.
Mike Stump1eb44332009-09-09 15:08:12 +00002656 } else if (const RecordType *FromRecordType
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002657 = From->getType()->getAs<RecordType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002658 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002659 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2660 // Add all of the conversion functions as candidates.
John McCalleec51cf2010-01-20 00:46:10 +00002661 const UnresolvedSetImpl *Conversions
Fariborz Jahanianb191e2d2009-09-14 20:41:01 +00002662 = FromRecordDecl->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00002663 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00002664 E = Conversions->end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00002665 DeclAccessPair FoundDecl = I.getPair();
2666 NamedDecl *D = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00002667 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2668 if (isa<UsingShadowDecl>(D))
2669 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2670
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002671 CXXConversionDecl *Conv;
2672 FunctionTemplateDecl *ConvTemplate;
John McCall32daa422010-03-31 01:36:47 +00002673 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2674 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002675 else
John McCall32daa422010-03-31 01:36:47 +00002676 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002677
2678 if (AllowExplicit || !Conv->isExplicit()) {
2679 if (ConvTemplate)
John McCall120d63c2010-08-24 20:38:10 +00002680 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2681 ActingContext, From, ToType,
2682 CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002683 else
John McCall120d63c2010-08-24 20:38:10 +00002684 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2685 From, ToType, CandidateSet);
Fariborz Jahanian8664ad52009-09-11 18:46:22 +00002686 }
2687 }
2688 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002689 }
Douglas Gregor60d62c22008-10-31 16:23:19 +00002690
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002691 bool HadMultipleCandidates = (CandidateSet.size() > 1);
2692
Douglas Gregor60d62c22008-10-31 16:23:19 +00002693 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00002694 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall120d63c2010-08-24 20:38:10 +00002695 case OR_Success:
2696 // Record the standard conversion we used and the conversion function.
2697 if (CXXConstructorDecl *Constructor
2698 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
Chandler Carruth25ca4212011-02-25 19:41:05 +00002699 S.MarkDeclarationReferenced(From->getLocStart(), Constructor);
2700
John McCall120d63c2010-08-24 20:38:10 +00002701 // C++ [over.ics.user]p1:
2702 // If the user-defined conversion is specified by a
2703 // constructor (12.3.1), the initial standard conversion
2704 // sequence converts the source type to the type required by
2705 // the argument of the constructor.
2706 //
2707 QualType ThisType = Constructor->getThisType(S.Context);
2708 if (Best->Conversions[0].isEllipsis())
2709 User.EllipsisConversion = true;
2710 else {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00002711 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00002712 User.EllipsisConversion = false;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002713 }
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002714 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00002715 User.ConversionFunction = Constructor;
John McCallca82a822011-09-21 08:36:56 +00002716 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00002717 User.After.setAsIdentityConversion();
2718 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2719 User.After.setAllToTypes(ToType);
2720 return OR_Success;
2721 } else if (CXXConversionDecl *Conversion
2722 = dyn_cast<CXXConversionDecl>(Best->Function)) {
Chandler Carruth25ca4212011-02-25 19:41:05 +00002723 S.MarkDeclarationReferenced(From->getLocStart(), Conversion);
2724
John McCall120d63c2010-08-24 20:38:10 +00002725 // C++ [over.ics.user]p1:
2726 //
2727 // [...] If the user-defined conversion is specified by a
2728 // conversion function (12.3.2), the initial standard
2729 // conversion sequence converts the source type to the
2730 // implicit object parameter of the conversion function.
2731 User.Before = Best->Conversions[0].Standard;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00002732 User.HadMultipleCandidates = HadMultipleCandidates;
John McCall120d63c2010-08-24 20:38:10 +00002733 User.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00002734 User.FoundConversionFunction = Best->FoundDecl;
John McCall120d63c2010-08-24 20:38:10 +00002735 User.EllipsisConversion = false;
Mike Stump1eb44332009-09-09 15:08:12 +00002736
John McCall120d63c2010-08-24 20:38:10 +00002737 // C++ [over.ics.user]p2:
2738 // The second standard conversion sequence converts the
2739 // result of the user-defined conversion to the target type
2740 // for the sequence. Since an implicit conversion sequence
2741 // is an initialization, the special rules for
2742 // initialization by user-defined conversion apply when
2743 // selecting the best user-defined conversion for a
2744 // user-defined conversion sequence (see 13.3.3 and
2745 // 13.3.3.1).
2746 User.After = Best->FinalConversion;
2747 return OR_Success;
2748 } else {
2749 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002750 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002751 }
2752
John McCall120d63c2010-08-24 20:38:10 +00002753 case OR_No_Viable_Function:
2754 return OR_No_Viable_Function;
2755 case OR_Deleted:
2756 // No conversion here! We're done.
2757 return OR_Deleted;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002758
John McCall120d63c2010-08-24 20:38:10 +00002759 case OR_Ambiguous:
2760 return OR_Ambiguous;
2761 }
2762
Fariborz Jahanian34acd3e2009-09-15 19:12:21 +00002763 return OR_No_Viable_Function;
Douglas Gregor60d62c22008-10-31 16:23:19 +00002764}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002765
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002766bool
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002767Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002768 ImplicitConversionSequence ICS;
John McCall5769d612010-02-08 23:07:23 +00002769 OverloadCandidateSet CandidateSet(From->getExprLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002770 OverloadingResult OvResult =
John McCall120d63c2010-08-24 20:38:10 +00002771 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002772 CandidateSet, false);
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00002773 if (OvResult == OR_Ambiguous)
2774 Diag(From->getSourceRange().getBegin(),
2775 diag::err_typecheck_ambiguous_condition)
2776 << From->getType() << ToType << From->getSourceRange();
2777 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2778 Diag(From->getSourceRange().getBegin(),
2779 diag::err_typecheck_nonviable_condition)
2780 << From->getType() << ToType << From->getSourceRange();
2781 else
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002782 return false;
John McCall120d63c2010-08-24 20:38:10 +00002783 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002784 return true;
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00002785}
Douglas Gregor60d62c22008-10-31 16:23:19 +00002786
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002787/// CompareImplicitConversionSequences - Compare two implicit
2788/// conversion sequences to determine whether one is better than the
2789/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall120d63c2010-08-24 20:38:10 +00002790static ImplicitConversionSequence::CompareKind
2791CompareImplicitConversionSequences(Sema &S,
2792 const ImplicitConversionSequence& ICS1,
2793 const ImplicitConversionSequence& ICS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002794{
2795 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2796 // conversion sequences (as defined in 13.3.3.1)
2797 // -- a standard conversion sequence (13.3.3.1.1) is a better
2798 // conversion sequence than a user-defined conversion sequence or
2799 // an ellipsis conversion sequence, and
2800 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2801 // conversion sequence than an ellipsis conversion sequence
2802 // (13.3.3.1.3).
Mike Stump1eb44332009-09-09 15:08:12 +00002803 //
John McCall1d318332010-01-12 00:44:57 +00002804 // C++0x [over.best.ics]p10:
2805 // For the purpose of ranking implicit conversion sequences as
2806 // described in 13.3.3.2, the ambiguous conversion sequence is
2807 // treated as a user-defined sequence that is indistinguishable
2808 // from any other user-defined conversion sequence.
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00002809 if (ICS1.getKindRank() < ICS2.getKindRank())
2810 return ImplicitConversionSequence::Better;
2811 else if (ICS2.getKindRank() < ICS1.getKindRank())
2812 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002813
Benjamin Kramerb6eee072010-04-18 12:05:54 +00002814 // The following checks require both conversion sequences to be of
2815 // the same kind.
2816 if (ICS1.getKind() != ICS2.getKind())
2817 return ImplicitConversionSequence::Indistinguishable;
2818
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002819 ImplicitConversionSequence::CompareKind Result =
2820 ImplicitConversionSequence::Indistinguishable;
2821
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002822 // Two implicit conversion sequences of the same form are
2823 // indistinguishable conversion sequences unless one of the
2824 // following rules apply: (C++ 13.3.3.2p3):
John McCall1d318332010-01-12 00:44:57 +00002825 if (ICS1.isStandard())
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002826 Result = CompareStandardConversionSequences(S,
2827 ICS1.Standard, ICS2.Standard);
John McCall1d318332010-01-12 00:44:57 +00002828 else if (ICS1.isUserDefined()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002829 // User-defined conversion sequence U1 is a better conversion
2830 // sequence than another user-defined conversion sequence U2 if
2831 // they contain the same user-defined conversion function or
2832 // constructor and if the second standard conversion sequence of
2833 // U1 is better than the second standard conversion sequence of
2834 // U2 (C++ 13.3.3.2p3).
Mike Stump1eb44332009-09-09 15:08:12 +00002835 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002836 ICS2.UserDefined.ConversionFunction)
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002837 Result = CompareStandardConversionSequences(S,
2838 ICS1.UserDefined.After,
2839 ICS2.UserDefined.After);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002840 }
2841
Sebastian Redlcc7a6482011-11-01 15:53:09 +00002842 // List-initialization sequence L1 is a better conversion sequence than
2843 // list-initialization sequence L2 if L1 converts to std::initializer_list<X>
2844 // for some X and L2 does not.
2845 if (Result == ImplicitConversionSequence::Indistinguishable &&
2846 ICS1.isListInitializationSequence() &&
2847 ICS2.isListInitializationSequence()) {
2848 // FIXME: Find out if ICS1 converts to initializer_list and ICS2 doesn't.
2849 }
2850
2851 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002852}
2853
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002854static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2855 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2856 Qualifiers Quals;
2857 T1 = Context.getUnqualifiedArrayType(T1, Quals);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002858 T2 = Context.getUnqualifiedArrayType(T2, Quals);
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002859 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002860
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002861 return Context.hasSameUnqualifiedType(T1, T2);
2862}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002863
Douglas Gregorad323a82010-01-27 03:51:04 +00002864// Per 13.3.3.2p3, compare the given standard conversion sequences to
2865// determine if one is a proper subset of the other.
2866static ImplicitConversionSequence::CompareKind
2867compareStandardConversionSubsets(ASTContext &Context,
2868 const StandardConversionSequence& SCS1,
2869 const StandardConversionSequence& SCS2) {
2870 ImplicitConversionSequence::CompareKind Result
2871 = ImplicitConversionSequence::Indistinguishable;
2872
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002873 // the identity conversion sequence is considered to be a subsequence of
Douglas Gregorae65f4b2010-05-23 22:10:15 +00002874 // any non-identity conversion sequence
Douglas Gregor4ae5b722011-06-05 06:15:20 +00002875 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2876 return ImplicitConversionSequence::Better;
2877 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2878 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002879
Douglas Gregorad323a82010-01-27 03:51:04 +00002880 if (SCS1.Second != SCS2.Second) {
2881 if (SCS1.Second == ICK_Identity)
2882 Result = ImplicitConversionSequence::Better;
2883 else if (SCS2.Second == ICK_Identity)
2884 Result = ImplicitConversionSequence::Worse;
2885 else
2886 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor5a57efd2010-06-09 03:53:18 +00002887 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregorad323a82010-01-27 03:51:04 +00002888 return ImplicitConversionSequence::Indistinguishable;
2889
2890 if (SCS1.Third == SCS2.Third) {
2891 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2892 : ImplicitConversionSequence::Indistinguishable;
2893 }
2894
2895 if (SCS1.Third == ICK_Identity)
2896 return Result == ImplicitConversionSequence::Worse
2897 ? ImplicitConversionSequence::Indistinguishable
2898 : ImplicitConversionSequence::Better;
2899
2900 if (SCS2.Third == ICK_Identity)
2901 return Result == ImplicitConversionSequence::Better
2902 ? ImplicitConversionSequence::Indistinguishable
2903 : ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002904
Douglas Gregorad323a82010-01-27 03:51:04 +00002905 return ImplicitConversionSequence::Indistinguishable;
2906}
2907
Douglas Gregor440a4832011-01-26 14:52:12 +00002908/// \brief Determine whether one of the given reference bindings is better
2909/// than the other based on what kind of bindings they are.
2910static bool isBetterReferenceBindingKind(const StandardConversionSequence &SCS1,
2911 const StandardConversionSequence &SCS2) {
2912 // C++0x [over.ics.rank]p3b4:
2913 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2914 // implicit object parameter of a non-static member function declared
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002915 // without a ref-qualifier, and *either* S1 binds an rvalue reference
Douglas Gregor440a4832011-01-26 14:52:12 +00002916 // to an rvalue and S2 binds an lvalue reference *or S1 binds an
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002917 // lvalue reference to a function lvalue and S2 binds an rvalue
Douglas Gregor440a4832011-01-26 14:52:12 +00002918 // reference*.
2919 //
2920 // FIXME: Rvalue references. We're going rogue with the above edits,
2921 // because the semantics in the current C++0x working paper (N3225 at the
2922 // time of this writing) break the standard definition of std::forward
2923 // and std::reference_wrapper when dealing with references to functions.
2924 // Proposed wording changes submitted to CWG for consideration.
Douglas Gregorfcab48b2011-01-26 19:41:18 +00002925 if (SCS1.BindsImplicitObjectArgumentWithoutRefQualifier ||
2926 SCS2.BindsImplicitObjectArgumentWithoutRefQualifier)
2927 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002928
Douglas Gregor440a4832011-01-26 14:52:12 +00002929 return (!SCS1.IsLvalueReference && SCS1.BindsToRvalue &&
2930 SCS2.IsLvalueReference) ||
2931 (SCS1.IsLvalueReference && SCS1.BindsToFunctionLvalue &&
2932 !SCS2.IsLvalueReference);
2933}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00002934
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002935/// CompareStandardConversionSequences - Compare two standard
2936/// conversion sequences to determine whether one is better than the
2937/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall120d63c2010-08-24 20:38:10 +00002938static ImplicitConversionSequence::CompareKind
2939CompareStandardConversionSequences(Sema &S,
2940 const StandardConversionSequence& SCS1,
2941 const StandardConversionSequence& SCS2)
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002942{
2943 // Standard conversion sequence S1 is a better conversion sequence
2944 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2945
2946 // -- S1 is a proper subsequence of S2 (comparing the conversion
2947 // sequences in the canonical form defined by 13.3.3.1.1,
2948 // excluding any Lvalue Transformation; the identity conversion
2949 // sequence is considered to be a subsequence of any
2950 // non-identity conversion sequence) or, if not that,
Douglas Gregorad323a82010-01-27 03:51:04 +00002951 if (ImplicitConversionSequence::CompareKind CK
John McCall120d63c2010-08-24 20:38:10 +00002952 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregorad323a82010-01-27 03:51:04 +00002953 return CK;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002954
2955 // -- the rank of S1 is better than the rank of S2 (by the rules
2956 // defined below), or, if not that,
2957 ImplicitConversionRank Rank1 = SCS1.getRank();
2958 ImplicitConversionRank Rank2 = SCS2.getRank();
2959 if (Rank1 < Rank2)
2960 return ImplicitConversionSequence::Better;
2961 else if (Rank2 < Rank1)
2962 return ImplicitConversionSequence::Worse;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00002963
Douglas Gregor57373262008-10-22 14:17:15 +00002964 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2965 // are indistinguishable unless one of the following rules
2966 // applies:
Mike Stump1eb44332009-09-09 15:08:12 +00002967
Douglas Gregor57373262008-10-22 14:17:15 +00002968 // A conversion that is not a conversion of a pointer, or
2969 // pointer to member, to bool is better than another conversion
2970 // that is such a conversion.
2971 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2972 return SCS2.isPointerConversionToBool()
2973 ? ImplicitConversionSequence::Better
2974 : ImplicitConversionSequence::Worse;
2975
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002976 // C++ [over.ics.rank]p4b2:
2977 //
2978 // If class B is derived directly or indirectly from class A,
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002979 // conversion of B* to A* is better than conversion of B* to
2980 // void*, and conversion of A* to void* is better than conversion
2981 // of B* to void*.
Mike Stump1eb44332009-09-09 15:08:12 +00002982 bool SCS1ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002983 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump1eb44332009-09-09 15:08:12 +00002984 bool SCS2ConvertsToVoid
John McCall120d63c2010-08-24 20:38:10 +00002985 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002986 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2987 // Exactly one of the conversion sequences is a conversion to
2988 // a void pointer; it's the worse conversion.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002989 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2990 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002991 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2992 // Neither conversion sequence converts to a void pointer; compare
2993 // their derived-to-base conversions.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002994 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall120d63c2010-08-24 20:38:10 +00002995 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00002996 return DerivedCK;
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00002997 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid &&
2998 !S.Context.hasSameType(SCS1.getFromType(), SCS2.getFromType())) {
Douglas Gregorf70bdb92008-10-29 14:50:44 +00002999 // Both conversion sequences are conversions to void
3000 // pointers. Compare the source types to determine if there's an
3001 // inheritance relationship in their sources.
John McCall1d318332010-01-12 00:44:57 +00003002 QualType FromType1 = SCS1.getFromType();
3003 QualType FromType2 = SCS2.getFromType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003004
3005 // Adjust the types we're converting from via the array-to-pointer
3006 // conversion, if we need to.
3007 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003008 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003009 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003010 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003011
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003012 QualType FromPointee1 = FromType1->getPointeeType().getUnqualifiedType();
3013 QualType FromPointee2 = FromType2->getPointeeType().getUnqualifiedType();
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003014
John McCall120d63c2010-08-24 20:38:10 +00003015 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor01919692009-12-13 21:37:05 +00003016 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003017 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor01919692009-12-13 21:37:05 +00003018 return ImplicitConversionSequence::Worse;
3019
3020 // Objective-C++: If one interface is more specific than the
3021 // other, it is the better one.
Douglas Gregor0f7b3dc2011-04-27 00:01:52 +00003022 const ObjCObjectPointerType* FromObjCPtr1
3023 = FromType1->getAs<ObjCObjectPointerType>();
3024 const ObjCObjectPointerType* FromObjCPtr2
3025 = FromType2->getAs<ObjCObjectPointerType>();
3026 if (FromObjCPtr1 && FromObjCPtr2) {
3027 bool AssignLeft = S.Context.canAssignObjCInterfaces(FromObjCPtr1,
3028 FromObjCPtr2);
3029 bool AssignRight = S.Context.canAssignObjCInterfaces(FromObjCPtr2,
3030 FromObjCPtr1);
3031 if (AssignLeft != AssignRight) {
3032 return AssignLeft? ImplicitConversionSequence::Better
3033 : ImplicitConversionSequence::Worse;
3034 }
Douglas Gregor01919692009-12-13 21:37:05 +00003035 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003036 }
Douglas Gregor57373262008-10-22 14:17:15 +00003037
3038 // Compare based on qualification conversions (C++ 13.3.3.2p3,
3039 // bullet 3).
Mike Stump1eb44332009-09-09 15:08:12 +00003040 if (ImplicitConversionSequence::CompareKind QualCK
John McCall120d63c2010-08-24 20:38:10 +00003041 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003042 return QualCK;
Douglas Gregor57373262008-10-22 14:17:15 +00003043
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003044 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Douglas Gregor440a4832011-01-26 14:52:12 +00003045 // Check for a better reference binding based on the kind of bindings.
3046 if (isBetterReferenceBindingKind(SCS1, SCS2))
3047 return ImplicitConversionSequence::Better;
3048 else if (isBetterReferenceBindingKind(SCS2, SCS1))
3049 return ImplicitConversionSequence::Worse;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003050
Sebastian Redlf2e21e52009-03-22 23:49:27 +00003051 // C++ [over.ics.rank]p3b4:
3052 // -- S1 and S2 are reference bindings (8.5.3), and the types to
3053 // which the references refer are the same type except for
3054 // top-level cv-qualifiers, and the type to which the reference
3055 // initialized by S2 refers is more cv-qualified than the type
3056 // to which the reference initialized by S1 refers.
Douglas Gregorad323a82010-01-27 03:51:04 +00003057 QualType T1 = SCS1.getToType(2);
3058 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003059 T1 = S.Context.getCanonicalType(T1);
3060 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003061 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003062 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3063 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003064 if (UnqualT1 == UnqualT2) {
John McCallf85e1932011-06-15 23:02:42 +00003065 // Objective-C++ ARC: If the references refer to objects with different
3066 // lifetimes, prefer bindings that don't change lifetime.
3067 if (SCS1.ObjCLifetimeConversionBinding !=
3068 SCS2.ObjCLifetimeConversionBinding) {
3069 return SCS1.ObjCLifetimeConversionBinding
3070 ? ImplicitConversionSequence::Worse
3071 : ImplicitConversionSequence::Better;
3072 }
3073
Chandler Carruth6df868e2010-12-12 08:17:55 +00003074 // If the type is an array type, promote the element qualifiers to the
3075 // type for comparison.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003076 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003077 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003078 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003079 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003080 if (T2.isMoreQualifiedThan(T1))
3081 return ImplicitConversionSequence::Better;
3082 else if (T1.isMoreQualifiedThan(T2))
John McCallf85e1932011-06-15 23:02:42 +00003083 return ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003084 }
3085 }
Douglas Gregor57373262008-10-22 14:17:15 +00003086
Francois Pichet1c98d622011-09-18 21:37:37 +00003087 // In Microsoft mode, prefer an integral conversion to a
3088 // floating-to-integral conversion if the integral conversion
3089 // is between types of the same size.
3090 // For example:
3091 // void f(float);
3092 // void f(int);
3093 // int main {
3094 // long a;
3095 // f(a);
3096 // }
3097 // Here, MSVC will call f(int) instead of generating a compile error
3098 // as clang will do in standard mode.
3099 if (S.getLangOptions().MicrosoftMode &&
3100 SCS1.Second == ICK_Integral_Conversion &&
3101 SCS2.Second == ICK_Floating_Integral &&
3102 S.Context.getTypeSize(SCS1.getFromType()) ==
3103 S.Context.getTypeSize(SCS1.getToType(2)))
3104 return ImplicitConversionSequence::Better;
3105
Douglas Gregor57373262008-10-22 14:17:15 +00003106 return ImplicitConversionSequence::Indistinguishable;
3107}
3108
3109/// CompareQualificationConversions - Compares two standard conversion
3110/// sequences to determine whether they can be ranked based on their
Mike Stump1eb44332009-09-09 15:08:12 +00003111/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
3112ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003113CompareQualificationConversions(Sema &S,
3114 const StandardConversionSequence& SCS1,
3115 const StandardConversionSequence& SCS2) {
Douglas Gregorba7e2102008-10-22 15:04:37 +00003116 // C++ 13.3.3.2p3:
Douglas Gregor57373262008-10-22 14:17:15 +00003117 // -- S1 and S2 differ only in their qualification conversion and
3118 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
3119 // cv-qualification signature of type T1 is a proper subset of
3120 // the cv-qualification signature of type T2, and S1 is not the
3121 // deprecated string literal array-to-pointer conversion (4.2).
3122 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
3123 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
3124 return ImplicitConversionSequence::Indistinguishable;
3125
3126 // FIXME: the example in the standard doesn't use a qualification
3127 // conversion (!)
Douglas Gregorad323a82010-01-27 03:51:04 +00003128 QualType T1 = SCS1.getToType(2);
3129 QualType T2 = SCS2.getToType(2);
John McCall120d63c2010-08-24 20:38:10 +00003130 T1 = S.Context.getCanonicalType(T1);
3131 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003132 Qualifiers T1Quals, T2Quals;
John McCall120d63c2010-08-24 20:38:10 +00003133 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
3134 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregor57373262008-10-22 14:17:15 +00003135
3136 // If the types are the same, we won't learn anything by unwrapped
3137 // them.
Chandler Carruth28e318c2009-12-29 07:16:59 +00003138 if (UnqualT1 == UnqualT2)
Douglas Gregor57373262008-10-22 14:17:15 +00003139 return ImplicitConversionSequence::Indistinguishable;
3140
Chandler Carruth28e318c2009-12-29 07:16:59 +00003141 // If the type is an array type, promote the element qualifiers to the type
3142 // for comparison.
3143 if (isa<ArrayType>(T1) && T1Quals)
John McCall120d63c2010-08-24 20:38:10 +00003144 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003145 if (isa<ArrayType>(T2) && T2Quals)
John McCall120d63c2010-08-24 20:38:10 +00003146 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth28e318c2009-12-29 07:16:59 +00003147
Mike Stump1eb44332009-09-09 15:08:12 +00003148 ImplicitConversionSequence::CompareKind Result
Douglas Gregor57373262008-10-22 14:17:15 +00003149 = ImplicitConversionSequence::Indistinguishable;
John McCallf85e1932011-06-15 23:02:42 +00003150
3151 // Objective-C++ ARC:
3152 // Prefer qualification conversions not involving a change in lifetime
3153 // to qualification conversions that do not change lifetime.
3154 if (SCS1.QualificationIncludesObjCLifetime !=
3155 SCS2.QualificationIncludesObjCLifetime) {
3156 Result = SCS1.QualificationIncludesObjCLifetime
3157 ? ImplicitConversionSequence::Worse
3158 : ImplicitConversionSequence::Better;
3159 }
3160
John McCall120d63c2010-08-24 20:38:10 +00003161 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregor57373262008-10-22 14:17:15 +00003162 // Within each iteration of the loop, we check the qualifiers to
3163 // determine if this still looks like a qualification
3164 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregorf8268ae2008-10-22 17:49:05 +00003165 // pointers or pointers-to-members and do it all again
Douglas Gregor57373262008-10-22 14:17:15 +00003166 // until there are no more pointers or pointers-to-members left
3167 // to unwrap. This essentially mimics what
3168 // IsQualificationConversion does, but here we're checking for a
3169 // strict subset of qualifiers.
3170 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
3171 // The qualifiers are the same, so this doesn't tell us anything
3172 // about how the sequences rank.
3173 ;
3174 else if (T2.isMoreQualifiedThan(T1)) {
3175 // T1 has fewer qualifiers, so it could be the better sequence.
3176 if (Result == ImplicitConversionSequence::Worse)
3177 // Neither has qualifiers that are a subset of the other's
3178 // qualifiers.
3179 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003180
Douglas Gregor57373262008-10-22 14:17:15 +00003181 Result = ImplicitConversionSequence::Better;
3182 } else if (T1.isMoreQualifiedThan(T2)) {
3183 // T2 has fewer qualifiers, so it could be the better sequence.
3184 if (Result == ImplicitConversionSequence::Better)
3185 // Neither has qualifiers that are a subset of the other's
3186 // qualifiers.
3187 return ImplicitConversionSequence::Indistinguishable;
Mike Stump1eb44332009-09-09 15:08:12 +00003188
Douglas Gregor57373262008-10-22 14:17:15 +00003189 Result = ImplicitConversionSequence::Worse;
3190 } else {
3191 // Qualifiers are disjoint.
3192 return ImplicitConversionSequence::Indistinguishable;
3193 }
3194
3195 // If the types after this point are equivalent, we're done.
John McCall120d63c2010-08-24 20:38:10 +00003196 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregor57373262008-10-22 14:17:15 +00003197 break;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003198 }
3199
Douglas Gregor57373262008-10-22 14:17:15 +00003200 // Check that the winning standard conversion sequence isn't using
3201 // the deprecated string literal array to pointer conversion.
3202 switch (Result) {
3203 case ImplicitConversionSequence::Better:
Douglas Gregora9bff302010-02-28 18:30:25 +00003204 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003205 Result = ImplicitConversionSequence::Indistinguishable;
3206 break;
3207
3208 case ImplicitConversionSequence::Indistinguishable:
3209 break;
3210
3211 case ImplicitConversionSequence::Worse:
Douglas Gregora9bff302010-02-28 18:30:25 +00003212 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregor57373262008-10-22 14:17:15 +00003213 Result = ImplicitConversionSequence::Indistinguishable;
3214 break;
3215 }
3216
3217 return Result;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00003218}
3219
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003220/// CompareDerivedToBaseConversions - Compares two standard conversion
3221/// sequences to determine whether they can be ranked based on their
Douglas Gregorcb7de522008-11-26 23:31:11 +00003222/// various kinds of derived-to-base conversions (C++
3223/// [over.ics.rank]p4b3). As part of these checks, we also look at
3224/// conversions between Objective-C interface types.
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003225ImplicitConversionSequence::CompareKind
John McCall120d63c2010-08-24 20:38:10 +00003226CompareDerivedToBaseConversions(Sema &S,
3227 const StandardConversionSequence& SCS1,
3228 const StandardConversionSequence& SCS2) {
John McCall1d318332010-01-12 00:44:57 +00003229 QualType FromType1 = SCS1.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003230 QualType ToType1 = SCS1.getToType(1);
John McCall1d318332010-01-12 00:44:57 +00003231 QualType FromType2 = SCS2.getFromType();
Douglas Gregorad323a82010-01-27 03:51:04 +00003232 QualType ToType2 = SCS2.getToType(1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003233
3234 // Adjust the types we're converting from via the array-to-pointer
3235 // conversion, if we need to.
3236 if (SCS1.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003237 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003238 if (SCS2.First == ICK_Array_To_Pointer)
John McCall120d63c2010-08-24 20:38:10 +00003239 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003240
3241 // Canonicalize all of the types.
John McCall120d63c2010-08-24 20:38:10 +00003242 FromType1 = S.Context.getCanonicalType(FromType1);
3243 ToType1 = S.Context.getCanonicalType(ToType1);
3244 FromType2 = S.Context.getCanonicalType(FromType2);
3245 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003246
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003247 // C++ [over.ics.rank]p4b3:
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003248 //
3249 // If class B is derived directly or indirectly from class A and
3250 // class C is derived directly or indirectly from B,
Douglas Gregorcb7de522008-11-26 23:31:11 +00003251 //
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003252 // Compare based on pointer conversions.
Mike Stump1eb44332009-09-09 15:08:12 +00003253 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregor7ca09762008-11-27 01:19:21 +00003254 SCS2.Second == ICK_Pointer_Conversion &&
3255 /*FIXME: Remove if Objective-C id conversions get their own rank*/
3256 FromType1->isPointerType() && FromType2->isPointerType() &&
3257 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003258 QualType FromPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003259 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +00003260 QualType ToPointee1
Ted Kremenek6217b802009-07-29 21:53:49 +00003261 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003262 QualType FromPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003263 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003264 QualType ToPointee2
Ted Kremenek6217b802009-07-29 21:53:49 +00003265 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregorcb7de522008-11-26 23:31:11 +00003266
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003267 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003268 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003269 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003270 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003271 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003272 return ImplicitConversionSequence::Worse;
3273 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003274
3275 // -- conversion of B* to A* is better than conversion of C* to A*,
3276 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003277 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003278 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003279 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003280 return ImplicitConversionSequence::Worse;
Douglas Gregor395cc372011-01-31 18:51:41 +00003281 }
3282 } else if (SCS1.Second == ICK_Pointer_Conversion &&
3283 SCS2.Second == ICK_Pointer_Conversion) {
3284 const ObjCObjectPointerType *FromPtr1
3285 = FromType1->getAs<ObjCObjectPointerType>();
3286 const ObjCObjectPointerType *FromPtr2
3287 = FromType2->getAs<ObjCObjectPointerType>();
3288 const ObjCObjectPointerType *ToPtr1
3289 = ToType1->getAs<ObjCObjectPointerType>();
3290 const ObjCObjectPointerType *ToPtr2
3291 = ToType2->getAs<ObjCObjectPointerType>();
3292
3293 if (FromPtr1 && FromPtr2 && ToPtr1 && ToPtr2) {
3294 // Apply the same conversion ranking rules for Objective-C pointer types
3295 // that we do for C++ pointers to class types. However, we employ the
3296 // Objective-C pseudo-subtyping relationship used for assignment of
3297 // Objective-C pointer types.
3298 bool FromAssignLeft
3299 = S.Context.canAssignObjCInterfaces(FromPtr1, FromPtr2);
3300 bool FromAssignRight
3301 = S.Context.canAssignObjCInterfaces(FromPtr2, FromPtr1);
3302 bool ToAssignLeft
3303 = S.Context.canAssignObjCInterfaces(ToPtr1, ToPtr2);
3304 bool ToAssignRight
3305 = S.Context.canAssignObjCInterfaces(ToPtr2, ToPtr1);
3306
3307 // A conversion to an a non-id object pointer type or qualified 'id'
3308 // type is better than a conversion to 'id'.
3309 if (ToPtr1->isObjCIdType() &&
3310 (ToPtr2->isObjCQualifiedIdType() || ToPtr2->getInterfaceDecl()))
3311 return ImplicitConversionSequence::Worse;
3312 if (ToPtr2->isObjCIdType() &&
3313 (ToPtr1->isObjCQualifiedIdType() || ToPtr1->getInterfaceDecl()))
3314 return ImplicitConversionSequence::Better;
3315
3316 // A conversion to a non-id object pointer type is better than a
3317 // conversion to a qualified 'id' type
3318 if (ToPtr1->isObjCQualifiedIdType() && ToPtr2->getInterfaceDecl())
3319 return ImplicitConversionSequence::Worse;
3320 if (ToPtr2->isObjCQualifiedIdType() && ToPtr1->getInterfaceDecl())
3321 return ImplicitConversionSequence::Better;
3322
3323 // A conversion to an a non-Class object pointer type or qualified 'Class'
3324 // type is better than a conversion to 'Class'.
3325 if (ToPtr1->isObjCClassType() &&
3326 (ToPtr2->isObjCQualifiedClassType() || ToPtr2->getInterfaceDecl()))
3327 return ImplicitConversionSequence::Worse;
3328 if (ToPtr2->isObjCClassType() &&
3329 (ToPtr1->isObjCQualifiedClassType() || ToPtr1->getInterfaceDecl()))
3330 return ImplicitConversionSequence::Better;
3331
3332 // A conversion to a non-Class object pointer type is better than a
3333 // conversion to a qualified 'Class' type.
3334 if (ToPtr1->isObjCQualifiedClassType() && ToPtr2->getInterfaceDecl())
3335 return ImplicitConversionSequence::Worse;
3336 if (ToPtr2->isObjCQualifiedClassType() && ToPtr1->getInterfaceDecl())
3337 return ImplicitConversionSequence::Better;
Mike Stump1eb44332009-09-09 15:08:12 +00003338
Douglas Gregor395cc372011-01-31 18:51:41 +00003339 // -- "conversion of C* to B* is better than conversion of C* to A*,"
3340 if (S.Context.hasSameType(FromType1, FromType2) &&
3341 !FromPtr1->isObjCIdType() && !FromPtr1->isObjCClassType() &&
3342 (ToAssignLeft != ToAssignRight))
3343 return ToAssignLeft? ImplicitConversionSequence::Worse
3344 : ImplicitConversionSequence::Better;
3345
3346 // -- "conversion of B* to A* is better than conversion of C* to A*,"
3347 if (S.Context.hasSameUnqualifiedType(ToType1, ToType2) &&
3348 (FromAssignLeft != FromAssignRight))
3349 return FromAssignLeft? ImplicitConversionSequence::Better
3350 : ImplicitConversionSequence::Worse;
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003351 }
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003352 }
Douglas Gregor395cc372011-01-31 18:51:41 +00003353
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003354 // Ranking of member-pointer types.
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003355 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
3356 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
3357 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003358 const MemberPointerType * FromMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003359 FromType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003360 const MemberPointerType * ToMemPointer1 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003361 ToType1->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003362 const MemberPointerType * FromMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003363 FromType2->getAs<MemberPointerType>();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003364 const MemberPointerType * ToMemPointer2 =
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003365 ToType2->getAs<MemberPointerType>();
3366 const Type *FromPointeeType1 = FromMemPointer1->getClass();
3367 const Type *ToPointeeType1 = ToMemPointer1->getClass();
3368 const Type *FromPointeeType2 = FromMemPointer2->getClass();
3369 const Type *ToPointeeType2 = ToMemPointer2->getClass();
3370 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
3371 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
3372 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
3373 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanian2357da02009-10-20 20:07:35 +00003374 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003375 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003376 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003377 return ImplicitConversionSequence::Worse;
John McCall120d63c2010-08-24 20:38:10 +00003378 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003379 return ImplicitConversionSequence::Better;
3380 }
3381 // conversion of B::* to C::* is better than conversion of A::* to C::*
3382 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall120d63c2010-08-24 20:38:10 +00003383 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003384 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003385 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian8577c982009-10-20 20:04:46 +00003386 return ImplicitConversionSequence::Worse;
3387 }
3388 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003389
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00003390 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor225c41e2008-11-03 19:09:14 +00003391 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor9e239322010-02-25 19:01:05 +00003392 // -- binding of an expression of type C to a reference of type
3393 // B& is better than binding an expression of type C to a
3394 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003395 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3396 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3397 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003398 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003399 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003400 return ImplicitConversionSequence::Worse;
3401 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003402
Douglas Gregor225c41e2008-11-03 19:09:14 +00003403 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor9e239322010-02-25 19:01:05 +00003404 // -- binding of an expression of type B to a reference of type
3405 // A& is better than binding an expression of type C to a
3406 // reference of type A&,
John McCall120d63c2010-08-24 20:38:10 +00003407 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
3408 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
3409 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003410 return ImplicitConversionSequence::Better;
John McCall120d63c2010-08-24 20:38:10 +00003411 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor225c41e2008-11-03 19:09:14 +00003412 return ImplicitConversionSequence::Worse;
3413 }
3414 }
Douglas Gregorf70bdb92008-10-29 14:50:44 +00003415
Douglas Gregorbc0805a2008-10-23 00:40:37 +00003416 return ImplicitConversionSequence::Indistinguishable;
3417}
3418
Douglas Gregorabe183d2010-04-13 16:31:36 +00003419/// CompareReferenceRelationship - Compare the two types T1 and T2 to
3420/// determine whether they are reference-related,
3421/// reference-compatible, reference-compatible with added
3422/// qualification, or incompatible, for use in C++ initialization by
3423/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
3424/// type, and the first type (T1) is the pointee type of the reference
3425/// type being initialized.
3426Sema::ReferenceCompareResult
3427Sema::CompareReferenceRelationship(SourceLocation Loc,
3428 QualType OrigT1, QualType OrigT2,
Douglas Gregor569c3162010-08-07 11:51:51 +00003429 bool &DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003430 bool &ObjCConversion,
3431 bool &ObjCLifetimeConversion) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003432 assert(!OrigT1->isReferenceType() &&
3433 "T1 must be the pointee type of the reference type");
3434 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
3435
3436 QualType T1 = Context.getCanonicalType(OrigT1);
3437 QualType T2 = Context.getCanonicalType(OrigT2);
3438 Qualifiers T1Quals, T2Quals;
3439 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
3440 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
3441
3442 // C++ [dcl.init.ref]p4:
3443 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
3444 // reference-related to "cv2 T2" if T1 is the same type as T2, or
3445 // T1 is a base class of T2.
Douglas Gregor569c3162010-08-07 11:51:51 +00003446 DerivedToBase = false;
3447 ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003448 ObjCLifetimeConversion = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003449 if (UnqualT1 == UnqualT2) {
3450 // Nothing to do.
3451 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregorabe183d2010-04-13 16:31:36 +00003452 IsDerivedFrom(UnqualT2, UnqualT1))
3453 DerivedToBase = true;
Douglas Gregor569c3162010-08-07 11:51:51 +00003454 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
3455 UnqualT2->isObjCObjectOrInterfaceType() &&
3456 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
3457 ObjCConversion = true;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003458 else
3459 return Ref_Incompatible;
3460
3461 // At this point, we know that T1 and T2 are reference-related (at
3462 // least).
3463
3464 // If the type is an array type, promote the element qualifiers to the type
3465 // for comparison.
3466 if (isa<ArrayType>(T1) && T1Quals)
3467 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
3468 if (isa<ArrayType>(T2) && T2Quals)
3469 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
3470
3471 // C++ [dcl.init.ref]p4:
3472 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
3473 // reference-related to T2 and cv1 is the same cv-qualification
3474 // as, or greater cv-qualification than, cv2. For purposes of
3475 // overload resolution, cases for which cv1 is greater
3476 // cv-qualification than cv2 are identified as
3477 // reference-compatible with added qualification (see 13.3.3.2).
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003478 //
3479 // Note that we also require equivalence of Objective-C GC and address-space
3480 // qualifiers when performing these computations, so that e.g., an int in
3481 // address space 1 is not reference-compatible with an int in address
3482 // space 2.
John McCallf85e1932011-06-15 23:02:42 +00003483 if (T1Quals.getObjCLifetime() != T2Quals.getObjCLifetime() &&
3484 T1Quals.compatiblyIncludesObjCLifetime(T2Quals)) {
3485 T1Quals.removeObjCLifetime();
3486 T2Quals.removeObjCLifetime();
3487 ObjCLifetimeConversion = true;
3488 }
3489
Douglas Gregora6ce3e62011-04-28 17:56:11 +00003490 if (T1Quals == T2Quals)
Douglas Gregorabe183d2010-04-13 16:31:36 +00003491 return Ref_Compatible;
John McCallf85e1932011-06-15 23:02:42 +00003492 else if (T1Quals.compatiblyIncludes(T2Quals))
Douglas Gregorabe183d2010-04-13 16:31:36 +00003493 return Ref_Compatible_With_Added_Qualification;
3494 else
3495 return Ref_Related;
3496}
3497
Douglas Gregor604eb652010-08-11 02:15:33 +00003498/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redl4680bf22010-06-30 18:13:39 +00003499/// with DeclType. Return true if something definite is found.
3500static bool
Douglas Gregor604eb652010-08-11 02:15:33 +00003501FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
3502 QualType DeclType, SourceLocation DeclLoc,
3503 Expr *Init, QualType T2, bool AllowRvalues,
3504 bool AllowExplicit) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003505 assert(T2->isRecordType() && "Can only find conversions of record types.");
3506 CXXRecordDecl *T2RecordDecl
3507 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
3508
3509 OverloadCandidateSet CandidateSet(DeclLoc);
3510 const UnresolvedSetImpl *Conversions
3511 = T2RecordDecl->getVisibleConversionFunctions();
3512 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3513 E = Conversions->end(); I != E; ++I) {
3514 NamedDecl *D = *I;
3515 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
3516 if (isa<UsingShadowDecl>(D))
3517 D = cast<UsingShadowDecl>(D)->getTargetDecl();
3518
3519 FunctionTemplateDecl *ConvTemplate
3520 = dyn_cast<FunctionTemplateDecl>(D);
3521 CXXConversionDecl *Conv;
3522 if (ConvTemplate)
3523 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
3524 else
3525 Conv = cast<CXXConversionDecl>(D);
3526
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003527 // If this is an explicit conversion, and we're not allowed to consider
Douglas Gregor604eb652010-08-11 02:15:33 +00003528 // explicit conversions, skip it.
3529 if (!AllowExplicit && Conv->isExplicit())
3530 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003531
Douglas Gregor604eb652010-08-11 02:15:33 +00003532 if (AllowRvalues) {
3533 bool DerivedToBase = false;
3534 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003535 bool ObjCLifetimeConversion = false;
Douglas Gregor203050c2011-10-04 23:59:32 +00003536
3537 // If we are initializing an rvalue reference, don't permit conversion
3538 // functions that return lvalues.
3539 if (!ConvTemplate && DeclType->isRValueReferenceType()) {
3540 const ReferenceType *RefType
3541 = Conv->getConversionType()->getAs<LValueReferenceType>();
3542 if (RefType && !RefType->getPointeeType()->isFunctionType())
3543 continue;
3544 }
3545
Douglas Gregor604eb652010-08-11 02:15:33 +00003546 if (!ConvTemplate &&
Chandler Carruth6df868e2010-12-12 08:17:55 +00003547 S.CompareReferenceRelationship(
3548 DeclLoc,
3549 Conv->getConversionType().getNonReferenceType()
3550 .getUnqualifiedType(),
3551 DeclType.getNonReferenceType().getUnqualifiedType(),
John McCallf85e1932011-06-15 23:02:42 +00003552 DerivedToBase, ObjCConversion, ObjCLifetimeConversion) ==
Chandler Carruth6df868e2010-12-12 08:17:55 +00003553 Sema::Ref_Incompatible)
Douglas Gregor604eb652010-08-11 02:15:33 +00003554 continue;
3555 } else {
3556 // If the conversion function doesn't return a reference type,
3557 // it can't be considered for this conversion. An rvalue reference
3558 // is only acceptable if its referencee is a function type.
3559
3560 const ReferenceType *RefType =
3561 Conv->getConversionType()->getAs<ReferenceType>();
3562 if (!RefType ||
3563 (!RefType->isLValueReferenceType() &&
3564 !RefType->getPointeeType()->isFunctionType()))
3565 continue;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003566 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003567
Douglas Gregor604eb652010-08-11 02:15:33 +00003568 if (ConvTemplate)
3569 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003570 Init, DeclType, CandidateSet);
Douglas Gregor604eb652010-08-11 02:15:33 +00003571 else
3572 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003573 DeclType, CandidateSet);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003574 }
3575
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003576 bool HadMultipleCandidates = (CandidateSet.size() > 1);
3577
Sebastian Redl4680bf22010-06-30 18:13:39 +00003578 OverloadCandidateSet::iterator Best;
Douglas Gregor8fcc5162010-09-12 08:07:23 +00003579 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003580 case OR_Success:
3581 // C++ [over.ics.ref]p1:
3582 //
3583 // [...] If the parameter binds directly to the result of
3584 // applying a conversion function to the argument
3585 // expression, the implicit conversion sequence is a
3586 // user-defined conversion sequence (13.3.3.1.2), with the
3587 // second standard conversion sequence either an identity
3588 // conversion or, if the conversion function returns an
3589 // entity of a type that is a derived class of the parameter
3590 // type, a derived-to-base Conversion.
3591 if (!Best->FinalConversion.DirectBinding)
3592 return false;
3593
Chandler Carruth25ca4212011-02-25 19:41:05 +00003594 if (Best->Function)
3595 S.MarkDeclarationReferenced(DeclLoc, Best->Function);
Sebastian Redl4680bf22010-06-30 18:13:39 +00003596 ICS.setUserDefined();
3597 ICS.UserDefined.Before = Best->Conversions[0].Standard;
3598 ICS.UserDefined.After = Best->FinalConversion;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00003599 ICS.UserDefined.HadMultipleCandidates = HadMultipleCandidates;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003600 ICS.UserDefined.ConversionFunction = Best->Function;
John McCallca82a822011-09-21 08:36:56 +00003601 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003602 ICS.UserDefined.EllipsisConversion = false;
3603 assert(ICS.UserDefined.After.ReferenceBinding &&
3604 ICS.UserDefined.After.DirectBinding &&
3605 "Expected a direct reference binding!");
3606 return true;
3607
3608 case OR_Ambiguous:
3609 ICS.setAmbiguous();
3610 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
3611 Cand != CandidateSet.end(); ++Cand)
3612 if (Cand->Viable)
3613 ICS.Ambiguous.addConversion(Cand->Function);
3614 return true;
3615
3616 case OR_No_Viable_Function:
3617 case OR_Deleted:
3618 // There was no suitable conversion, or we found a deleted
3619 // conversion; continue with other checks.
3620 return false;
3621 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003622
Eric Christopher1c3d5022010-06-30 18:36:32 +00003623 return false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003624}
3625
Douglas Gregorabe183d2010-04-13 16:31:36 +00003626/// \brief Compute an implicit conversion sequence for reference
3627/// initialization.
3628static ImplicitConversionSequence
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00003629TryReferenceInit(Sema &S, Expr *Init, QualType DeclType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00003630 SourceLocation DeclLoc,
3631 bool SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00003632 bool AllowExplicit) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003633 assert(DeclType->isReferenceType() && "Reference init needs a reference");
3634
3635 // Most paths end in a failed conversion.
3636 ImplicitConversionSequence ICS;
3637 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3638
3639 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
3640 QualType T2 = Init->getType();
3641
3642 // If the initializer is the address of an overloaded function, try
3643 // to resolve the overloaded function. If all goes well, T2 is the
3644 // type of the resulting function.
3645 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3646 DeclAccessPair Found;
3647 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
3648 false, Found))
3649 T2 = Fn->getType();
3650 }
3651
3652 // Compute some basic properties of the types and the initializer.
3653 bool isRValRef = DeclType->isRValueReferenceType();
3654 bool DerivedToBase = false;
Douglas Gregor569c3162010-08-07 11:51:51 +00003655 bool ObjCConversion = false;
John McCallf85e1932011-06-15 23:02:42 +00003656 bool ObjCLifetimeConversion = false;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003657 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003658 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor569c3162010-08-07 11:51:51 +00003659 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
John McCallf85e1932011-06-15 23:02:42 +00003660 ObjCConversion, ObjCLifetimeConversion);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003661
Douglas Gregorabe183d2010-04-13 16:31:36 +00003662
Sebastian Redl4680bf22010-06-30 18:13:39 +00003663 // C++0x [dcl.init.ref]p5:
Douglas Gregor66821b52010-04-18 09:22:00 +00003664 // A reference to type "cv1 T1" is initialized by an expression
3665 // of type "cv2 T2" as follows:
3666
Sebastian Redl4680bf22010-06-30 18:13:39 +00003667 // -- If reference is an lvalue reference and the initializer expression
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003668 if (!isRValRef) {
Sebastian Redl4680bf22010-06-30 18:13:39 +00003669 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
3670 // reference-compatible with "cv2 T2," or
3671 //
3672 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
3673 if (InitCategory.isLValue() &&
3674 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregorabe183d2010-04-13 16:31:36 +00003675 // C++ [over.ics.ref]p1:
Sebastian Redl4680bf22010-06-30 18:13:39 +00003676 // When a parameter of reference type binds directly (8.5.3)
3677 // to an argument expression, the implicit conversion sequence
3678 // is the identity conversion, unless the argument expression
3679 // has a type that is a derived class of the parameter type,
3680 // in which case the implicit conversion sequence is a
3681 // derived-to-base Conversion (13.3.3.1).
3682 ICS.setStandard();
3683 ICS.Standard.First = ICK_Identity;
Douglas Gregor569c3162010-08-07 11:51:51 +00003684 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3685 : ObjCConversion? ICK_Compatible_Conversion
3686 : ICK_Identity;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003687 ICS.Standard.Third = ICK_Identity;
3688 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3689 ICS.Standard.setToType(0, T2);
3690 ICS.Standard.setToType(1, T1);
3691 ICS.Standard.setToType(2, T1);
3692 ICS.Standard.ReferenceBinding = true;
3693 ICS.Standard.DirectBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003694 ICS.Standard.IsLvalueReference = !isRValRef;
3695 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3696 ICS.Standard.BindsToRvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003697 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003698 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003699 ICS.Standard.CopyConstructor = 0;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003700
Sebastian Redl4680bf22010-06-30 18:13:39 +00003701 // Nothing more to do: the inaccessibility/ambiguity check for
3702 // derived-to-base conversions is suppressed when we're
3703 // computing the implicit conversion sequence (C++
3704 // [over.best.ics]p2).
Douglas Gregorabe183d2010-04-13 16:31:36 +00003705 return ICS;
Sebastian Redl4680bf22010-06-30 18:13:39 +00003706 }
Douglas Gregorabe183d2010-04-13 16:31:36 +00003707
Sebastian Redl4680bf22010-06-30 18:13:39 +00003708 // -- has a class type (i.e., T2 is a class type), where T1 is
3709 // not reference-related to T2, and can be implicitly
3710 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
3711 // is reference-compatible with "cv3 T3" 92) (this
3712 // conversion is selected by enumerating the applicable
3713 // conversion functions (13.3.1.6) and choosing the best
3714 // one through overload resolution (13.3)),
3715 if (!SuppressUserConversions && T2->isRecordType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003716 !S.RequireCompleteType(DeclLoc, T2, 0) &&
Sebastian Redl4680bf22010-06-30 18:13:39 +00003717 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor604eb652010-08-11 02:15:33 +00003718 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3719 Init, T2, /*AllowRvalues=*/false,
3720 AllowExplicit))
Sebastian Redl4680bf22010-06-30 18:13:39 +00003721 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003722 }
3723 }
3724
Sebastian Redl4680bf22010-06-30 18:13:39 +00003725 // -- Otherwise, the reference shall be an lvalue reference to a
3726 // non-volatile const type (i.e., cv1 shall be const), or the reference
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003727 // shall be an rvalue reference.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003728 //
Douglas Gregor66821b52010-04-18 09:22:00 +00003729 // We actually handle one oddity of C++ [over.ics.ref] at this
3730 // point, which is that, due to p2 (which short-circuits reference
3731 // binding by only attempting a simple conversion for non-direct
3732 // bindings) and p3's strange wording, we allow a const volatile
3733 // reference to bind to an rvalue. Hence the check for the presence
3734 // of "const" rather than checking for "const" being the only
3735 // qualifier.
Sebastian Redl4680bf22010-06-30 18:13:39 +00003736 // This is also the point where rvalue references and lvalue inits no longer
3737 // go together.
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003738 if (!isRValRef && !T1.isConstQualified())
Douglas Gregorabe183d2010-04-13 16:31:36 +00003739 return ICS;
3740
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003741 // -- If the initializer expression
3742 //
3743 // -- is an xvalue, class prvalue, array prvalue or function
John McCallf85e1932011-06-15 23:02:42 +00003744 // lvalue and "cv1 T1" is reference-compatible with "cv2 T2", or
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003745 if (RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification &&
3746 (InitCategory.isXValue() ||
3747 (InitCategory.isPRValue() && (T2->isRecordType() || T2->isArrayType())) ||
3748 (InitCategory.isLValue() && T2->isFunctionType()))) {
3749 ICS.setStandard();
3750 ICS.Standard.First = ICK_Identity;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003751 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003752 : ObjCConversion? ICK_Compatible_Conversion
3753 : ICK_Identity;
3754 ICS.Standard.Third = ICK_Identity;
3755 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3756 ICS.Standard.setToType(0, T2);
3757 ICS.Standard.setToType(1, T1);
3758 ICS.Standard.setToType(2, T1);
3759 ICS.Standard.ReferenceBinding = true;
3760 // In C++0x, this is always a direct binding. In C++98/03, it's a direct
3761 // binding unless we're binding to a class prvalue.
3762 // Note: Although xvalues wouldn't normally show up in C++98/03 code, we
3763 // allow the use of rvalue references in C++98/03 for the benefit of
3764 // standard library implementors; therefore, we need the xvalue check here.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003765 ICS.Standard.DirectBinding =
3766 S.getLangOptions().CPlusPlus0x ||
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003767 (InitCategory.isPRValue() && !T2->isRecordType());
Douglas Gregor440a4832011-01-26 14:52:12 +00003768 ICS.Standard.IsLvalueReference = !isRValRef;
3769 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003770 ICS.Standard.BindsToRvalue = InitCategory.isRValue();
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003771 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003772 ICS.Standard.ObjCLifetimeConversionBinding = ObjCLifetimeConversion;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003773 ICS.Standard.CopyConstructor = 0;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003774 return ICS;
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003775 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003776
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003777 // -- has a class type (i.e., T2 is a class type), where T1 is not
3778 // reference-related to T2, and can be implicitly converted to
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003779 // an xvalue, class prvalue, or function lvalue of type
3780 // "cv3 T3", where "cv1 T1" is reference-compatible with
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003781 // "cv3 T3",
3782 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003783 // then the reference is bound to the value of the initializer
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003784 // expression in the first case and to the result of the conversion
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003785 // in the second case (or, in either case, to an appropriate base
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003786 // class subobject).
3787 if (!SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003788 T2->isRecordType() && !S.RequireCompleteType(DeclLoc, T2, 0) &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003789 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3790 Init, T2, /*AllowRvalues=*/true,
3791 AllowExplicit)) {
3792 // In the second case, if the reference is an rvalue reference
3793 // and the second standard conversion sequence of the
3794 // user-defined conversion sequence includes an lvalue-to-rvalue
3795 // conversion, the program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003796 if (ICS.isUserDefined() && isRValRef &&
Douglas Gregor8dde14e2011-01-24 16:14:37 +00003797 ICS.UserDefined.After.First == ICK_Lvalue_To_Rvalue)
3798 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
3799
Douglas Gregor68ed68b2011-01-21 16:36:05 +00003800 return ICS;
Rafael Espindolaaa5952c2011-01-22 15:32:35 +00003801 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00003802
Douglas Gregorabe183d2010-04-13 16:31:36 +00003803 // -- Otherwise, a temporary of type "cv1 T1" is created and
3804 // initialized from the initializer expression using the
3805 // rules for a non-reference copy initialization (8.5). The
3806 // reference is then bound to the temporary. If T1 is
3807 // reference-related to T2, cv1 must be the same
3808 // cv-qualification as, or greater cv-qualification than,
3809 // cv2; otherwise, the program is ill-formed.
3810 if (RefRelationship == Sema::Ref_Related) {
3811 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3812 // we would be reference-compatible or reference-compatible with
3813 // added qualification. But that wasn't the case, so the reference
3814 // initialization fails.
John McCallf85e1932011-06-15 23:02:42 +00003815 //
3816 // Note that we only want to check address spaces and cvr-qualifiers here.
3817 // ObjC GC and lifetime qualifiers aren't important.
3818 Qualifiers T1Quals = T1.getQualifiers();
3819 Qualifiers T2Quals = T2.getQualifiers();
3820 T1Quals.removeObjCGCAttr();
3821 T1Quals.removeObjCLifetime();
3822 T2Quals.removeObjCGCAttr();
3823 T2Quals.removeObjCLifetime();
3824 if (!T1Quals.compatiblyIncludes(T2Quals))
3825 return ICS;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003826 }
3827
3828 // If at least one of the types is a class type, the types are not
3829 // related, and we aren't allowed any user conversions, the
3830 // reference binding fails. This case is important for breaking
3831 // recursion, since TryImplicitConversion below will attempt to
3832 // create a temporary through the use of a copy constructor.
3833 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3834 (T1->isRecordType() || T2->isRecordType()))
3835 return ICS;
3836
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003837 // If T1 is reference-related to T2 and the reference is an rvalue
3838 // reference, the initializer expression shall not be an lvalue.
3839 if (RefRelationship >= Sema::Ref_Related &&
3840 isRValRef && Init->Classify(S.Context).isLValue())
3841 return ICS;
3842
Douglas Gregorabe183d2010-04-13 16:31:36 +00003843 // C++ [over.ics.ref]p2:
Douglas Gregorabe183d2010-04-13 16:31:36 +00003844 // When a parameter of reference type is not bound directly to
3845 // an argument expression, the conversion sequence is the one
3846 // required to convert the argument expression to the
3847 // underlying type of the reference according to
3848 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3849 // to copy-initializing a temporary of the underlying type with
3850 // the argument expression. Any difference in top-level
3851 // cv-qualification is subsumed by the initialization itself
3852 // and does not constitute a conversion.
John McCall120d63c2010-08-24 20:38:10 +00003853 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3854 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00003855 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00003856 /*CStyle=*/false,
3857 /*AllowObjCWritebackConversion=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00003858
3859 // Of course, that's still a reference binding.
3860 if (ICS.isStandard()) {
3861 ICS.Standard.ReferenceBinding = true;
Douglas Gregor440a4832011-01-26 14:52:12 +00003862 ICS.Standard.IsLvalueReference = !isRValRef;
3863 ICS.Standard.BindsToFunctionLvalue = T2->isFunctionType();
3864 ICS.Standard.BindsToRvalue = true;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00003865 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier = false;
John McCallf85e1932011-06-15 23:02:42 +00003866 ICS.Standard.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003867 } else if (ICS.isUserDefined()) {
Douglas Gregor203050c2011-10-04 23:59:32 +00003868 // Don't allow rvalue references to bind to lvalues.
3869 if (DeclType->isRValueReferenceType()) {
3870 if (const ReferenceType *RefType
3871 = ICS.UserDefined.ConversionFunction->getResultType()
3872 ->getAs<LValueReferenceType>()) {
3873 if (!RefType->getPointeeType()->isFunctionType()) {
3874 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, Init,
3875 DeclType);
3876 return ICS;
3877 }
3878 }
3879 }
3880
Douglas Gregorabe183d2010-04-13 16:31:36 +00003881 ICS.UserDefined.After.ReferenceBinding = true;
Douglas Gregorf20d2722011-08-15 13:59:46 +00003882 ICS.UserDefined.After.IsLvalueReference = !isRValRef;
3883 ICS.UserDefined.After.BindsToFunctionLvalue = T2->isFunctionType();
3884 ICS.UserDefined.After.BindsToRvalue = true;
3885 ICS.UserDefined.After.BindsImplicitObjectArgumentWithoutRefQualifier = false;
3886 ICS.UserDefined.After.ObjCLifetimeConversionBinding = false;
Douglas Gregorabe183d2010-04-13 16:31:36 +00003887 }
Douglas Gregor2ad746a2011-01-21 05:18:22 +00003888
Douglas Gregorabe183d2010-04-13 16:31:36 +00003889 return ICS;
3890}
3891
Sebastian Redl5405b812011-10-16 18:19:34 +00003892static ImplicitConversionSequence
3893TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
3894 bool SuppressUserConversions,
3895 bool InOverloadResolution,
3896 bool AllowObjCWritebackConversion);
3897
3898/// TryListConversion - Try to copy-initialize a value of type ToType from the
3899/// initializer list From.
3900static ImplicitConversionSequence
3901TryListConversion(Sema &S, InitListExpr *From, QualType ToType,
3902 bool SuppressUserConversions,
3903 bool InOverloadResolution,
3904 bool AllowObjCWritebackConversion) {
3905 // C++11 [over.ics.list]p1:
3906 // When an argument is an initializer list, it is not an expression and
3907 // special rules apply for converting it to a parameter type.
3908
3909 ImplicitConversionSequence Result;
3910 Result.setBad(BadConversionSequence::no_conversion, From, ToType);
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003911 Result.setListInitializationSequence();
Sebastian Redl5405b812011-10-16 18:19:34 +00003912
3913 // C++11 [over.ics.list]p2:
3914 // If the parameter type is std::initializer_list<X> or "array of X" and
3915 // all the elements can be implicitly converted to X, the implicit
3916 // conversion sequence is the worst conversion necessary to convert an
3917 // element of the list to X.
3918 // FIXME: Recognize std::initializer_list.
3919 // FIXME: Arrays don't make sense until we can deal with references.
3920 if (ToType->isArrayType())
3921 return Result;
3922
3923 // C++11 [over.ics.list]p3:
3924 // Otherwise, if the parameter is a non-aggregate class X and overload
3925 // resolution chooses a single best constructor [...] the implicit
3926 // conversion sequence is a user-defined conversion sequence. If multiple
3927 // constructors are viable but none is better than the others, the
3928 // implicit conversion sequence is a user-defined conversion sequence.
3929 // FIXME: Implement this.
3930 if (ToType->isRecordType() && !ToType->isAggregateType())
3931 return Result;
3932
3933 // C++11 [over.ics.list]p4:
3934 // Otherwise, if the parameter has an aggregate type which can be
3935 // initialized from the initializer list [...] the implicit conversion
3936 // sequence is a user-defined conversion sequence.
Sebastian Redl5405b812011-10-16 18:19:34 +00003937 if (ToType->isAggregateType()) {
Sebastian Redlcc7a6482011-11-01 15:53:09 +00003938 // Type is an aggregate, argument is an init list. At this point it comes
3939 // down to checking whether the initialization works.
3940 // FIXME: Find out whether this parameter is consumed or not.
3941 InitializedEntity Entity =
3942 InitializedEntity::InitializeParameter(S.Context, ToType,
3943 /*Consumed=*/false);
3944 if (S.CanPerformCopyInitialization(Entity, S.Owned(From))) {
3945 Result.setUserDefined();
3946 Result.UserDefined.Before.setAsIdentityConversion();
3947 // Initializer lists don't have a type.
3948 Result.UserDefined.Before.setFromType(QualType());
3949 Result.UserDefined.Before.setAllToTypes(QualType());
3950
3951 Result.UserDefined.After.setAsIdentityConversion();
3952 Result.UserDefined.After.setFromType(ToType);
3953 Result.UserDefined.After.setAllToTypes(ToType);
3954 }
Sebastian Redl5405b812011-10-16 18:19:34 +00003955 return Result;
3956 }
3957
3958 // C++11 [over.ics.list]p5:
3959 // Otherwise, if the parameter is a reference, see 13.3.3.1.4.
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00003960 if (ToType->isReferenceType()) {
3961 // The standard is notoriously unclear here, since 13.3.3.1.4 doesn't
3962 // mention initializer lists in any way. So we go by what list-
3963 // initialization would do and try to extrapolate from that.
3964
3965 QualType T1 = ToType->getAs<ReferenceType>()->getPointeeType();
3966
3967 // If the initializer list has a single element that is reference-related
3968 // to the parameter type, we initialize the reference from that.
3969 if (From->getNumInits() == 1) {
3970 Expr *Init = From->getInit(0);
3971
3972 QualType T2 = Init->getType();
3973
3974 // If the initializer is the address of an overloaded function, try
3975 // to resolve the overloaded function. If all goes well, T2 is the
3976 // type of the resulting function.
3977 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
3978 DeclAccessPair Found;
3979 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(
3980 Init, ToType, false, Found))
3981 T2 = Fn->getType();
3982 }
3983
3984 // Compute some basic properties of the types and the initializer.
3985 bool dummy1 = false;
3986 bool dummy2 = false;
3987 bool dummy3 = false;
3988 Sema::ReferenceCompareResult RefRelationship
3989 = S.CompareReferenceRelationship(From->getLocStart(), T1, T2, dummy1,
3990 dummy2, dummy3);
3991
3992 if (RefRelationship >= Sema::Ref_Related)
3993 return TryReferenceInit(S, Init, ToType,
3994 /*FIXME:*/From->getLocStart(),
3995 SuppressUserConversions,
3996 /*AllowExplicit=*/false);
3997 }
3998
3999 // Otherwise, we bind the reference to a temporary created from the
4000 // initializer list.
4001 Result = TryListConversion(S, From, T1, SuppressUserConversions,
4002 InOverloadResolution,
4003 AllowObjCWritebackConversion);
4004 if (Result.isFailure())
4005 return Result;
4006 assert(!Result.isEllipsis() &&
4007 "Sub-initialization cannot result in ellipsis conversion.");
4008
4009 // Can we even bind to a temporary?
4010 if (ToType->isRValueReferenceType() ||
4011 (T1.isConstQualified() && !T1.isVolatileQualified())) {
4012 StandardConversionSequence &SCS = Result.isStandard() ? Result.Standard :
4013 Result.UserDefined.After;
4014 SCS.ReferenceBinding = true;
4015 SCS.IsLvalueReference = ToType->isLValueReferenceType();
4016 SCS.BindsToRvalue = true;
4017 SCS.BindsToFunctionLvalue = false;
4018 SCS.BindsImplicitObjectArgumentWithoutRefQualifier = false;
4019 SCS.ObjCLifetimeConversionBinding = false;
4020 } else
4021 Result.setBad(BadConversionSequence::lvalue_ref_to_rvalue,
4022 From, ToType);
Sebastian Redl5405b812011-10-16 18:19:34 +00004023 return Result;
Sebastian Redl1cdb70b2011-12-03 14:54:30 +00004024 }
Sebastian Redl5405b812011-10-16 18:19:34 +00004025
4026 // C++11 [over.ics.list]p6:
4027 // Otherwise, if the parameter type is not a class:
4028 if (!ToType->isRecordType()) {
4029 // - if the initializer list has one element, the implicit conversion
4030 // sequence is the one required to convert the element to the
4031 // parameter type.
4032 // FIXME: Catch narrowing here?
4033 unsigned NumInits = From->getNumInits();
4034 if (NumInits == 1)
4035 Result = TryCopyInitialization(S, From->getInit(0), ToType,
4036 SuppressUserConversions,
4037 InOverloadResolution,
4038 AllowObjCWritebackConversion);
4039 // - if the initializer list has no elements, the implicit conversion
4040 // sequence is the identity conversion.
4041 else if (NumInits == 0) {
4042 Result.setStandard();
4043 Result.Standard.setAsIdentityConversion();
4044 }
4045 return Result;
4046 }
4047
4048 // C++11 [over.ics.list]p7:
4049 // In all cases other than those enumerated above, no conversion is possible
4050 return Result;
4051}
4052
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004053/// TryCopyInitialization - Try to copy-initialize a value of type
4054/// ToType from the expression From. Return the implicit conversion
4055/// sequence required to pass this argument, which may be a bad
4056/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor225c41e2008-11-03 19:09:14 +00004057/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregor74e386e2010-04-16 18:00:29 +00004058/// do not permit any user-defined conversion sequences.
Douglas Gregor74eb6582010-04-16 17:51:22 +00004059static ImplicitConversionSequence
4060TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004061 bool SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004062 bool InOverloadResolution,
4063 bool AllowObjCWritebackConversion) {
Sebastian Redl5405b812011-10-16 18:19:34 +00004064 if (InitListExpr *FromInitList = dyn_cast<InitListExpr>(From))
4065 return TryListConversion(S, FromInitList, ToType, SuppressUserConversions,
4066 InOverloadResolution,AllowObjCWritebackConversion);
4067
Douglas Gregorabe183d2010-04-13 16:31:36 +00004068 if (ToType->isReferenceType())
Douglas Gregor74eb6582010-04-16 17:51:22 +00004069 return TryReferenceInit(S, From, ToType,
Douglas Gregorabe183d2010-04-13 16:31:36 +00004070 /*FIXME:*/From->getLocStart(),
4071 SuppressUserConversions,
Douglas Gregor23ef6c02010-04-16 17:45:54 +00004072 /*AllowExplicit=*/false);
Douglas Gregorabe183d2010-04-13 16:31:36 +00004073
John McCall120d63c2010-08-24 20:38:10 +00004074 return TryImplicitConversion(S, From, ToType,
4075 SuppressUserConversions,
4076 /*AllowExplicit=*/false,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004077 InOverloadResolution,
John McCallf85e1932011-06-15 23:02:42 +00004078 /*CStyle=*/false,
4079 AllowObjCWritebackConversion);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00004080}
4081
Anna Zaksf3546ee2011-07-28 19:46:48 +00004082static bool TryCopyInitialization(const CanQualType FromQTy,
4083 const CanQualType ToQTy,
4084 Sema &S,
4085 SourceLocation Loc,
4086 ExprValueKind FromVK) {
4087 OpaqueValueExpr TmpExpr(Loc, FromQTy, FromVK);
4088 ImplicitConversionSequence ICS =
4089 TryCopyInitialization(S, &TmpExpr, ToQTy, true, true, false);
4090
4091 return !ICS.isBad();
4092}
4093
Douglas Gregor96176b32008-11-18 23:14:02 +00004094/// TryObjectArgumentInitialization - Try to initialize the object
4095/// parameter of the given member function (@c Method) from the
4096/// expression @p From.
John McCall120d63c2010-08-24 20:38:10 +00004097static ImplicitConversionSequence
4098TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004099 Expr::Classification FromClassification,
John McCall120d63c2010-08-24 20:38:10 +00004100 CXXMethodDecl *Method,
4101 CXXRecordDecl *ActingContext) {
4102 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl65bdbfa2009-11-18 20:55:52 +00004103 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
4104 // const volatile object.
4105 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
4106 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall120d63c2010-08-24 20:38:10 +00004107 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor96176b32008-11-18 23:14:02 +00004108
4109 // Set up the conversion sequence as a "bad" conversion, to allow us
4110 // to exit early.
4111 ImplicitConversionSequence ICS;
Douglas Gregor96176b32008-11-18 23:14:02 +00004112
4113 // We need to have an object of class type.
John McCall651f3ee2010-01-14 03:28:57 +00004114 QualType FromType = OrigFromType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004115 if (const PointerType *PT = FromType->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004116 FromType = PT->getPointeeType();
4117
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004118 // When we had a pointer, it's implicitly dereferenced, so we
4119 // better have an lvalue.
4120 assert(FromClassification.isLValue());
4121 }
4122
Anders Carlssona552f7c2009-05-01 18:34:30 +00004123 assert(FromType->isRecordType());
Douglas Gregor96176b32008-11-18 23:14:02 +00004124
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004125 // C++0x [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004126 // For non-static member functions, the type of the implicit object
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004127 // parameter is
4128 //
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004129 // - "lvalue reference to cv X" for functions declared without a
4130 // ref-qualifier or with the & ref-qualifier
4131 // - "rvalue reference to cv X" for functions declared with the &&
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004132 // ref-qualifier
4133 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004134 // where X is the class of which the function is a member and cv is the
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004135 // cv-qualification on the member function declaration.
4136 //
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004137 // However, when finding an implicit conversion sequence for the argument, we
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004138 // are not allowed to create temporaries or perform user-defined conversions
Douglas Gregor96176b32008-11-18 23:14:02 +00004139 // (C++ [over.match.funcs]p5). We perform a simplified version of
4140 // reference binding here, that allows class rvalues to bind to
4141 // non-constant references.
4142
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004143 // First check the qualifiers.
John McCall120d63c2010-08-24 20:38:10 +00004144 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004145 if (ImplicitParamType.getCVRQualifiers()
Douglas Gregora4923eb2009-11-16 21:35:15 +00004146 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCalladbb8f82010-01-13 09:16:55 +00004147 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCallb1bdc622010-02-25 01:37:24 +00004148 ICS.setBad(BadConversionSequence::bad_qualifiers,
4149 OrigFromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004150 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004151 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004152
4153 // Check that we have either the same type or a derived type. It
4154 // affects the conversion rank.
John McCall120d63c2010-08-24 20:38:10 +00004155 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCallb1bdc622010-02-25 01:37:24 +00004156 ImplicitConversionKind SecondKind;
4157 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
4158 SecondKind = ICK_Identity;
John McCall120d63c2010-08-24 20:38:10 +00004159 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCallb1bdc622010-02-25 01:37:24 +00004160 SecondKind = ICK_Derived_To_Base;
John McCalladbb8f82010-01-13 09:16:55 +00004161 else {
John McCallb1bdc622010-02-25 01:37:24 +00004162 ICS.setBad(BadConversionSequence::unrelated_class,
4163 FromType, ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004164 return ICS;
John McCalladbb8f82010-01-13 09:16:55 +00004165 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004166
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004167 // Check the ref-qualifier.
4168 switch (Method->getRefQualifier()) {
4169 case RQ_None:
4170 // Do nothing; we don't care about lvalueness or rvalueness.
4171 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004172
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004173 case RQ_LValue:
4174 if (!FromClassification.isLValue() && Quals != Qualifiers::Const) {
4175 // non-const lvalue reference cannot bind to an rvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004176 ICS.setBad(BadConversionSequence::lvalue_ref_to_rvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004177 ImplicitParamType);
4178 return ICS;
4179 }
4180 break;
4181
4182 case RQ_RValue:
4183 if (!FromClassification.isRValue()) {
4184 // rvalue reference cannot bind to an lvalue
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004185 ICS.setBad(BadConversionSequence::rvalue_ref_to_lvalue, FromType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004186 ImplicitParamType);
4187 return ICS;
4188 }
4189 break;
4190 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004191
Douglas Gregor96176b32008-11-18 23:14:02 +00004192 // Success. Mark this as a reference binding.
John McCall1d318332010-01-12 00:44:57 +00004193 ICS.setStandard();
John McCallb1bdc622010-02-25 01:37:24 +00004194 ICS.Standard.setAsIdentityConversion();
4195 ICS.Standard.Second = SecondKind;
John McCall1d318332010-01-12 00:44:57 +00004196 ICS.Standard.setFromType(FromType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004197 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor96176b32008-11-18 23:14:02 +00004198 ICS.Standard.ReferenceBinding = true;
4199 ICS.Standard.DirectBinding = true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004200 ICS.Standard.IsLvalueReference = Method->getRefQualifier() != RQ_RValue;
Douglas Gregor440a4832011-01-26 14:52:12 +00004201 ICS.Standard.BindsToFunctionLvalue = false;
Douglas Gregorfcab48b2011-01-26 19:41:18 +00004202 ICS.Standard.BindsToRvalue = FromClassification.isRValue();
4203 ICS.Standard.BindsImplicitObjectArgumentWithoutRefQualifier
4204 = (Method->getRefQualifier() == RQ_None);
Douglas Gregor96176b32008-11-18 23:14:02 +00004205 return ICS;
4206}
4207
4208/// PerformObjectArgumentInitialization - Perform initialization of
4209/// the implicit object parameter for the given Method with the given
4210/// expression.
John Wiegley429bb272011-04-08 18:41:53 +00004211ExprResult
4212Sema::PerformObjectArgumentInitialization(Expr *From,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004213 NestedNameSpecifier *Qualifier,
John McCall6bb80172010-03-30 21:47:33 +00004214 NamedDecl *FoundDecl,
Douglas Gregor5fccd362010-03-03 23:55:11 +00004215 CXXMethodDecl *Method) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004216 QualType FromRecordType, DestType;
Mike Stump1eb44332009-09-09 15:08:12 +00004217 QualType ImplicitParamRecordType =
Ted Kremenek6217b802009-07-29 21:53:49 +00004218 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump1eb44332009-09-09 15:08:12 +00004219
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004220 Expr::Classification FromClassification;
Ted Kremenek6217b802009-07-29 21:53:49 +00004221 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssona552f7c2009-05-01 18:34:30 +00004222 FromRecordType = PT->getPointeeType();
4223 DestType = Method->getThisType(Context);
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004224 FromClassification = Expr::Classification::makeSimpleLValue();
Anders Carlssona552f7c2009-05-01 18:34:30 +00004225 } else {
4226 FromRecordType = From->getType();
4227 DestType = ImplicitParamRecordType;
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004228 FromClassification = From->Classify(Context);
Anders Carlssona552f7c2009-05-01 18:34:30 +00004229 }
4230
John McCall701c89e2009-12-03 04:06:58 +00004231 // Note that we always use the true parent context when performing
4232 // the actual argument initialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004233 ImplicitConversionSequence ICS
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004234 = TryObjectArgumentInitialization(*this, From->getType(), FromClassification,
4235 Method, Method->getParent());
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004236 if (ICS.isBad()) {
4237 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
4238 Qualifiers FromQs = FromRecordType.getQualifiers();
4239 Qualifiers ToQs = DestType.getQualifiers();
4240 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
4241 if (CVR) {
4242 Diag(From->getSourceRange().getBegin(),
4243 diag::err_member_function_call_bad_cvr)
4244 << Method->getDeclName() << FromRecordType << (CVR - 1)
4245 << From->getSourceRange();
4246 Diag(Method->getLocation(), diag::note_previous_decl)
4247 << Method->getDeclName();
John Wiegley429bb272011-04-08 18:41:53 +00004248 return ExprError();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004249 }
4250 }
4251
Douglas Gregor96176b32008-11-18 23:14:02 +00004252 return Diag(From->getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00004253 diag::err_implicit_object_parameter_init)
Anders Carlssona552f7c2009-05-01 18:34:30 +00004254 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis64ccf242010-11-16 08:04:45 +00004255 }
Mike Stump1eb44332009-09-09 15:08:12 +00004256
John Wiegley429bb272011-04-08 18:41:53 +00004257 if (ICS.Standard.Second == ICK_Derived_To_Base) {
4258 ExprResult FromRes =
4259 PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
4260 if (FromRes.isInvalid())
4261 return ExprError();
4262 From = FromRes.take();
4263 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004264
Douglas Gregor5fccd362010-03-03 23:55:11 +00004265 if (!Context.hasSameType(From->getType(), DestType))
John Wiegley429bb272011-04-08 18:41:53 +00004266 From = ImpCastExprToType(From, DestType, CK_NoOp,
Richard Smithacdfa4d2011-11-10 23:32:36 +00004267 From->getValueKind()).take();
John Wiegley429bb272011-04-08 18:41:53 +00004268 return Owned(From);
Douglas Gregor96176b32008-11-18 23:14:02 +00004269}
4270
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004271/// TryContextuallyConvertToBool - Attempt to contextually convert the
4272/// expression From to bool (C++0x [conv]p3).
John McCall120d63c2010-08-24 20:38:10 +00004273static ImplicitConversionSequence
4274TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregorc6dfe192010-05-08 22:41:50 +00004275 // FIXME: This is pretty broken.
John McCall120d63c2010-08-24 20:38:10 +00004276 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonda7a18b2009-08-27 17:24:15 +00004277 // FIXME: Are these flags correct?
4278 /*SuppressUserConversions=*/false,
Mike Stump1eb44332009-09-09 15:08:12 +00004279 /*AllowExplicit=*/true,
Douglas Gregor14d0aee2011-01-27 00:58:17 +00004280 /*InOverloadResolution=*/false,
John McCallf85e1932011-06-15 23:02:42 +00004281 /*CStyle=*/false,
4282 /*AllowObjCWritebackConversion=*/false);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004283}
4284
4285/// PerformContextuallyConvertToBool - Perform a contextual conversion
4286/// of the expression From to bool (C++0x [conv]p3).
John Wiegley429bb272011-04-08 18:41:53 +00004287ExprResult Sema::PerformContextuallyConvertToBool(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004288 if (checkPlaceholderForOverload(*this, From))
4289 return ExprError();
4290
John McCall120d63c2010-08-24 20:38:10 +00004291 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall1d318332010-01-12 00:44:57 +00004292 if (!ICS.isBad())
4293 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004294
Fariborz Jahaniancc5306a2009-11-18 18:26:29 +00004295 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
John McCall864c0412011-04-26 20:42:42 +00004296 return Diag(From->getSourceRange().getBegin(),
4297 diag::err_typecheck_bool_condition)
Fariborz Jahanian17c7a5d2009-09-22 20:24:30 +00004298 << From->getType() << From->getSourceRange();
John Wiegley429bb272011-04-08 18:41:53 +00004299 return ExprError();
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004300}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004301
John McCall0bcc9bc2011-09-09 06:11:02 +00004302/// dropPointerConversions - If the given standard conversion sequence
4303/// involves any pointer conversions, remove them. This may change
4304/// the result type of the conversion sequence.
4305static void dropPointerConversion(StandardConversionSequence &SCS) {
4306 if (SCS.Second == ICK_Pointer_Conversion) {
4307 SCS.Second = ICK_Identity;
4308 SCS.Third = ICK_Identity;
4309 SCS.ToTypePtrs[2] = SCS.ToTypePtrs[1] = SCS.ToTypePtrs[0];
4310 }
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004311}
John McCall120d63c2010-08-24 20:38:10 +00004312
John McCall0bcc9bc2011-09-09 06:11:02 +00004313/// TryContextuallyConvertToObjCPointer - Attempt to contextually
4314/// convert the expression From to an Objective-C pointer type.
4315static ImplicitConversionSequence
4316TryContextuallyConvertToObjCPointer(Sema &S, Expr *From) {
4317 // Do an implicit conversion to 'id'.
4318 QualType Ty = S.Context.getObjCIdType();
4319 ImplicitConversionSequence ICS
4320 = TryImplicitConversion(S, From, Ty,
4321 // FIXME: Are these flags correct?
4322 /*SuppressUserConversions=*/false,
4323 /*AllowExplicit=*/true,
4324 /*InOverloadResolution=*/false,
4325 /*CStyle=*/false,
4326 /*AllowObjCWritebackConversion=*/false);
4327
4328 // Strip off any final conversions to 'id'.
4329 switch (ICS.getKind()) {
4330 case ImplicitConversionSequence::BadConversion:
4331 case ImplicitConversionSequence::AmbiguousConversion:
4332 case ImplicitConversionSequence::EllipsisConversion:
4333 break;
4334
4335 case ImplicitConversionSequence::UserDefinedConversion:
4336 dropPointerConversion(ICS.UserDefined.After);
4337 break;
4338
4339 case ImplicitConversionSequence::StandardConversion:
4340 dropPointerConversion(ICS.Standard);
4341 break;
4342 }
4343
4344 return ICS;
4345}
4346
4347/// PerformContextuallyConvertToObjCPointer - Perform a contextual
4348/// conversion of the expression From to an Objective-C pointer type.
4349ExprResult Sema::PerformContextuallyConvertToObjCPointer(Expr *From) {
John McCall3c3b7f92011-10-25 17:37:35 +00004350 if (checkPlaceholderForOverload(*this, From))
4351 return ExprError();
4352
John McCallc12c5bb2010-05-15 11:32:37 +00004353 QualType Ty = Context.getObjCIdType();
John McCall0bcc9bc2011-09-09 06:11:02 +00004354 ImplicitConversionSequence ICS =
4355 TryContextuallyConvertToObjCPointer(*this, From);
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004356 if (!ICS.isBad())
4357 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
John Wiegley429bb272011-04-08 18:41:53 +00004358 return ExprError();
Fariborz Jahanian79d3f042010-05-12 23:29:11 +00004359}
Douglas Gregor09f41cf2009-01-14 15:45:31 +00004360
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004361/// \brief Attempt to convert the given expression to an integral or
Douglas Gregorc30614b2010-06-29 23:17:37 +00004362/// enumeration type.
4363///
4364/// This routine will attempt to convert an expression of class type to an
4365/// integral or enumeration type, if that class type only has a single
4366/// conversion to an integral or enumeration type.
4367///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004368/// \param Loc The source location of the construct that requires the
4369/// conversion.
Douglas Gregorc30614b2010-06-29 23:17:37 +00004370///
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004371/// \param FromE The expression we're converting from.
4372///
4373/// \param NotIntDiag The diagnostic to be emitted if the expression does not
4374/// have integral or enumeration type.
4375///
4376/// \param IncompleteDiag The diagnostic to be emitted if the expression has
4377/// incomplete class type.
4378///
4379/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
4380/// explicit conversion function (because no implicit conversion functions
4381/// were available). This is a recovery mode.
4382///
4383/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
4384/// showing which conversion was picked.
4385///
4386/// \param AmbigDiag The diagnostic to be emitted if there is more than one
4387/// conversion function that could convert to integral or enumeration type.
4388///
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004389/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004390/// usable conversion function.
4391///
4392/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
4393/// function, which may be an extension in this case.
4394///
4395/// \returns The expression, converted to an integral or enumeration type if
4396/// successful.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004397ExprResult
John McCall9ae2f072010-08-23 23:25:46 +00004398Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorc30614b2010-06-29 23:17:37 +00004399 const PartialDiagnostic &NotIntDiag,
4400 const PartialDiagnostic &IncompleteDiag,
4401 const PartialDiagnostic &ExplicitConvDiag,
4402 const PartialDiagnostic &ExplicitConvNote,
4403 const PartialDiagnostic &AmbigDiag,
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004404 const PartialDiagnostic &AmbigNote,
4405 const PartialDiagnostic &ConvDiag) {
Douglas Gregorc30614b2010-06-29 23:17:37 +00004406 // We can't perform any more checking for type-dependent expressions.
4407 if (From->isTypeDependent())
John McCall9ae2f072010-08-23 23:25:46 +00004408 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004409
Douglas Gregorc30614b2010-06-29 23:17:37 +00004410 // If the expression already has integral or enumeration type, we're golden.
4411 QualType T = From->getType();
4412 if (T->isIntegralOrEnumerationType())
John McCall9ae2f072010-08-23 23:25:46 +00004413 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004414
4415 // FIXME: Check for missing '()' if T is a function type?
4416
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004417 // 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 +00004418 // expression of integral or enumeration type.
4419 const RecordType *RecordTy = T->getAs<RecordType>();
4420 if (!RecordTy || !getLangOptions().CPlusPlus) {
4421 Diag(Loc, NotIntDiag)
4422 << T << From->getSourceRange();
John McCall9ae2f072010-08-23 23:25:46 +00004423 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004424 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004425
Douglas Gregorc30614b2010-06-29 23:17:37 +00004426 // We must have a complete class type.
4427 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCall9ae2f072010-08-23 23:25:46 +00004428 return Owned(From);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004429
Douglas Gregorc30614b2010-06-29 23:17:37 +00004430 // Look for a conversion to an integral or enumeration type.
4431 UnresolvedSet<4> ViableConversions;
4432 UnresolvedSet<4> ExplicitConversions;
4433 const UnresolvedSetImpl *Conversions
4434 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004435
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004436 bool HadMultipleCandidates = (Conversions->size() > 1);
4437
Douglas Gregorc30614b2010-06-29 23:17:37 +00004438 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004439 E = Conversions->end();
4440 I != E;
Douglas Gregorc30614b2010-06-29 23:17:37 +00004441 ++I) {
4442 if (CXXConversionDecl *Conversion
4443 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
4444 if (Conversion->getConversionType().getNonReferenceType()
4445 ->isIntegralOrEnumerationType()) {
4446 if (Conversion->isExplicit())
4447 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
4448 else
4449 ViableConversions.addDecl(I.getDecl(), I.getAccess());
4450 }
4451 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004452
Douglas Gregorc30614b2010-06-29 23:17:37 +00004453 switch (ViableConversions.size()) {
4454 case 0:
4455 if (ExplicitConversions.size() == 1) {
4456 DeclAccessPair Found = ExplicitConversions[0];
4457 CXXConversionDecl *Conversion
4458 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004459
Douglas Gregorc30614b2010-06-29 23:17:37 +00004460 // The user probably meant to invoke the given explicit
4461 // conversion; use it.
4462 QualType ConvTy
4463 = Conversion->getConversionType().getNonReferenceType();
4464 std::string TypeStr;
Douglas Gregor8987b232011-09-27 23:30:47 +00004465 ConvTy.getAsStringInternal(TypeStr, getPrintingPolicy());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004466
Douglas Gregorc30614b2010-06-29 23:17:37 +00004467 Diag(Loc, ExplicitConvDiag)
4468 << T << ConvTy
4469 << FixItHint::CreateInsertion(From->getLocStart(),
4470 "static_cast<" + TypeStr + ">(")
4471 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
4472 ")");
4473 Diag(Conversion->getLocation(), ExplicitConvNote)
4474 << ConvTy->isEnumeralType() << ConvTy;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004475
4476 // If we aren't in a SFINAE context, build a call to the
Douglas Gregorc30614b2010-06-29 23:17:37 +00004477 // explicit conversion function.
4478 if (isSFINAEContext())
4479 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004480
Douglas Gregorc30614b2010-06-29 23:17:37 +00004481 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004482 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4483 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004484 if (Result.isInvalid())
4485 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00004486 // Record usage of conversion in an implicit cast.
4487 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4488 CK_UserDefinedConversion,
4489 Result.get(), 0,
4490 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00004491 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004492
Douglas Gregorc30614b2010-06-29 23:17:37 +00004493 // We'll complain below about a non-integral condition type.
4494 break;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004495
Douglas Gregorc30614b2010-06-29 23:17:37 +00004496 case 1: {
4497 // Apply this conversion.
4498 DeclAccessPair Found = ViableConversions[0];
4499 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004500
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004501 CXXConversionDecl *Conversion
4502 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
4503 QualType ConvTy
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004504 = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004505 if (ConvDiag.getDiagID()) {
4506 if (isSFINAEContext())
4507 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004508
Douglas Gregor6bc574d2010-06-30 00:20:43 +00004509 Diag(Loc, ConvDiag)
4510 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
4511 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004512
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00004513 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion,
4514 HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00004515 if (Result.isInvalid())
4516 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +00004517 // Record usage of conversion in an implicit cast.
4518 From = ImplicitCastExpr::Create(Context, Result.get()->getType(),
4519 CK_UserDefinedConversion,
4520 Result.get(), 0,
4521 Result.get()->getValueKind());
Douglas Gregorc30614b2010-06-29 23:17:37 +00004522 break;
4523 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004524
Douglas Gregorc30614b2010-06-29 23:17:37 +00004525 default:
4526 Diag(Loc, AmbigDiag)
4527 << T << From->getSourceRange();
4528 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
4529 CXXConversionDecl *Conv
4530 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
4531 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
4532 Diag(Conv->getLocation(), AmbigNote)
4533 << ConvTy->isEnumeralType() << ConvTy;
4534 }
John McCall9ae2f072010-08-23 23:25:46 +00004535 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004536 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004537
Douglas Gregoracb0bd82010-06-29 23:25:20 +00004538 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorc30614b2010-06-29 23:17:37 +00004539 Diag(Loc, NotIntDiag)
4540 << From->getType() << From->getSourceRange();
Douglas Gregorc30614b2010-06-29 23:17:37 +00004541
John McCall9ae2f072010-08-23 23:25:46 +00004542 return Owned(From);
Douglas Gregorc30614b2010-06-29 23:17:37 +00004543}
4544
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004545/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor225c41e2008-11-03 19:09:14 +00004546/// candidate functions, using the given function call arguments. If
4547/// @p SuppressUserConversions, then don't allow user-defined
4548/// conversions via constructors or conversion operators.
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004549///
4550/// \para PartialOverloading true if we are performing "partial" overloading
4551/// based on an incomplete set of function arguments. This feature is used by
4552/// code completion.
Mike Stump1eb44332009-09-09 15:08:12 +00004553void
4554Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCall9aa472c2010-03-19 07:35:19 +00004555 DeclAccessPair FoundDecl,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004556 Expr **Args, unsigned NumArgs,
Douglas Gregor225c41e2008-11-03 19:09:14 +00004557 OverloadCandidateSet& CandidateSet,
Sebastian Redle2b68332009-04-12 17:16:29 +00004558 bool SuppressUserConversions,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004559 bool PartialOverloading) {
Mike Stump1eb44332009-09-09 15:08:12 +00004560 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00004561 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004562 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump1eb44332009-09-09 15:08:12 +00004563 assert(!Function->getDescribedFunctionTemplate() &&
NAKAMURA Takumi00995302011-01-27 07:09:49 +00004564 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump1eb44332009-09-09 15:08:12 +00004565
Douglas Gregor88a35142008-12-22 05:46:06 +00004566 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004567 if (!isa<CXXConstructorDecl>(Method)) {
4568 // If we get here, it's because we're calling a member function
4569 // that is named without a member access expression (e.g.,
4570 // "this->f") that was either written explicitly or created
4571 // implicitly. This can happen with a qualified call to a member
John McCall701c89e2009-12-03 04:06:58 +00004572 // function, e.g., X::f(). We use an empty type for the implied
4573 // object argument (C++ [over.call.func]p3), and the acting context
4574 // is irrelevant.
John McCall9aa472c2010-03-19 07:35:19 +00004575 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004576 QualType(), Expr::Classification::makeSimpleLValue(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004577 Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004578 SuppressUserConversions);
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004579 return;
4580 }
4581 // We treat a constructor like a non-member function, since its object
4582 // argument doesn't participate in overload resolution.
Douglas Gregor88a35142008-12-22 05:46:06 +00004583 }
4584
Douglas Gregorfd476482009-11-13 23:59:09 +00004585 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor3f396022009-09-28 04:47:19 +00004586 return;
Douglas Gregor66724ea2009-11-14 01:20:54 +00004587
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 Gregor66724ea2009-11-14 01:20:54 +00004591 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
4592 // C++ [class.copy]p3:
4593 // A member function template is never instantiated to perform the copy
4594 // of a class object to an object of its class type.
4595 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004596 if (NumArgs == 1 &&
Douglas Gregor6493cc52010-11-08 17:16:59 +00004597 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor12116062010-02-21 18:30:38 +00004598 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
4599 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregor66724ea2009-11-14 01:20:54 +00004600 return;
4601 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004602
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004603 // Add this candidate
4604 CandidateSet.push_back(OverloadCandidate());
4605 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004606 Candidate.FoundDecl = FoundDecl;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004607 Candidate.Function = Function;
Douglas Gregor88a35142008-12-22 05:46:06 +00004608 Candidate.Viable = true;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004609 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004610 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004611 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004612
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004613 unsigned NumArgsInProto = Proto->getNumArgs();
4614
4615 // (C++ 13.3.2p2): A candidate function having fewer than m
4616 // parameters is viable only if it has an ellipsis in its parameter
4617 // list (8.3.5).
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004618 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
Douglas Gregor5bd1a112009-09-23 14:56:09 +00004619 !Proto->isVariadic()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004620 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004621 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004622 return;
4623 }
4624
4625 // (C++ 13.3.2p2): A candidate function having more than m parameters
4626 // is viable only if the (m+1)st parameter has a default argument
4627 // (8.3.6). For the purposes of overload resolution, the
4628 // parameter list is truncated on the right, so that there are
4629 // exactly m parameters.
4630 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00004631 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004632 // Not enough arguments.
4633 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004634 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004635 return;
4636 }
4637
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00004638 // (CUDA B.1): Check for invalid calls between targets.
4639 if (getLangOptions().CUDA)
4640 if (const FunctionDecl *Caller = dyn_cast<FunctionDecl>(CurContext))
4641 if (CheckCUDATarget(Caller, Function)) {
4642 Candidate.Viable = false;
4643 Candidate.FailureKind = ovl_fail_bad_target;
4644 return;
4645 }
4646
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004647 // Determine the implicit conversion sequences for each of the
4648 // arguments.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004649 Candidate.Conversions.resize(NumArgs);
4650 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4651 if (ArgIdx < NumArgsInProto) {
4652 // (C++ 13.3.2p3): for F to be a viable function, there shall
4653 // exist for each argument an implicit conversion sequence
4654 // (13.3.3.1) that converts that argument to the corresponding
4655 // parameter of F.
4656 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004657 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004658 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004659 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004660 /*InOverloadResolution=*/true,
4661 /*AllowObjCWritebackConversion=*/
4662 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00004663 if (Candidate.Conversions[ArgIdx].isBad()) {
4664 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004665 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall1d318332010-01-12 00:44:57 +00004666 break;
Douglas Gregor96176b32008-11-18 23:14:02 +00004667 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004668 } else {
4669 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4670 // argument for which there is no corresponding parameter is
4671 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004672 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00004673 }
4674 }
4675}
4676
Douglas Gregor063daf62009-03-13 18:40:31 +00004677/// \brief Add all of the function declarations in the given function set to
4678/// the overload canddiate set.
John McCall6e266892010-01-26 03:27:55 +00004679void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00004680 Expr **Args, unsigned NumArgs,
4681 OverloadCandidateSet& CandidateSet,
4682 bool SuppressUserConversions) {
John McCall6e266892010-01-26 03:27:55 +00004683 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCall9aa472c2010-03-19 07:35:19 +00004684 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
4685 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004686 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00004687 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00004688 cast<CXXMethodDecl>(FD)->getParent(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004689 Args[0]->getType(), Args[0]->Classify(Context),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004690 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00004691 CandidateSet, SuppressUserConversions);
4692 else
John McCall9aa472c2010-03-19 07:35:19 +00004693 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor3f396022009-09-28 04:47:19 +00004694 SuppressUserConversions);
4695 } else {
John McCall9aa472c2010-03-19 07:35:19 +00004696 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor3f396022009-09-28 04:47:19 +00004697 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
4698 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCall9aa472c2010-03-19 07:35:19 +00004699 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall701c89e2009-12-03 04:06:58 +00004700 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCalld5532b62009-11-23 01:53:49 +00004701 /*FIXME: explicit args */ 0,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004702 Args[0]->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004703 Args[0]->Classify(Context),
4704 Args + 1, NumArgs - 1,
Douglas Gregor3f396022009-09-28 04:47:19 +00004705 CandidateSet,
Douglas Gregor364e0212009-06-27 21:05:07 +00004706 SuppressUserConversions);
Douglas Gregor3f396022009-09-28 04:47:19 +00004707 else
John McCall9aa472c2010-03-19 07:35:19 +00004708 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCalld5532b62009-11-23 01:53:49 +00004709 /*FIXME: explicit args */ 0,
Douglas Gregor3f396022009-09-28 04:47:19 +00004710 Args, NumArgs, CandidateSet,
4711 SuppressUserConversions);
4712 }
Douglas Gregor364e0212009-06-27 21:05:07 +00004713 }
Douglas Gregor063daf62009-03-13 18:40:31 +00004714}
4715
John McCall314be4e2009-11-17 07:50:12 +00004716/// AddMethodCandidate - Adds a named decl (which is some kind of
4717/// method) as a method candidate to the given overload set.
John McCall9aa472c2010-03-19 07:35:19 +00004718void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004719 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004720 Expr::Classification ObjectClassification,
John McCall314be4e2009-11-17 07:50:12 +00004721 Expr **Args, unsigned NumArgs,
4722 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004723 bool SuppressUserConversions) {
John McCall9aa472c2010-03-19 07:35:19 +00004724 NamedDecl *Decl = FoundDecl.getDecl();
John McCall701c89e2009-12-03 04:06:58 +00004725 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCall314be4e2009-11-17 07:50:12 +00004726
4727 if (isa<UsingShadowDecl>(Decl))
4728 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004729
John McCall314be4e2009-11-17 07:50:12 +00004730 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
4731 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
4732 "Expected a member function template");
John McCall9aa472c2010-03-19 07:35:19 +00004733 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
4734 /*ExplicitArgs*/ 0,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004735 ObjectType, ObjectClassification, Args, NumArgs,
John McCall314be4e2009-11-17 07:50:12 +00004736 CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004737 SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00004738 } else {
John McCall9aa472c2010-03-19 07:35:19 +00004739 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004740 ObjectType, ObjectClassification, Args, NumArgs,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004741 CandidateSet, SuppressUserConversions);
John McCall314be4e2009-11-17 07:50:12 +00004742 }
4743}
4744
Douglas Gregor96176b32008-11-18 23:14:02 +00004745/// AddMethodCandidate - Adds the given C++ member function to the set
4746/// of candidate functions, using the given function call arguments
4747/// and the object argument (@c Object). For example, in a call
4748/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
4749/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
4750/// allow user-defined conversions via constructors or conversion
Douglas Gregor7ec77522010-04-16 17:33:27 +00004751/// operators.
Mike Stump1eb44332009-09-09 15:08:12 +00004752void
John McCall9aa472c2010-03-19 07:35:19 +00004753Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCall86820f52010-01-26 01:37:31 +00004754 CXXRecordDecl *ActingContext, QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004755 Expr::Classification ObjectClassification,
John McCall86820f52010-01-26 01:37:31 +00004756 Expr **Args, unsigned NumArgs,
Douglas Gregor96176b32008-11-18 23:14:02 +00004757 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004758 bool SuppressUserConversions) {
Mike Stump1eb44332009-09-09 15:08:12 +00004759 const FunctionProtoType* Proto
John McCall183700f2009-09-21 23:43:11 +00004760 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor96176b32008-11-18 23:14:02 +00004761 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl3201f6b2009-04-16 17:51:27 +00004762 assert(!isa<CXXConstructorDecl>(Method) &&
4763 "Use AddOverloadCandidate for constructors");
Douglas Gregor96176b32008-11-18 23:14:02 +00004764
Douglas Gregor3f396022009-09-28 04:47:19 +00004765 if (!CandidateSet.isNewCandidate(Method))
4766 return;
4767
Douglas Gregor7edfb692009-11-23 12:27:39 +00004768 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004769 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004770
Douglas Gregor96176b32008-11-18 23:14:02 +00004771 // Add this candidate
4772 CandidateSet.push_back(OverloadCandidate());
4773 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004774 Candidate.FoundDecl = FoundDecl;
Douglas Gregor96176b32008-11-18 23:14:02 +00004775 Candidate.Function = Method;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004776 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004777 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004778 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor96176b32008-11-18 23:14:02 +00004779
4780 unsigned NumArgsInProto = Proto->getNumArgs();
4781
4782 // (C++ 13.3.2p2): A candidate function having fewer than m
4783 // parameters is viable only if it has an ellipsis in its parameter
4784 // list (8.3.5).
4785 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4786 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004787 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00004788 return;
4789 }
4790
4791 // (C++ 13.3.2p2): A candidate function having more than m parameters
4792 // is viable only if the (m+1)st parameter has a default argument
4793 // (8.3.6). For the purposes of overload resolution, the
4794 // parameter list is truncated on the right, so that there are
4795 // exactly m parameters.
4796 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
4797 if (NumArgs < MinRequiredArgs) {
4798 // Not enough arguments.
4799 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004800 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor96176b32008-11-18 23:14:02 +00004801 return;
4802 }
4803
4804 Candidate.Viable = true;
4805 Candidate.Conversions.resize(NumArgs + 1);
4806
John McCall701c89e2009-12-03 04:06:58 +00004807 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor88a35142008-12-22 05:46:06 +00004808 // The implicit object argument is ignored.
4809 Candidate.IgnoreObjectArgument = true;
4810 else {
4811 // Determine the implicit conversion sequence for the object
4812 // parameter.
John McCall701c89e2009-12-03 04:06:58 +00004813 Candidate.Conversions[0]
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004814 = TryObjectArgumentInitialization(*this, ObjectType, ObjectClassification,
4815 Method, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00004816 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor88a35142008-12-22 05:46:06 +00004817 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004818 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor88a35142008-12-22 05:46:06 +00004819 return;
4820 }
Douglas Gregor96176b32008-11-18 23:14:02 +00004821 }
4822
4823 // Determine the implicit conversion sequences for each of the
4824 // arguments.
4825 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4826 if (ArgIdx < NumArgsInProto) {
4827 // (C++ 13.3.2p3): for F to be a viable function, there shall
4828 // exist for each argument an implicit conversion sequence
4829 // (13.3.3.1) that converts that argument to the corresponding
4830 // parameter of F.
4831 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00004832 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00004833 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004834 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00004835 /*InOverloadResolution=*/true,
4836 /*AllowObjCWritebackConversion=*/
4837 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00004838 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor96176b32008-11-18 23:14:02 +00004839 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004840 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00004841 break;
4842 }
4843 } else {
4844 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4845 // argument for which there is no corresponding parameter is
4846 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00004847 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor96176b32008-11-18 23:14:02 +00004848 }
4849 }
4850}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004851
Douglas Gregor6b906862009-08-21 00:16:32 +00004852/// \brief Add a C++ member function template as a candidate to the candidate
4853/// set, using template argument deduction to produce an appropriate member
4854/// function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004855void
Douglas Gregor6b906862009-08-21 00:16:32 +00004856Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCall9aa472c2010-03-19 07:35:19 +00004857 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004858 CXXRecordDecl *ActingContext,
Douglas Gregor67714232011-03-03 02:41:12 +00004859 TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall701c89e2009-12-03 04:06:58 +00004860 QualType ObjectType,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004861 Expr::Classification ObjectClassification,
John McCall701c89e2009-12-03 04:06:58 +00004862 Expr **Args, unsigned NumArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00004863 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004864 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004865 if (!CandidateSet.isNewCandidate(MethodTmpl))
4866 return;
4867
Douglas Gregor6b906862009-08-21 00:16:32 +00004868 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00004869 // In each case where a candidate is a function template, candidate
Douglas Gregor6b906862009-08-21 00:16:32 +00004870 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00004871 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor6b906862009-08-21 00:16:32 +00004872 // candidate functions in the usual way.113) A given name can refer to one
4873 // or more function templates and also to a set of overloaded non-template
4874 // functions. In such a case, the candidate functions generated from each
4875 // function template are combined with the set of non-template candidate
4876 // functions.
John McCall5769d612010-02-08 23:07:23 +00004877 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor6b906862009-08-21 00:16:32 +00004878 FunctionDecl *Specialization = 0;
4879 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004880 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor6b906862009-08-21 00:16:32 +00004881 Args, NumArgs, Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00004882 CandidateSet.push_back(OverloadCandidate());
4883 OverloadCandidate &Candidate = CandidateSet.back();
4884 Candidate.FoundDecl = FoundDecl;
4885 Candidate.Function = MethodTmpl->getTemplatedDecl();
4886 Candidate.Viable = false;
4887 Candidate.FailureKind = ovl_fail_bad_deduction;
4888 Candidate.IsSurrogate = false;
4889 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004890 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004891 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004892 Info);
4893 return;
4894 }
Mike Stump1eb44332009-09-09 15:08:12 +00004895
Douglas Gregor6b906862009-08-21 00:16:32 +00004896 // Add the function template specialization produced by template argument
4897 // deduction as a candidate.
4898 assert(Specialization && "Missing member function template specialization?");
Mike Stump1eb44332009-09-09 15:08:12 +00004899 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor6b906862009-08-21 00:16:32 +00004900 "Specialization is not a member function?");
John McCall9aa472c2010-03-19 07:35:19 +00004901 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00004902 ActingContext, ObjectType, ObjectClassification,
4903 Args, NumArgs, CandidateSet, SuppressUserConversions);
Douglas Gregor6b906862009-08-21 00:16:32 +00004904}
4905
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004906/// \brief Add a C++ function template specialization as a candidate
4907/// in the candidate set, using template argument deduction to produce
4908/// an appropriate function template specialization.
Mike Stump1eb44332009-09-09 15:08:12 +00004909void
Douglas Gregore53060f2009-06-25 22:08:12 +00004910Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00004911 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00004912 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregore53060f2009-06-25 22:08:12 +00004913 Expr **Args, unsigned NumArgs,
4914 OverloadCandidateSet& CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004915 bool SuppressUserConversions) {
Douglas Gregor3f396022009-09-28 04:47:19 +00004916 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4917 return;
4918
Douglas Gregore53060f2009-06-25 22:08:12 +00004919 // C++ [over.match.funcs]p7:
Mike Stump1eb44332009-09-09 15:08:12 +00004920 // In each case where a candidate is a function template, candidate
Douglas Gregore53060f2009-06-25 22:08:12 +00004921 // function template specializations are generated using template argument
Mike Stump1eb44332009-09-09 15:08:12 +00004922 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregore53060f2009-06-25 22:08:12 +00004923 // candidate functions in the usual way.113) A given name can refer to one
4924 // or more function templates and also to a set of overloaded non-template
4925 // functions. In such a case, the candidate functions generated from each
4926 // function template are combined with the set of non-template candidate
4927 // functions.
John McCall5769d612010-02-08 23:07:23 +00004928 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregore53060f2009-06-25 22:08:12 +00004929 FunctionDecl *Specialization = 0;
4930 if (TemplateDeductionResult Result
John McCalld5532b62009-11-23 01:53:49 +00004931 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00004932 Args, NumArgs, Specialization, Info)) {
John McCall578b69b2009-12-16 08:11:27 +00004933 CandidateSet.push_back(OverloadCandidate());
4934 OverloadCandidate &Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004935 Candidate.FoundDecl = FoundDecl;
John McCall578b69b2009-12-16 08:11:27 +00004936 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4937 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00004938 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCall578b69b2009-12-16 08:11:27 +00004939 Candidate.IsSurrogate = false;
4940 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00004941 Candidate.ExplicitCallArguments = NumArgs;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004942 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00004943 Info);
Douglas Gregore53060f2009-06-25 22:08:12 +00004944 return;
4945 }
Mike Stump1eb44332009-09-09 15:08:12 +00004946
Douglas Gregore53060f2009-06-25 22:08:12 +00004947 // Add the function template specialization produced by template argument
4948 // deduction as a candidate.
4949 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00004950 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregor7ec77522010-04-16 17:33:27 +00004951 SuppressUserConversions);
Douglas Gregore53060f2009-06-25 22:08:12 +00004952}
Mike Stump1eb44332009-09-09 15:08:12 +00004953
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004954/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump1eb44332009-09-09 15:08:12 +00004955/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004956/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump1eb44332009-09-09 15:08:12 +00004957/// and ToType is the type that we're eventually trying to convert to
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004958/// (which may or may not be the same type as the type that the
4959/// conversion function produces).
4960void
4961Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00004962 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00004963 CXXRecordDecl *ActingContext,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004964 Expr *From, QualType ToType,
4965 OverloadCandidateSet& CandidateSet) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00004966 assert(!Conversion->getDescribedFunctionTemplate() &&
4967 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004968 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor3f396022009-09-28 04:47:19 +00004969 if (!CandidateSet.isNewCandidate(Conversion))
4970 return;
4971
Douglas Gregor7edfb692009-11-23 12:27:39 +00004972 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00004973 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00004974
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004975 // Add this candidate
4976 CandidateSet.push_back(OverloadCandidate());
4977 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00004978 Candidate.FoundDecl = FoundDecl;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004979 Candidate.Function = Conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00004980 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00004981 Candidate.IgnoreObjectArgument = false;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004982 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor3fbaf3e2010-04-17 22:01:05 +00004983 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregorad323a82010-01-27 03:51:04 +00004984 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregorf1991ea2008-11-07 22:36:19 +00004985 Candidate.Viable = true;
4986 Candidate.Conversions.resize(1);
Douglas Gregordfc331e2011-01-19 23:54:39 +00004987 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004988
Douglas Gregorbca39322010-08-19 15:37:02 +00004989 // C++ [over.match.funcs]p4:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00004990 // For conversion functions, the function is considered to be a member of
4991 // the class of the implicit implied object argument for the purpose of
Douglas Gregorbca39322010-08-19 15:37:02 +00004992 // defining the type of the implicit object parameter.
Douglas Gregorc774b2f2010-08-19 15:57:50 +00004993 //
4994 // Determine the implicit conversion sequence for the implicit
4995 // object parameter.
4996 QualType ImplicitParamType = From->getType();
4997 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
4998 ImplicitParamType = FromPtrType->getPointeeType();
4999 CXXRecordDecl *ConversionContext
5000 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005001
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005002 Candidate.Conversions[0]
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005003 = TryObjectArgumentInitialization(*this, From->getType(),
5004 From->Classify(Context),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005005 Conversion, ConversionContext);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005006
John McCall1d318332010-01-12 00:44:57 +00005007 if (Candidate.Conversions[0].isBad()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005008 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005009 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005010 return;
5011 }
Douglas Gregorc774b2f2010-08-19 15:57:50 +00005012
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005013 // We won't go through a user-define type conversion function to convert a
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005014 // derived to base as such conversions are given Conversion Rank. They only
5015 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
5016 QualType FromCanon
5017 = Context.getCanonicalType(From->getType().getUnqualifiedType());
5018 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
5019 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
5020 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005021 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian3759a032009-10-19 19:18:20 +00005022 return;
5023 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005024
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005025 // To determine what the conversion from the result of calling the
5026 // conversion function to the type we're eventually trying to
5027 // convert to (ToType), we need to synthesize a call to the
5028 // conversion function and attempt copy initialization from it. This
5029 // makes sure that we get the right semantics with respect to
5030 // lvalues/rvalues and the type. Fortunately, we can allocate this
5031 // call on the stack and we don't need its arguments to be
5032 // well-formed.
Mike Stump1eb44332009-09-09 15:08:12 +00005033 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00005034 VK_LValue, From->getLocStart());
John McCallf871d0c2010-08-07 06:22:56 +00005035 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
5036 Context.getPointerType(Conversion->getType()),
John McCall2de56d12010-08-25 11:45:40 +00005037 CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00005038 &ConversionRef, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00005039
Richard Smith87c1f1f2011-07-13 22:53:21 +00005040 QualType ConversionType = Conversion->getConversionType();
5041 if (RequireCompleteType(From->getLocStart(), ConversionType, 0)) {
Douglas Gregor7d14d382010-11-13 19:36:57 +00005042 Candidate.Viable = false;
5043 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5044 return;
5045 }
5046
Richard Smith87c1f1f2011-07-13 22:53:21 +00005047 ExprValueKind VK = Expr::getValueKindForType(ConversionType);
John McCallf89e55a2010-11-18 06:31:45 +00005048
Mike Stump1eb44332009-09-09 15:08:12 +00005049 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenek668bf912009-02-09 20:51:47 +00005050 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
5051 // allocator).
Richard Smith87c1f1f2011-07-13 22:53:21 +00005052 QualType CallResultType = ConversionType.getNonLValueExprType(Context);
John McCallf89e55a2010-11-18 06:31:45 +00005053 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregor0a0d1ac2009-11-17 21:16:22 +00005054 From->getLocStart());
Mike Stump1eb44332009-09-09 15:08:12 +00005055 ImplicitConversionSequence ICS =
Douglas Gregor74eb6582010-04-16 17:51:22 +00005056 TryCopyInitialization(*this, &Call, ToType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005057 /*SuppressUserConversions=*/true,
John McCallf85e1932011-06-15 23:02:42 +00005058 /*InOverloadResolution=*/false,
5059 /*AllowObjCWritebackConversion=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00005060
John McCall1d318332010-01-12 00:44:57 +00005061 switch (ICS.getKind()) {
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005062 case ImplicitConversionSequence::StandardConversion:
5063 Candidate.FinalConversion = ICS.Standard;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005064
Douglas Gregorc520c842010-04-12 23:42:09 +00005065 // C++ [over.ics.user]p3:
5066 // If the user-defined conversion is specified by a specialization of a
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005067 // conversion function template, the second standard conversion sequence
Douglas Gregorc520c842010-04-12 23:42:09 +00005068 // shall have exact match rank.
5069 if (Conversion->getPrimaryTemplate() &&
5070 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
5071 Candidate.Viable = false;
5072 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
5073 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005074
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005075 // C++0x [dcl.init.ref]p5:
5076 // In the second case, if the reference is an rvalue reference and
5077 // the second standard conversion sequence of the user-defined
5078 // conversion sequence includes an lvalue-to-rvalue conversion, the
5079 // program is ill-formed.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005080 if (ToType->isRValueReferenceType() &&
Douglas Gregor2ad746a2011-01-21 05:18:22 +00005081 ICS.Standard.First == ICK_Lvalue_To_Rvalue) {
5082 Candidate.Viable = false;
5083 Candidate.FailureKind = ovl_fail_bad_final_conversion;
5084 }
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005085 break;
5086
5087 case ImplicitConversionSequence::BadConversion:
5088 Candidate.Viable = false;
John McCall717e8912010-01-23 05:17:32 +00005089 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005090 break;
5091
5092 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00005093 llvm_unreachable(
Douglas Gregorf1991ea2008-11-07 22:36:19 +00005094 "Can only end up with a standard conversion sequence or failure");
5095 }
5096}
5097
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005098/// \brief Adds a conversion function template specialization
5099/// candidate to the overload set, using template argument deduction
5100/// to deduce the template arguments of the conversion function
5101/// template from the type that we are converting to (C++
5102/// [temp.deduct.conv]).
Mike Stump1eb44332009-09-09 15:08:12 +00005103void
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005104Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCall9aa472c2010-03-19 07:35:19 +00005105 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005106 CXXRecordDecl *ActingDC,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005107 Expr *From, QualType ToType,
5108 OverloadCandidateSet &CandidateSet) {
5109 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
5110 "Only conversion function templates permitted here");
5111
Douglas Gregor3f396022009-09-28 04:47:19 +00005112 if (!CandidateSet.isNewCandidate(FunctionTemplate))
5113 return;
5114
John McCall5769d612010-02-08 23:07:23 +00005115 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005116 CXXConversionDecl *Specialization = 0;
5117 if (TemplateDeductionResult Result
Mike Stump1eb44332009-09-09 15:08:12 +00005118 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005119 Specialization, Info)) {
Douglas Gregorff5adac2010-05-08 20:18:54 +00005120 CandidateSet.push_back(OverloadCandidate());
5121 OverloadCandidate &Candidate = CandidateSet.back();
5122 Candidate.FoundDecl = FoundDecl;
5123 Candidate.Function = FunctionTemplate->getTemplatedDecl();
5124 Candidate.Viable = false;
5125 Candidate.FailureKind = ovl_fail_bad_deduction;
5126 Candidate.IsSurrogate = false;
5127 Candidate.IgnoreObjectArgument = false;
Douglas Gregordfc331e2011-01-19 23:54:39 +00005128 Candidate.ExplicitCallArguments = 1;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005129 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
Douglas Gregorff5adac2010-05-08 20:18:54 +00005130 Info);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005131 return;
5132 }
Mike Stump1eb44332009-09-09 15:08:12 +00005133
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005134 // Add the conversion function template specialization produced by
5135 // template argument deduction as a candidate.
5136 assert(Specialization && "Missing function template specialization?");
John McCall9aa472c2010-03-19 07:35:19 +00005137 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCall86820f52010-01-26 01:37:31 +00005138 CandidateSet);
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005139}
5140
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005141/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
5142/// converts the given @c Object to a function pointer via the
5143/// conversion function @c Conversion, and then attempts to call it
5144/// with the given arguments (C++ [over.call.object]p2-4). Proto is
5145/// the type of function that we'll eventually be calling.
5146void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCall9aa472c2010-03-19 07:35:19 +00005147 DeclAccessPair FoundDecl,
John McCall701c89e2009-12-03 04:06:58 +00005148 CXXRecordDecl *ActingContext,
Douglas Gregor72564e72009-02-26 23:50:07 +00005149 const FunctionProtoType *Proto,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005150 Expr *Object,
John McCall701c89e2009-12-03 04:06:58 +00005151 Expr **Args, unsigned NumArgs,
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005152 OverloadCandidateSet& CandidateSet) {
Douglas Gregor3f396022009-09-28 04:47:19 +00005153 if (!CandidateSet.isNewCandidate(Conversion))
5154 return;
5155
Douglas Gregor7edfb692009-11-23 12:27:39 +00005156 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005157 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005158
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005159 CandidateSet.push_back(OverloadCandidate());
5160 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00005161 Candidate.FoundDecl = FoundDecl;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005162 Candidate.Function = 0;
5163 Candidate.Surrogate = Conversion;
5164 Candidate.Viable = true;
5165 Candidate.IsSurrogate = true;
Douglas Gregor88a35142008-12-22 05:46:06 +00005166 Candidate.IgnoreObjectArgument = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005167 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregordfc331e2011-01-19 23:54:39 +00005168 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005169
5170 // Determine the implicit conversion sequence for the implicit
5171 // object parameter.
Mike Stump1eb44332009-09-09 15:08:12 +00005172 ImplicitConversionSequence ObjectInit
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005173 = TryObjectArgumentInitialization(*this, Object->getType(),
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005174 Object->Classify(Context),
5175 Conversion, ActingContext);
John McCall1d318332010-01-12 00:44:57 +00005176 if (ObjectInit.isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005177 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005178 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall717e8912010-01-23 05:17:32 +00005179 Candidate.Conversions[0] = ObjectInit;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005180 return;
5181 }
5182
5183 // The first conversion is actually a user-defined conversion whose
5184 // first conversion is ObjectInit's standard conversion (which is
5185 // effectively a reference binding). Record it as such.
John McCall1d318332010-01-12 00:44:57 +00005186 Candidate.Conversions[0].setUserDefined();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005187 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian966256a2009-11-06 00:23:08 +00005188 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00005189 Candidate.Conversions[0].UserDefined.HadMultipleCandidates = false;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005190 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
John McCallca82a822011-09-21 08:36:56 +00005191 Candidate.Conversions[0].UserDefined.FoundConversionFunction = FoundDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00005192 Candidate.Conversions[0].UserDefined.After
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005193 = Candidate.Conversions[0].UserDefined.Before;
5194 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
5195
Mike Stump1eb44332009-09-09 15:08:12 +00005196 // Find the
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005197 unsigned NumArgsInProto = Proto->getNumArgs();
5198
5199 // (C++ 13.3.2p2): A candidate function having fewer than m
5200 // parameters is viable only if it has an ellipsis in its parameter
5201 // list (8.3.5).
5202 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
5203 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005204 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005205 return;
5206 }
5207
5208 // Function types don't have any default arguments, so just check if
5209 // we have enough arguments.
5210 if (NumArgs < NumArgsInProto) {
5211 // Not enough arguments.
5212 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005213 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005214 return;
5215 }
5216
5217 // Determine the implicit conversion sequences for each of the
5218 // arguments.
5219 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5220 if (ArgIdx < NumArgsInProto) {
5221 // (C++ 13.3.2p3): for F to be a viable function, there shall
5222 // exist for each argument an implicit conversion sequence
5223 // (13.3.3.1) that converts that argument to the corresponding
5224 // parameter of F.
5225 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump1eb44332009-09-09 15:08:12 +00005226 Candidate.Conversions[ArgIdx + 1]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005227 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlssond28b4282009-08-27 17:18:13 +00005228 /*SuppressUserConversions=*/false,
John McCallf85e1932011-06-15 23:02:42 +00005229 /*InOverloadResolution=*/false,
5230 /*AllowObjCWritebackConversion=*/
5231 getLangOptions().ObjCAutoRefCount);
John McCall1d318332010-01-12 00:44:57 +00005232 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005233 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005234 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005235 break;
5236 }
5237 } else {
5238 // (C++ 13.3.2p2): For the purposes of overload resolution, any
5239 // argument for which there is no corresponding parameter is
5240 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall1d318332010-01-12 00:44:57 +00005241 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor106c6eb2008-11-19 22:57:39 +00005242 }
5243 }
5244}
5245
Douglas Gregor063daf62009-03-13 18:40:31 +00005246/// \brief Add overload candidates for overloaded operators that are
5247/// member functions.
5248///
5249/// Add the overloaded operator candidates that are member functions
5250/// for the operator Op that was used in an operator expression such
5251/// as "x Op y". , Args/NumArgs provides the operator arguments, and
5252/// CandidateSet will store the added overload candidates. (C++
5253/// [over.match.oper]).
5254void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
5255 SourceLocation OpLoc,
5256 Expr **Args, unsigned NumArgs,
5257 OverloadCandidateSet& CandidateSet,
5258 SourceRange OpRange) {
Douglas Gregor96176b32008-11-18 23:14:02 +00005259 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
5260
5261 // C++ [over.match.oper]p3:
5262 // For a unary operator @ with an operand of a type whose
5263 // cv-unqualified version is T1, and for a binary operator @ with
5264 // a left operand of a type whose cv-unqualified version is T1 and
5265 // a right operand of a type whose cv-unqualified version is T2,
5266 // three sets of candidate functions, designated member
5267 // candidates, non-member candidates and built-in candidates, are
5268 // constructed as follows:
5269 QualType T1 = Args[0]->getType();
Douglas Gregor96176b32008-11-18 23:14:02 +00005270
5271 // -- If T1 is a class type, the set of member candidates is the
5272 // result of the qualified lookup of T1::operator@
5273 // (13.3.1.1.1); otherwise, the set of member candidates is
5274 // empty.
Ted Kremenek6217b802009-07-29 21:53:49 +00005275 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005276 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson8c8d9192009-10-09 23:51:55 +00005277 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005278 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005279
John McCalla24dc2e2009-11-17 02:14:36 +00005280 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
5281 LookupQualifiedName(Operators, T1Rec->getDecl());
5282 Operators.suppressDiagnostics();
5283
Mike Stump1eb44332009-09-09 15:08:12 +00005284 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor8a5ae242009-08-27 23:35:55 +00005285 OperEnd = Operators.end();
5286 Oper != OperEnd;
John McCall314be4e2009-11-17 07:50:12 +00005287 ++Oper)
John McCall9aa472c2010-03-19 07:35:19 +00005288 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005289 Args[0]->Classify(Context), Args + 1, NumArgs - 1,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005290 CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00005291 /* SuppressUserConversions = */ false);
Douglas Gregor96176b32008-11-18 23:14:02 +00005292 }
Douglas Gregor96176b32008-11-18 23:14:02 +00005293}
5294
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005295/// AddBuiltinCandidate - Add a candidate for a built-in
5296/// operator. ResultTy and ParamTys are the result and parameter types
5297/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005298/// arguments being passed to the candidate. IsAssignmentOperator
5299/// should be true when this built-in candidate is an assignment
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005300/// operator. NumContextualBoolArguments is the number of arguments
5301/// (at the beginning of the argument list) that will be contextually
5302/// converted to bool.
Mike Stump1eb44332009-09-09 15:08:12 +00005303void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005304 Expr **Args, unsigned NumArgs,
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005305 OverloadCandidateSet& CandidateSet,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005306 bool IsAssignmentOperator,
5307 unsigned NumContextualBoolArguments) {
Douglas Gregor7edfb692009-11-23 12:27:39 +00005308 // Overload resolution is always an unevaluated context.
John McCallf312b1e2010-08-26 23:41:50 +00005309 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor7edfb692009-11-23 12:27:39 +00005310
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005311 // Add this candidate
5312 CandidateSet.push_back(OverloadCandidate());
5313 OverloadCandidate& Candidate = CandidateSet.back();
John McCall9aa472c2010-03-19 07:35:19 +00005314 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005315 Candidate.Function = 0;
Douglas Gregorc9467cf2008-12-12 02:00:36 +00005316 Candidate.IsSurrogate = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00005317 Candidate.IgnoreObjectArgument = false;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005318 Candidate.BuiltinTypes.ResultTy = ResultTy;
5319 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5320 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
5321
5322 // Determine the implicit conversion sequences for each of the
5323 // arguments.
5324 Candidate.Viable = true;
5325 Candidate.Conversions.resize(NumArgs);
Douglas Gregordfc331e2011-01-19 23:54:39 +00005326 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005327 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005328 // C++ [over.match.oper]p4:
5329 // For the built-in assignment operators, conversions of the
5330 // left operand are restricted as follows:
5331 // -- no temporaries are introduced to hold the left operand, and
5332 // -- no user-defined conversions are applied to the left
5333 // operand to achieve a type match with the left-most
Mike Stump1eb44332009-09-09 15:08:12 +00005334 // parameter of a built-in candidate.
Douglas Gregor88b4bf22009-01-13 00:52:54 +00005335 //
5336 // We block these conversions by turning off user-defined
5337 // conversions, since that is the only way that initialization of
5338 // a reference to a non-class type can occur from something that
5339 // is not of the same type.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005340 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump1eb44332009-09-09 15:08:12 +00005341 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005342 "Contextual conversion to bool requires bool type");
John McCall120d63c2010-08-24 20:38:10 +00005343 Candidate.Conversions[ArgIdx]
5344 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005345 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00005346 Candidate.Conversions[ArgIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00005347 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlssond28b4282009-08-27 17:18:13 +00005348 ArgIdx == 0 && IsAssignmentOperator,
John McCallf85e1932011-06-15 23:02:42 +00005349 /*InOverloadResolution=*/false,
5350 /*AllowObjCWritebackConversion=*/
5351 getLangOptions().ObjCAutoRefCount);
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005352 }
John McCall1d318332010-01-12 00:44:57 +00005353 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005354 Candidate.Viable = false;
John McCalladbb8f82010-01-13 09:16:55 +00005355 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor96176b32008-11-18 23:14:02 +00005356 break;
5357 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005358 }
5359}
5360
5361/// BuiltinCandidateTypeSet - A set of types that will be used for the
5362/// candidate operator functions for built-in operators (C++
5363/// [over.built]). The types are separated into pointer types and
5364/// enumeration types.
5365class BuiltinCandidateTypeSet {
5366 /// TypeSet - A set of types.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005367 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005368
5369 /// PointerTypes - The set of pointer types that will be used in the
5370 /// built-in candidates.
5371 TypeSet PointerTypes;
5372
Sebastian Redl78eb8742009-04-19 21:53:20 +00005373 /// MemberPointerTypes - The set of member pointer types that will be
5374 /// used in the built-in candidates.
5375 TypeSet MemberPointerTypes;
5376
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005377 /// EnumerationTypes - The set of enumeration types that will be
5378 /// used in the built-in candidates.
5379 TypeSet EnumerationTypes;
5380
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005381 /// \brief The set of vector types that will be used in the built-in
Douglas Gregor26bcf672010-05-19 03:21:00 +00005382 /// candidates.
5383 TypeSet VectorTypes;
Chandler Carruth6a577462010-12-13 01:44:01 +00005384
5385 /// \brief A flag indicating non-record types are viable candidates
5386 bool HasNonRecordTypes;
5387
5388 /// \brief A flag indicating whether either arithmetic or enumeration types
5389 /// were present in the candidate set.
5390 bool HasArithmeticOrEnumeralTypes;
5391
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005392 /// \brief A flag indicating whether the nullptr type was present in the
5393 /// candidate set.
5394 bool HasNullPtrType;
5395
Douglas Gregor5842ba92009-08-24 15:23:48 +00005396 /// Sema - The semantic analysis instance where we are building the
5397 /// candidate type set.
5398 Sema &SemaRef;
Mike Stump1eb44332009-09-09 15:08:12 +00005399
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005400 /// Context - The AST context in which we will build the type sets.
5401 ASTContext &Context;
5402
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005403 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5404 const Qualifiers &VisibleQuals);
Sebastian Redl78eb8742009-04-19 21:53:20 +00005405 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005406
5407public:
5408 /// iterator - Iterates through the types that are part of the set.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005409 typedef TypeSet::iterator iterator;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005410
Mike Stump1eb44332009-09-09 15:08:12 +00005411 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth6a577462010-12-13 01:44:01 +00005412 : HasNonRecordTypes(false),
5413 HasArithmeticOrEnumeralTypes(false),
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005414 HasNullPtrType(false),
Chandler Carruth6a577462010-12-13 01:44:01 +00005415 SemaRef(SemaRef),
5416 Context(SemaRef.Context) { }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005417
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005418 void AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00005419 SourceLocation Loc,
5420 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005421 bool AllowExplicitConversions,
5422 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005423
5424 /// pointer_begin - First pointer type found;
5425 iterator pointer_begin() { return PointerTypes.begin(); }
5426
Sebastian Redl78eb8742009-04-19 21:53:20 +00005427 /// pointer_end - Past the last pointer type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005428 iterator pointer_end() { return PointerTypes.end(); }
5429
Sebastian Redl78eb8742009-04-19 21:53:20 +00005430 /// member_pointer_begin - First member pointer type found;
5431 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
5432
5433 /// member_pointer_end - Past the last member pointer type found;
5434 iterator member_pointer_end() { return MemberPointerTypes.end(); }
5435
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005436 /// enumeration_begin - First enumeration type found;
5437 iterator enumeration_begin() { return EnumerationTypes.begin(); }
5438
Sebastian Redl78eb8742009-04-19 21:53:20 +00005439 /// enumeration_end - Past the last enumeration type found;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005440 iterator enumeration_end() { return EnumerationTypes.end(); }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005441
Douglas Gregor26bcf672010-05-19 03:21:00 +00005442 iterator vector_begin() { return VectorTypes.begin(); }
5443 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth6a577462010-12-13 01:44:01 +00005444
5445 bool hasNonRecordTypes() { return HasNonRecordTypes; }
5446 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005447 bool hasNullPtrType() const { return HasNullPtrType; }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005448};
5449
Sebastian Redl78eb8742009-04-19 21:53:20 +00005450/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005451/// the set of pointer types along with any more-qualified variants of
5452/// that type. For example, if @p Ty is "int const *", this routine
5453/// will add "int const *", "int const volatile *", "int const
5454/// restrict *", and "int const volatile restrict *" to the set of
5455/// pointer types. Returns true if the add of @p Ty itself succeeded,
5456/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00005457///
5458/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00005459bool
Douglas Gregor573d9c32009-10-21 23:19:44 +00005460BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
5461 const Qualifiers &VisibleQuals) {
John McCall0953e762009-09-24 19:53:00 +00005462
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005463 // Insert this type.
Chris Lattnere37b94c2009-03-29 00:04:01 +00005464 if (!PointerTypes.insert(Ty))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005465 return false;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005466
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005467 QualType PointeeTy;
John McCall0953e762009-09-24 19:53:00 +00005468 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005469 bool buildObjCPtr = false;
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005470 if (!PointerTy) {
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005471 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005472 PointeeTy = PTy->getPointeeType();
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005473 buildObjCPtr = true;
5474 }
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005475 else
David Blaikieb219cfc2011-09-23 05:06:16 +00005476 llvm_unreachable("type was not a pointer type!");
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005477 }
5478 else
5479 PointeeTy = PointerTy->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005480
Sebastian Redla9efada2009-11-18 20:39:26 +00005481 // Don't add qualified variants of arrays. For one, they're not allowed
5482 // (the qualifier would sink to the element type), and for another, the
5483 // only overload situation where it matters is subscript or pointer +- int,
5484 // and those shouldn't have qualifier variants anyway.
5485 if (PointeeTy->isArrayType())
5486 return true;
John McCall0953e762009-09-24 19:53:00 +00005487 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor89c49f02009-11-09 22:08:55 +00005488 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahaniand411b3f2009-11-09 21:02:05 +00005489 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005490 bool hasVolatile = VisibleQuals.hasVolatile();
5491 bool hasRestrict = VisibleQuals.hasRestrict();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005492
John McCall0953e762009-09-24 19:53:00 +00005493 // Iterate through all strict supersets of BaseCVR.
5494 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5495 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005496 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
5497 // in the types.
5498 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
5499 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall0953e762009-09-24 19:53:00 +00005500 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanian957b4df2010-08-21 17:11:09 +00005501 if (!buildObjCPtr)
5502 PointerTypes.insert(Context.getPointerType(QPointeeTy));
5503 else
5504 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005505 }
5506
5507 return true;
5508}
5509
Sebastian Redl78eb8742009-04-19 21:53:20 +00005510/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
5511/// to the set of pointer types along with any more-qualified variants of
5512/// that type. For example, if @p Ty is "int const *", this routine
5513/// will add "int const *", "int const volatile *", "int const
5514/// restrict *", and "int const volatile restrict *" to the set of
5515/// pointer types. Returns true if the add of @p Ty itself succeeded,
5516/// false otherwise.
John McCall0953e762009-09-24 19:53:00 +00005517///
5518/// FIXME: what to do about extended qualifiers?
Sebastian Redl78eb8742009-04-19 21:53:20 +00005519bool
5520BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
5521 QualType Ty) {
5522 // Insert this type.
5523 if (!MemberPointerTypes.insert(Ty))
5524 return false;
5525
John McCall0953e762009-09-24 19:53:00 +00005526 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
5527 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl78eb8742009-04-19 21:53:20 +00005528
John McCall0953e762009-09-24 19:53:00 +00005529 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redla9efada2009-11-18 20:39:26 +00005530 // Don't add qualified variants of arrays. For one, they're not allowed
5531 // (the qualifier would sink to the element type), and for another, the
5532 // only overload situation where it matters is subscript or pointer +- int,
5533 // and those shouldn't have qualifier variants anyway.
5534 if (PointeeTy->isArrayType())
5535 return true;
John McCall0953e762009-09-24 19:53:00 +00005536 const Type *ClassTy = PointerTy->getClass();
5537
5538 // Iterate through all strict supersets of the pointee type's CVR
5539 // qualifiers.
5540 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
5541 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
5542 if ((CVR | BaseCVR) != CVR) continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005543
John McCall0953e762009-09-24 19:53:00 +00005544 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth6df868e2010-12-12 08:17:55 +00005545 MemberPointerTypes.insert(
5546 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl78eb8742009-04-19 21:53:20 +00005547 }
5548
5549 return true;
5550}
5551
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005552/// AddTypesConvertedFrom - Add each of the types to which the type @p
5553/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl78eb8742009-04-19 21:53:20 +00005554/// primarily interested in pointer types and enumeration types. We also
5555/// take member pointer types, for the conditional operator.
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005556/// AllowUserConversions is true if we should look at the conversion
5557/// functions of a class type, and AllowExplicitConversions if we
5558/// should also include the explicit conversion functions of a class
5559/// type.
Mike Stump1eb44332009-09-09 15:08:12 +00005560void
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005561BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregor573d9c32009-10-21 23:19:44 +00005562 SourceLocation Loc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00005563 bool AllowUserConversions,
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005564 bool AllowExplicitConversions,
5565 const Qualifiers &VisibleQuals) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005566 // Only deal with canonical types.
5567 Ty = Context.getCanonicalType(Ty);
5568
5569 // Look through reference types; they aren't part of the type of an
5570 // expression for the purposes of conversions.
Ted Kremenek6217b802009-07-29 21:53:49 +00005571 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005572 Ty = RefTy->getPointeeType();
5573
John McCall3b657512011-01-19 10:06:00 +00005574 // If we're dealing with an array type, decay to the pointer.
5575 if (Ty->isArrayType())
5576 Ty = SemaRef.Context.getArrayDecayedType(Ty);
5577
5578 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregora4923eb2009-11-16 21:35:15 +00005579 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005580
Chandler Carruth6a577462010-12-13 01:44:01 +00005581 // Flag if we ever add a non-record type.
5582 const RecordType *TyRec = Ty->getAs<RecordType>();
5583 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
5584
Chandler Carruth6a577462010-12-13 01:44:01 +00005585 // Flag if we encounter an arithmetic type.
5586 HasArithmeticOrEnumeralTypes =
5587 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
5588
Fariborz Jahanian2e2acec2010-08-21 00:10:36 +00005589 if (Ty->isObjCIdType() || Ty->isObjCClassType())
5590 PointerTypes.insert(Ty);
5591 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005592 // Insert our type, and its more-qualified variants, into the set
5593 // of types.
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005594 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005595 return;
Sebastian Redl78eb8742009-04-19 21:53:20 +00005596 } else if (Ty->isMemberPointerType()) {
5597 // Member pointers are far easier, since the pointee can't be converted.
5598 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
5599 return;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005600 } else if (Ty->isEnumeralType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005601 HasArithmeticOrEnumeralTypes = true;
Chris Lattnere37b94c2009-03-29 00:04:01 +00005602 EnumerationTypes.insert(Ty);
Douglas Gregor26bcf672010-05-19 03:21:00 +00005603 } else if (Ty->isVectorType()) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005604 // We treat vector types as arithmetic types in many contexts as an
5605 // extension.
5606 HasArithmeticOrEnumeralTypes = true;
Douglas Gregor26bcf672010-05-19 03:21:00 +00005607 VectorTypes.insert(Ty);
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00005608 } else if (Ty->isNullPtrType()) {
5609 HasNullPtrType = true;
Chandler Carruth6a577462010-12-13 01:44:01 +00005610 } else if (AllowUserConversions && TyRec) {
5611 // No conversion functions in incomplete types.
5612 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
5613 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005614
Chandler Carruth6a577462010-12-13 01:44:01 +00005615 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
5616 const UnresolvedSetImpl *Conversions
5617 = ClassDecl->getVisibleConversionFunctions();
5618 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
5619 E = Conversions->end(); I != E; ++I) {
5620 NamedDecl *D = I.getDecl();
5621 if (isa<UsingShadowDecl>(D))
5622 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005623
Chandler Carruth6a577462010-12-13 01:44:01 +00005624 // Skip conversion function templates; they don't tell us anything
5625 // about which builtin types we can convert to.
5626 if (isa<FunctionTemplateDecl>(D))
5627 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00005628
Chandler Carruth6a577462010-12-13 01:44:01 +00005629 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
5630 if (AllowExplicitConversions || !Conv->isExplicit()) {
5631 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
5632 VisibleQuals);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00005633 }
5634 }
5635 }
5636}
5637
Douglas Gregor19b7b152009-08-24 13:43:27 +00005638/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
5639/// the volatile- and non-volatile-qualified assignment operators for the
5640/// given type to the candidate set.
5641static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
5642 QualType T,
Mike Stump1eb44332009-09-09 15:08:12 +00005643 Expr **Args,
Douglas Gregor19b7b152009-08-24 13:43:27 +00005644 unsigned NumArgs,
5645 OverloadCandidateSet &CandidateSet) {
5646 QualType ParamTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00005647
Douglas Gregor19b7b152009-08-24 13:43:27 +00005648 // T& operator=(T&, T)
5649 ParamTypes[0] = S.Context.getLValueReferenceType(T);
5650 ParamTypes[1] = T;
5651 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5652 /*IsAssignmentOperator=*/true);
Mike Stump1eb44332009-09-09 15:08:12 +00005653
Douglas Gregor19b7b152009-08-24 13:43:27 +00005654 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
5655 // volatile T& operator=(volatile T&, T)
John McCall0953e762009-09-24 19:53:00 +00005656 ParamTypes[0]
5657 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor19b7b152009-08-24 13:43:27 +00005658 ParamTypes[1] = T;
5659 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump1eb44332009-09-09 15:08:12 +00005660 /*IsAssignmentOperator=*/true);
Douglas Gregor19b7b152009-08-24 13:43:27 +00005661 }
5662}
Mike Stump1eb44332009-09-09 15:08:12 +00005663
Sebastian Redl9994a342009-10-25 17:03:50 +00005664/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
5665/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005666static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
5667 Qualifiers VRQuals;
5668 const RecordType *TyRec;
5669 if (const MemberPointerType *RHSMPType =
5670 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregorb86cf0c2010-04-25 00:55:24 +00005671 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005672 else
5673 TyRec = ArgExpr->getType()->getAs<RecordType>();
5674 if (!TyRec) {
Fariborz Jahanian1cad6022009-10-16 22:08:05 +00005675 // Just to be safe, assume the worst case.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005676 VRQuals.addVolatile();
5677 VRQuals.addRestrict();
5678 return VRQuals;
5679 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005680
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005681 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall86ff3082010-02-04 22:26:26 +00005682 if (!ClassDecl->hasDefinition())
5683 return VRQuals;
5684
John McCalleec51cf2010-01-20 00:46:10 +00005685 const UnresolvedSetImpl *Conversions =
Sebastian Redl9994a342009-10-25 17:03:50 +00005686 ClassDecl->getVisibleConversionFunctions();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005687
John McCalleec51cf2010-01-20 00:46:10 +00005688 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00005689 E = Conversions->end(); I != E; ++I) {
John McCall32daa422010-03-31 01:36:47 +00005690 NamedDecl *D = I.getDecl();
5691 if (isa<UsingShadowDecl>(D))
5692 D = cast<UsingShadowDecl>(D)->getTargetDecl();
5693 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005694 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
5695 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
5696 CanTy = ResTypeRef->getPointeeType();
5697 // Need to go down the pointer/mempointer chain and add qualifiers
5698 // as see them.
5699 bool done = false;
5700 while (!done) {
5701 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
5702 CanTy = ResTypePtr->getPointeeType();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005703 else if (const MemberPointerType *ResTypeMPtr =
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00005704 CanTy->getAs<MemberPointerType>())
5705 CanTy = ResTypeMPtr->getPointeeType();
5706 else
5707 done = true;
5708 if (CanTy.isVolatileQualified())
5709 VRQuals.addVolatile();
5710 if (CanTy.isRestrictQualified())
5711 VRQuals.addRestrict();
5712 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
5713 return VRQuals;
5714 }
5715 }
5716 }
5717 return VRQuals;
5718}
John McCall00071ec2010-11-13 05:51:15 +00005719
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005720namespace {
John McCall00071ec2010-11-13 05:51:15 +00005721
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005722/// \brief Helper class to manage the addition of builtin operator overload
5723/// candidates. It provides shared state and utility methods used throughout
5724/// the process, as well as a helper method to add each group of builtin
5725/// operator overloads from the standard to a candidate set.
5726class BuiltinOperatorOverloadBuilder {
Chandler Carruth6d695582010-12-12 10:35:00 +00005727 // Common instance state available to all overload candidate addition methods.
5728 Sema &S;
5729 Expr **Args;
5730 unsigned NumArgs;
5731 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth6a577462010-12-13 01:44:01 +00005732 bool HasArithmeticOrEnumeralCandidateType;
Chris Lattner5f9e2722011-07-23 10:55:15 +00005733 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
Chandler Carruth6d695582010-12-12 10:35:00 +00005734 OverloadCandidateSet &CandidateSet;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005735
Chandler Carruth6d695582010-12-12 10:35:00 +00005736 // Define some constants used to index and iterate over the arithemetic types
5737 // provided via the getArithmeticType() method below.
John McCall00071ec2010-11-13 05:51:15 +00005738 // The "promoted arithmetic types" are the arithmetic
5739 // types are that preserved by promotion (C++ [over.built]p2).
John McCall00071ec2010-11-13 05:51:15 +00005740 static const unsigned FirstIntegralType = 3;
5741 static const unsigned LastIntegralType = 18;
5742 static const unsigned FirstPromotedIntegralType = 3,
5743 LastPromotedIntegralType = 9;
5744 static const unsigned FirstPromotedArithmeticType = 0,
5745 LastPromotedArithmeticType = 9;
5746 static const unsigned NumArithmeticTypes = 18;
5747
Chandler Carruth6d695582010-12-12 10:35:00 +00005748 /// \brief Get the canonical type for a given arithmetic type index.
5749 CanQualType getArithmeticType(unsigned index) {
5750 assert(index < NumArithmeticTypes);
5751 static CanQualType ASTContext::* const
5752 ArithmeticTypes[NumArithmeticTypes] = {
5753 // Start of promoted types.
5754 &ASTContext::FloatTy,
5755 &ASTContext::DoubleTy,
5756 &ASTContext::LongDoubleTy,
John McCall00071ec2010-11-13 05:51:15 +00005757
Chandler Carruth6d695582010-12-12 10:35:00 +00005758 // Start of integral types.
5759 &ASTContext::IntTy,
5760 &ASTContext::LongTy,
5761 &ASTContext::LongLongTy,
5762 &ASTContext::UnsignedIntTy,
5763 &ASTContext::UnsignedLongTy,
5764 &ASTContext::UnsignedLongLongTy,
5765 // End of promoted types.
5766
5767 &ASTContext::BoolTy,
5768 &ASTContext::CharTy,
5769 &ASTContext::WCharTy,
5770 &ASTContext::Char16Ty,
5771 &ASTContext::Char32Ty,
5772 &ASTContext::SignedCharTy,
5773 &ASTContext::ShortTy,
5774 &ASTContext::UnsignedCharTy,
5775 &ASTContext::UnsignedShortTy,
5776 // End of integral types.
5777 // FIXME: What about complex?
5778 };
5779 return S.Context.*ArithmeticTypes[index];
5780 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005781
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005782 /// \brief Gets the canonical type resulting from the usual arithemetic
5783 /// converions for the given arithmetic types.
5784 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
5785 // Accelerator table for performing the usual arithmetic conversions.
5786 // The rules are basically:
5787 // - if either is floating-point, use the wider floating-point
5788 // - if same signedness, use the higher rank
5789 // - if same size, use unsigned of the higher rank
5790 // - use the larger type
5791 // These rules, together with the axiom that higher ranks are
5792 // never smaller, are sufficient to precompute all of these results
5793 // *except* when dealing with signed types of higher rank.
5794 // (we could precompute SLL x UI for all known platforms, but it's
5795 // better not to make any assumptions).
5796 enum PromotedType {
5797 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
5798 };
5799 static PromotedType ConversionsTable[LastPromotedArithmeticType]
5800 [LastPromotedArithmeticType] = {
5801 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
5802 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
5803 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
5804 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
5805 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
5806 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
5807 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
5808 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
5809 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
5810 };
5811
5812 assert(L < LastPromotedArithmeticType);
5813 assert(R < LastPromotedArithmeticType);
5814 int Idx = ConversionsTable[L][R];
5815
5816 // Fast path: the table gives us a concrete answer.
Chandler Carruth6d695582010-12-12 10:35:00 +00005817 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005818
5819 // Slow path: we need to compare widths.
5820 // An invariant is that the signed type has higher rank.
Chandler Carruth6d695582010-12-12 10:35:00 +00005821 CanQualType LT = getArithmeticType(L),
5822 RT = getArithmeticType(R);
Chandler Carruth38ca8d12010-12-12 09:59:53 +00005823 unsigned LW = S.Context.getIntWidth(LT),
5824 RW = S.Context.getIntWidth(RT);
5825
5826 // If they're different widths, use the signed type.
5827 if (LW > RW) return LT;
5828 else if (LW < RW) return RT;
5829
5830 // Otherwise, use the unsigned type of the signed type's rank.
5831 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
5832 assert(L == SLL || R == SLL);
5833 return S.Context.UnsignedLongLongTy;
5834 }
5835
Chandler Carruth3c69dc42010-12-12 09:22:45 +00005836 /// \brief Helper method to factor out the common pattern of adding overloads
5837 /// for '++' and '--' builtin operators.
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005838 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
5839 bool HasVolatile) {
5840 QualType ParamTypes[2] = {
5841 S.Context.getLValueReferenceType(CandidateTy),
5842 S.Context.IntTy
5843 };
5844
5845 // Non-volatile version.
5846 if (NumArgs == 1)
5847 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5848 else
5849 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5850
5851 // Use a heuristic to reduce number of builtin candidates in the set:
5852 // add volatile version only if there are conversions to a volatile type.
5853 if (HasVolatile) {
5854 ParamTypes[0] =
5855 S.Context.getLValueReferenceType(
5856 S.Context.getVolatileType(CandidateTy));
5857 if (NumArgs == 1)
5858 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
5859 else
5860 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
5861 }
5862 }
5863
5864public:
5865 BuiltinOperatorOverloadBuilder(
5866 Sema &S, Expr **Args, unsigned NumArgs,
5867 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00005868 bool HasArithmeticOrEnumeralCandidateType,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005869 SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005870 OverloadCandidateSet &CandidateSet)
5871 : S(S), Args(Args), NumArgs(NumArgs),
5872 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth6a577462010-12-13 01:44:01 +00005873 HasArithmeticOrEnumeralCandidateType(
5874 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005875 CandidateTypes(CandidateTypes),
5876 CandidateSet(CandidateSet) {
5877 // Validate some of our static helper constants in debug builds.
Chandler Carruth6d695582010-12-12 10:35:00 +00005878 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005879 "Invalid first promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005880 assert(getArithmeticType(LastPromotedIntegralType - 1)
5881 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005882 "Invalid last promoted integral type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005883 assert(getArithmeticType(FirstPromotedArithmeticType)
5884 == S.Context.FloatTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005885 "Invalid first promoted arithmetic type");
Chandler Carruth6d695582010-12-12 10:35:00 +00005886 assert(getArithmeticType(LastPromotedArithmeticType - 1)
5887 == S.Context.UnsignedLongLongTy &&
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005888 "Invalid last promoted arithmetic type");
5889 }
5890
5891 // C++ [over.built]p3:
5892 //
5893 // For every pair (T, VQ), where T is an arithmetic type, and VQ
5894 // is either volatile or empty, there exist candidate operator
5895 // functions of the form
5896 //
5897 // VQ T& operator++(VQ T&);
5898 // T operator++(VQ T&, int);
5899 //
5900 // C++ [over.built]p4:
5901 //
5902 // For every pair (T, VQ), where T is an arithmetic type other
5903 // than bool, and VQ is either volatile or empty, there exist
5904 // candidate operator functions of the form
5905 //
5906 // VQ T& operator--(VQ T&);
5907 // T operator--(VQ T&, int);
5908 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00005909 if (!HasArithmeticOrEnumeralCandidateType)
5910 return;
5911
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005912 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
5913 Arith < NumArithmeticTypes; ++Arith) {
5914 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruth6d695582010-12-12 10:35:00 +00005915 getArithmeticType(Arith),
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005916 VisibleTypeConversionsQuals.hasVolatile());
5917 }
5918 }
5919
5920 // C++ [over.built]p5:
5921 //
5922 // For every pair (T, VQ), where T is a cv-qualified or
5923 // cv-unqualified object type, and VQ is either volatile or
5924 // empty, there exist candidate operator functions of the form
5925 //
5926 // T*VQ& operator++(T*VQ&);
5927 // T*VQ& operator--(T*VQ&);
5928 // T* operator++(T*VQ&, int);
5929 // T* operator--(T*VQ&, int);
5930 void addPlusPlusMinusMinusPointerOverloads() {
5931 for (BuiltinCandidateTypeSet::iterator
5932 Ptr = CandidateTypes[0].pointer_begin(),
5933 PtrEnd = CandidateTypes[0].pointer_end();
5934 Ptr != PtrEnd; ++Ptr) {
5935 // Skip pointer types that aren't pointers to object types.
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005936 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005937 continue;
5938
5939 addPlusPlusMinusMinusStyleOverloads(*Ptr,
5940 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5941 VisibleTypeConversionsQuals.hasVolatile()));
5942 }
5943 }
5944
5945 // C++ [over.built]p6:
5946 // For every cv-qualified or cv-unqualified object type T, there
5947 // exist candidate operator functions of the form
5948 //
5949 // T& operator*(T*);
5950 //
5951 // C++ [over.built]p7:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005952 // For every function type T that does not have cv-qualifiers or a
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005953 // ref-qualifier, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005954 // T& operator*(T*);
5955 void addUnaryStarPointerOverloads() {
5956 for (BuiltinCandidateTypeSet::iterator
5957 Ptr = CandidateTypes[0].pointer_begin(),
5958 PtrEnd = CandidateTypes[0].pointer_end();
5959 Ptr != PtrEnd; ++Ptr) {
5960 QualType ParamTy = *Ptr;
5961 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00005962 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
5963 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005964
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00005965 if (const FunctionProtoType *Proto =PointeeTy->getAs<FunctionProtoType>())
5966 if (Proto->getTypeQuals() || Proto->getRefQualifier())
5967 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00005968
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005969 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
5970 &ParamTy, Args, 1, CandidateSet);
5971 }
5972 }
5973
5974 // C++ [over.built]p9:
5975 // For every promoted arithmetic type T, there exist candidate
5976 // operator functions of the form
5977 //
5978 // T operator+(T);
5979 // T operator-(T);
5980 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00005981 if (!HasArithmeticOrEnumeralCandidateType)
5982 return;
5983
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005984 for (unsigned Arith = FirstPromotedArithmeticType;
5985 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruth6d695582010-12-12 10:35:00 +00005986 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00005987 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
5988 }
5989
5990 // Extension: We also add these operators for vector types.
5991 for (BuiltinCandidateTypeSet::iterator
5992 Vec = CandidateTypes[0].vector_begin(),
5993 VecEnd = CandidateTypes[0].vector_end();
5994 Vec != VecEnd; ++Vec) {
5995 QualType VecTy = *Vec;
5996 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
5997 }
5998 }
5999
6000 // C++ [over.built]p8:
6001 // For every type T, there exist candidate operator functions of
6002 // the form
6003 //
6004 // T* operator+(T*);
6005 void addUnaryPlusPointerOverloads() {
6006 for (BuiltinCandidateTypeSet::iterator
6007 Ptr = CandidateTypes[0].pointer_begin(),
6008 PtrEnd = CandidateTypes[0].pointer_end();
6009 Ptr != PtrEnd; ++Ptr) {
6010 QualType ParamTy = *Ptr;
6011 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
6012 }
6013 }
6014
6015 // C++ [over.built]p10:
6016 // For every promoted integral type T, there exist candidate
6017 // operator functions of the form
6018 //
6019 // T operator~(T);
6020 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006021 if (!HasArithmeticOrEnumeralCandidateType)
6022 return;
6023
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006024 for (unsigned Int = FirstPromotedIntegralType;
6025 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006026 QualType IntTy = getArithmeticType(Int);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006027 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
6028 }
6029
6030 // Extension: We also add this operator for vector types.
6031 for (BuiltinCandidateTypeSet::iterator
6032 Vec = CandidateTypes[0].vector_begin(),
6033 VecEnd = CandidateTypes[0].vector_end();
6034 Vec != VecEnd; ++Vec) {
6035 QualType VecTy = *Vec;
6036 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
6037 }
6038 }
6039
6040 // C++ [over.match.oper]p16:
6041 // For every pointer to member type T, there exist candidate operator
6042 // functions of the form
6043 //
6044 // bool operator==(T,T);
6045 // bool operator!=(T,T);
6046 void addEqualEqualOrNotEqualMemberPointerOverloads() {
6047 /// Set of (canonical) types that we've already handled.
6048 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6049
6050 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6051 for (BuiltinCandidateTypeSet::iterator
6052 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6053 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6054 MemPtr != MemPtrEnd;
6055 ++MemPtr) {
6056 // Don't add the same builtin candidate twice.
6057 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6058 continue;
6059
6060 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6061 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6062 CandidateSet);
6063 }
6064 }
6065 }
6066
6067 // C++ [over.built]p15:
6068 //
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006069 // For every T, where T is an enumeration type, a pointer type, or
6070 // std::nullptr_t, there exist candidate operator functions of the form
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006071 //
6072 // bool operator<(T, T);
6073 // bool operator>(T, T);
6074 // bool operator<=(T, T);
6075 // bool operator>=(T, T);
6076 // bool operator==(T, T);
6077 // bool operator!=(T, T);
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006078 void addRelationalPointerOrEnumeralOverloads() {
6079 // C++ [over.built]p1:
6080 // If there is a user-written candidate with the same name and parameter
6081 // types as a built-in candidate operator function, the built-in operator
6082 // function is hidden and is not included in the set of candidate
6083 // functions.
6084 //
6085 // The text is actually in a note, but if we don't implement it then we end
6086 // up with ambiguities when the user provides an overloaded operator for
6087 // an enumeration type. Note that only enumeration types have this problem,
6088 // so we track which enumeration types we've seen operators for. Also, the
6089 // only other overloaded operator with enumeration argumenst, operator=,
6090 // cannot be overloaded for enumeration types, so this is the only place
6091 // where we must suppress candidates like this.
6092 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
6093 UserDefinedBinaryOperators;
6094
6095 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6096 if (CandidateTypes[ArgIdx].enumeration_begin() !=
6097 CandidateTypes[ArgIdx].enumeration_end()) {
6098 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
6099 CEnd = CandidateSet.end();
6100 C != CEnd; ++C) {
6101 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
6102 continue;
6103
6104 QualType FirstParamType =
6105 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
6106 QualType SecondParamType =
6107 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
6108
6109 // Skip if either parameter isn't of enumeral type.
6110 if (!FirstParamType->isEnumeralType() ||
6111 !SecondParamType->isEnumeralType())
6112 continue;
6113
6114 // Add this operator to the set of known user-defined operators.
6115 UserDefinedBinaryOperators.insert(
6116 std::make_pair(S.Context.getCanonicalType(FirstParamType),
6117 S.Context.getCanonicalType(SecondParamType)));
6118 }
6119 }
6120 }
6121
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006122 /// Set of (canonical) types that we've already handled.
6123 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6124
6125 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6126 for (BuiltinCandidateTypeSet::iterator
6127 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6128 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6129 Ptr != PtrEnd; ++Ptr) {
6130 // Don't add the same builtin candidate twice.
6131 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6132 continue;
6133
6134 QualType ParamTypes[2] = { *Ptr, *Ptr };
6135 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6136 CandidateSet);
6137 }
6138 for (BuiltinCandidateTypeSet::iterator
6139 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6140 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6141 Enum != EnumEnd; ++Enum) {
6142 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
6143
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006144 // Don't add the same builtin candidate twice, or if a user defined
6145 // candidate exists.
6146 if (!AddedTypes.insert(CanonType) ||
6147 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
6148 CanonType)))
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006149 continue;
6150
6151 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006152 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6153 CandidateSet);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006154 }
Douglas Gregor84ee2ee2011-05-21 23:15:46 +00006155
6156 if (CandidateTypes[ArgIdx].hasNullPtrType()) {
6157 CanQualType NullPtrTy = S.Context.getCanonicalType(S.Context.NullPtrTy);
6158 if (AddedTypes.insert(NullPtrTy) &&
6159 !UserDefinedBinaryOperators.count(std::make_pair(NullPtrTy,
6160 NullPtrTy))) {
6161 QualType ParamTypes[2] = { NullPtrTy, NullPtrTy };
6162 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
6163 CandidateSet);
6164 }
6165 }
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006166 }
6167 }
6168
6169 // C++ [over.built]p13:
6170 //
6171 // For every cv-qualified or cv-unqualified object type T
6172 // there exist candidate operator functions of the form
6173 //
6174 // T* operator+(T*, ptrdiff_t);
6175 // T& operator[](T*, ptrdiff_t); [BELOW]
6176 // T* operator-(T*, ptrdiff_t);
6177 // T* operator+(ptrdiff_t, T*);
6178 // T& operator[](ptrdiff_t, T*); [BELOW]
6179 //
6180 // C++ [over.built]p14:
6181 //
6182 // For every T, where T is a pointer to object type, there
6183 // exist candidate operator functions of the form
6184 //
6185 // ptrdiff_t operator-(T, T);
6186 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
6187 /// Set of (canonical) types that we've already handled.
6188 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6189
6190 for (int Arg = 0; Arg < 2; ++Arg) {
6191 QualType AsymetricParamTypes[2] = {
6192 S.Context.getPointerDiffType(),
6193 S.Context.getPointerDiffType(),
6194 };
6195 for (BuiltinCandidateTypeSet::iterator
6196 Ptr = CandidateTypes[Arg].pointer_begin(),
6197 PtrEnd = CandidateTypes[Arg].pointer_end();
6198 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006199 QualType PointeeTy = (*Ptr)->getPointeeType();
6200 if (!PointeeTy->isObjectType())
6201 continue;
6202
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006203 AsymetricParamTypes[Arg] = *Ptr;
6204 if (Arg == 0 || Op == OO_Plus) {
6205 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
6206 // T* operator+(ptrdiff_t, T*);
6207 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
6208 CandidateSet);
6209 }
6210 if (Op == OO_Minus) {
6211 // ptrdiff_t operator-(T, T);
6212 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6213 continue;
6214
6215 QualType ParamTypes[2] = { *Ptr, *Ptr };
6216 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
6217 Args, 2, CandidateSet);
6218 }
6219 }
6220 }
6221 }
6222
6223 // C++ [over.built]p12:
6224 //
6225 // For every pair of promoted arithmetic types L and R, there
6226 // exist candidate operator functions of the form
6227 //
6228 // LR operator*(L, R);
6229 // LR operator/(L, R);
6230 // LR operator+(L, R);
6231 // LR operator-(L, R);
6232 // bool operator<(L, R);
6233 // bool operator>(L, R);
6234 // bool operator<=(L, R);
6235 // bool operator>=(L, R);
6236 // bool operator==(L, R);
6237 // bool operator!=(L, R);
6238 //
6239 // where LR is the result of the usual arithmetic conversions
6240 // between types L and R.
6241 //
6242 // C++ [over.built]p24:
6243 //
6244 // For every pair of promoted arithmetic types L and R, there exist
6245 // candidate operator functions of the form
6246 //
6247 // LR operator?(bool, L, R);
6248 //
6249 // where LR is the result of the usual arithmetic conversions
6250 // between types L and R.
6251 // Our candidates ignore the first parameter.
6252 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006253 if (!HasArithmeticOrEnumeralCandidateType)
6254 return;
6255
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006256 for (unsigned Left = FirstPromotedArithmeticType;
6257 Left < LastPromotedArithmeticType; ++Left) {
6258 for (unsigned Right = FirstPromotedArithmeticType;
6259 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006260 QualType LandR[2] = { getArithmeticType(Left),
6261 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006262 QualType Result =
6263 isComparison ? S.Context.BoolTy
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006264 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006265 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6266 }
6267 }
6268
6269 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
6270 // conditional operator for vector types.
6271 for (BuiltinCandidateTypeSet::iterator
6272 Vec1 = CandidateTypes[0].vector_begin(),
6273 Vec1End = CandidateTypes[0].vector_end();
6274 Vec1 != Vec1End; ++Vec1) {
6275 for (BuiltinCandidateTypeSet::iterator
6276 Vec2 = CandidateTypes[1].vector_begin(),
6277 Vec2End = CandidateTypes[1].vector_end();
6278 Vec2 != Vec2End; ++Vec2) {
6279 QualType LandR[2] = { *Vec1, *Vec2 };
6280 QualType Result = S.Context.BoolTy;
6281 if (!isComparison) {
6282 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
6283 Result = *Vec1;
6284 else
6285 Result = *Vec2;
6286 }
6287
6288 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6289 }
6290 }
6291 }
6292
6293 // C++ [over.built]p17:
6294 //
6295 // For every pair of promoted integral types L and R, there
6296 // exist candidate operator functions of the form
6297 //
6298 // LR operator%(L, R);
6299 // LR operator&(L, R);
6300 // LR operator^(L, R);
6301 // LR operator|(L, R);
6302 // L operator<<(L, R);
6303 // L operator>>(L, R);
6304 //
6305 // where LR is the result of the usual arithmetic conversions
6306 // between types L and R.
6307 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006308 if (!HasArithmeticOrEnumeralCandidateType)
6309 return;
6310
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006311 for (unsigned Left = FirstPromotedIntegralType;
6312 Left < LastPromotedIntegralType; ++Left) {
6313 for (unsigned Right = FirstPromotedIntegralType;
6314 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruth6d695582010-12-12 10:35:00 +00006315 QualType LandR[2] = { getArithmeticType(Left),
6316 getArithmeticType(Right) };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006317 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
6318 ? LandR[0]
Chandler Carruth38ca8d12010-12-12 09:59:53 +00006319 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006320 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
6321 }
6322 }
6323 }
6324
6325 // C++ [over.built]p20:
6326 //
6327 // For every pair (T, VQ), where T is an enumeration or
6328 // pointer to member type and VQ is either volatile or
6329 // empty, there exist candidate operator functions of the form
6330 //
6331 // VQ T& operator=(VQ T&, T);
6332 void addAssignmentMemberPointerOrEnumeralOverloads() {
6333 /// Set of (canonical) types that we've already handled.
6334 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6335
6336 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6337 for (BuiltinCandidateTypeSet::iterator
6338 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6339 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6340 Enum != EnumEnd; ++Enum) {
6341 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6342 continue;
6343
6344 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
6345 CandidateSet);
6346 }
6347
6348 for (BuiltinCandidateTypeSet::iterator
6349 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6350 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6351 MemPtr != MemPtrEnd; ++MemPtr) {
6352 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6353 continue;
6354
6355 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
6356 CandidateSet);
6357 }
6358 }
6359 }
6360
6361 // C++ [over.built]p19:
6362 //
6363 // For every pair (T, VQ), where T is any type and VQ is either
6364 // volatile or empty, there exist candidate operator functions
6365 // of the form
6366 //
6367 // T*VQ& operator=(T*VQ&, T*);
6368 //
6369 // C++ [over.built]p21:
6370 //
6371 // For every pair (T, VQ), where T is a cv-qualified or
6372 // cv-unqualified object type and VQ is either volatile or
6373 // empty, there exist candidate operator functions of the form
6374 //
6375 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
6376 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
6377 void addAssignmentPointerOverloads(bool isEqualOp) {
6378 /// Set of (canonical) types that we've already handled.
6379 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6380
6381 for (BuiltinCandidateTypeSet::iterator
6382 Ptr = CandidateTypes[0].pointer_begin(),
6383 PtrEnd = CandidateTypes[0].pointer_end();
6384 Ptr != PtrEnd; ++Ptr) {
6385 // If this is operator=, keep track of the builtin candidates we added.
6386 if (isEqualOp)
6387 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006388 else if (!(*Ptr)->getPointeeType()->isObjectType())
6389 continue;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006390
6391 // non-volatile version
6392 QualType ParamTypes[2] = {
6393 S.Context.getLValueReferenceType(*Ptr),
6394 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
6395 };
6396 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6397 /*IsAssigmentOperator=*/ isEqualOp);
6398
6399 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6400 VisibleTypeConversionsQuals.hasVolatile()) {
6401 // volatile version
6402 ParamTypes[0] =
6403 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
6404 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6405 /*IsAssigmentOperator=*/isEqualOp);
6406 }
6407 }
6408
6409 if (isEqualOp) {
6410 for (BuiltinCandidateTypeSet::iterator
6411 Ptr = CandidateTypes[1].pointer_begin(),
6412 PtrEnd = CandidateTypes[1].pointer_end();
6413 Ptr != PtrEnd; ++Ptr) {
6414 // Make sure we don't add the same candidate twice.
6415 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6416 continue;
6417
Chandler Carruth6df868e2010-12-12 08:17:55 +00006418 QualType ParamTypes[2] = {
6419 S.Context.getLValueReferenceType(*Ptr),
6420 *Ptr,
6421 };
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006422
6423 // non-volatile version
6424 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6425 /*IsAssigmentOperator=*/true);
6426
6427 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
6428 VisibleTypeConversionsQuals.hasVolatile()) {
6429 // volatile version
6430 ParamTypes[0] =
6431 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth6df868e2010-12-12 08:17:55 +00006432 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6433 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006434 }
6435 }
6436 }
6437 }
6438
6439 // C++ [over.built]p18:
6440 //
6441 // For every triple (L, VQ, R), where L is an arithmetic type,
6442 // VQ is either volatile or empty, and R is a promoted
6443 // arithmetic type, there exist candidate operator functions of
6444 // the form
6445 //
6446 // VQ L& operator=(VQ L&, R);
6447 // VQ L& operator*=(VQ L&, R);
6448 // VQ L& operator/=(VQ L&, R);
6449 // VQ L& operator+=(VQ L&, R);
6450 // VQ L& operator-=(VQ L&, R);
6451 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth6a577462010-12-13 01:44:01 +00006452 if (!HasArithmeticOrEnumeralCandidateType)
6453 return;
6454
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006455 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
6456 for (unsigned Right = FirstPromotedArithmeticType;
6457 Right < LastPromotedArithmeticType; ++Right) {
6458 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00006459 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006460
6461 // Add this built-in operator as a candidate (VQ is empty).
6462 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006463 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006464 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6465 /*IsAssigmentOperator=*/isEqualOp);
6466
6467 // Add this built-in operator as a candidate (VQ is 'volatile').
6468 if (VisibleTypeConversionsQuals.hasVolatile()) {
6469 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006470 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006471 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006472 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6473 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006474 /*IsAssigmentOperator=*/isEqualOp);
6475 }
6476 }
6477 }
6478
6479 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
6480 for (BuiltinCandidateTypeSet::iterator
6481 Vec1 = CandidateTypes[0].vector_begin(),
6482 Vec1End = CandidateTypes[0].vector_end();
6483 Vec1 != Vec1End; ++Vec1) {
6484 for (BuiltinCandidateTypeSet::iterator
6485 Vec2 = CandidateTypes[1].vector_begin(),
6486 Vec2End = CandidateTypes[1].vector_end();
6487 Vec2 != Vec2End; ++Vec2) {
6488 QualType ParamTypes[2];
6489 ParamTypes[1] = *Vec2;
6490 // Add this built-in operator as a candidate (VQ is empty).
6491 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
6492 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
6493 /*IsAssigmentOperator=*/isEqualOp);
6494
6495 // Add this built-in operator as a candidate (VQ is 'volatile').
6496 if (VisibleTypeConversionsQuals.hasVolatile()) {
6497 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
6498 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth6df868e2010-12-12 08:17:55 +00006499 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6500 CandidateSet,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006501 /*IsAssigmentOperator=*/isEqualOp);
6502 }
6503 }
6504 }
6505 }
6506
6507 // C++ [over.built]p22:
6508 //
6509 // For every triple (L, VQ, R), where L is an integral type, VQ
6510 // is either volatile or empty, and R is a promoted integral
6511 // type, there exist candidate operator functions of the form
6512 //
6513 // VQ L& operator%=(VQ L&, R);
6514 // VQ L& operator<<=(VQ L&, R);
6515 // VQ L& operator>>=(VQ L&, R);
6516 // VQ L& operator&=(VQ L&, R);
6517 // VQ L& operator^=(VQ L&, R);
6518 // VQ L& operator|=(VQ L&, R);
6519 void addAssignmentIntegralOverloads() {
Chandler Carruth6a577462010-12-13 01:44:01 +00006520 if (!HasArithmeticOrEnumeralCandidateType)
6521 return;
6522
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006523 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
6524 for (unsigned Right = FirstPromotedIntegralType;
6525 Right < LastPromotedIntegralType; ++Right) {
6526 QualType ParamTypes[2];
Chandler Carruth6d695582010-12-12 10:35:00 +00006527 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006528
6529 // Add this built-in operator as a candidate (VQ is empty).
6530 ParamTypes[0] =
Chandler Carruth6d695582010-12-12 10:35:00 +00006531 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006532 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
6533 if (VisibleTypeConversionsQuals.hasVolatile()) {
6534 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruth6d695582010-12-12 10:35:00 +00006535 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006536 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
6537 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
6538 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
6539 CandidateSet);
6540 }
6541 }
6542 }
6543 }
6544
6545 // C++ [over.operator]p23:
6546 //
6547 // There also exist candidate operator functions of the form
6548 //
6549 // bool operator!(bool);
6550 // bool operator&&(bool, bool);
6551 // bool operator||(bool, bool);
6552 void addExclaimOverload() {
6553 QualType ParamTy = S.Context.BoolTy;
6554 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
6555 /*IsAssignmentOperator=*/false,
6556 /*NumContextualBoolArguments=*/1);
6557 }
6558 void addAmpAmpOrPipePipeOverload() {
6559 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
6560 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
6561 /*IsAssignmentOperator=*/false,
6562 /*NumContextualBoolArguments=*/2);
6563 }
6564
6565 // C++ [over.built]p13:
6566 //
6567 // For every cv-qualified or cv-unqualified object type T there
6568 // exist candidate operator functions of the form
6569 //
6570 // T* operator+(T*, ptrdiff_t); [ABOVE]
6571 // T& operator[](T*, ptrdiff_t);
6572 // T* operator-(T*, ptrdiff_t); [ABOVE]
6573 // T* operator+(ptrdiff_t, T*); [ABOVE]
6574 // T& operator[](ptrdiff_t, T*);
6575 void addSubscriptOverloads() {
6576 for (BuiltinCandidateTypeSet::iterator
6577 Ptr = CandidateTypes[0].pointer_begin(),
6578 PtrEnd = CandidateTypes[0].pointer_end();
6579 Ptr != PtrEnd; ++Ptr) {
6580 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
6581 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006582 if (!PointeeType->isObjectType())
6583 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006584
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006585 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6586
6587 // T& operator[](T*, ptrdiff_t)
6588 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6589 }
6590
6591 for (BuiltinCandidateTypeSet::iterator
6592 Ptr = CandidateTypes[1].pointer_begin(),
6593 PtrEnd = CandidateTypes[1].pointer_end();
6594 Ptr != PtrEnd; ++Ptr) {
6595 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
6596 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor2fdc5e82011-01-05 00:13:17 +00006597 if (!PointeeType->isObjectType())
6598 continue;
6599
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006600 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
6601
6602 // T& operator[](ptrdiff_t, T*)
6603 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6604 }
6605 }
6606
6607 // C++ [over.built]p11:
6608 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
6609 // C1 is the same type as C2 or is a derived class of C2, T is an object
6610 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
6611 // there exist candidate operator functions of the form
6612 //
6613 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
6614 //
6615 // where CV12 is the union of CV1 and CV2.
6616 void addArrowStarOverloads() {
6617 for (BuiltinCandidateTypeSet::iterator
6618 Ptr = CandidateTypes[0].pointer_begin(),
6619 PtrEnd = CandidateTypes[0].pointer_end();
6620 Ptr != PtrEnd; ++Ptr) {
6621 QualType C1Ty = (*Ptr);
6622 QualType C1;
6623 QualifierCollector Q1;
6624 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
6625 if (!isa<RecordType>(C1))
6626 continue;
6627 // heuristic to reduce number of builtin candidates in the set.
6628 // Add volatile/restrict version only if there are conversions to a
6629 // volatile/restrict type.
6630 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
6631 continue;
6632 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
6633 continue;
6634 for (BuiltinCandidateTypeSet::iterator
6635 MemPtr = CandidateTypes[1].member_pointer_begin(),
6636 MemPtrEnd = CandidateTypes[1].member_pointer_end();
6637 MemPtr != MemPtrEnd; ++MemPtr) {
6638 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
6639 QualType C2 = QualType(mptr->getClass(), 0);
6640 C2 = C2.getUnqualifiedType();
6641 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
6642 break;
6643 QualType ParamTypes[2] = { *Ptr, *MemPtr };
6644 // build CV12 T&
6645 QualType T = mptr->getPointeeType();
6646 if (!VisibleTypeConversionsQuals.hasVolatile() &&
6647 T.isVolatileQualified())
6648 continue;
6649 if (!VisibleTypeConversionsQuals.hasRestrict() &&
6650 T.isRestrictQualified())
6651 continue;
6652 T = Q1.apply(S.Context, T);
6653 QualType ResultTy = S.Context.getLValueReferenceType(T);
6654 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
6655 }
6656 }
6657 }
6658
6659 // Note that we don't consider the first argument, since it has been
6660 // contextually converted to bool long ago. The candidates below are
6661 // therefore added as binary.
6662 //
6663 // C++ [over.built]p25:
6664 // For every type T, where T is a pointer, pointer-to-member, or scoped
6665 // enumeration type, there exist candidate operator functions of the form
6666 //
6667 // T operator?(bool, T, T);
6668 //
6669 void addConditionalOperatorOverloads() {
6670 /// Set of (canonical) types that we've already handled.
6671 llvm::SmallPtrSet<QualType, 8> AddedTypes;
6672
6673 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
6674 for (BuiltinCandidateTypeSet::iterator
6675 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
6676 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
6677 Ptr != PtrEnd; ++Ptr) {
6678 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
6679 continue;
6680
6681 QualType ParamTypes[2] = { *Ptr, *Ptr };
6682 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
6683 }
6684
6685 for (BuiltinCandidateTypeSet::iterator
6686 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
6687 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
6688 MemPtr != MemPtrEnd; ++MemPtr) {
6689 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
6690 continue;
6691
6692 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
6693 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
6694 }
6695
6696 if (S.getLangOptions().CPlusPlus0x) {
6697 for (BuiltinCandidateTypeSet::iterator
6698 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
6699 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
6700 Enum != EnumEnd; ++Enum) {
6701 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
6702 continue;
6703
6704 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
6705 continue;
6706
6707 QualType ParamTypes[2] = { *Enum, *Enum };
6708 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
6709 }
6710 }
6711 }
6712 }
6713};
6714
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006715} // end anonymous namespace
6716
6717/// AddBuiltinOperatorCandidates - Add the appropriate built-in
6718/// operator overloads to the candidate set (C++ [over.built]), based
6719/// on the operator @p Op and the arguments given. For example, if the
6720/// operator is a binary '+', this routine might add "int
6721/// operator+(int, int)" to cover integer addition.
6722void
6723Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
6724 SourceLocation OpLoc,
6725 Expr **Args, unsigned NumArgs,
6726 OverloadCandidateSet& CandidateSet) {
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006727 // Find all of the types that the arguments can convert to, but only
6728 // if the operator we're looking at has built-in operator candidates
Chandler Carruth6a577462010-12-13 01:44:01 +00006729 // that make use of these types. Also record whether we encounter non-record
6730 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahaniana9cca892009-10-15 17:14:05 +00006731 Qualifiers VisibleTypeConversionsQuals;
6732 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanian8621d012009-10-19 21:30:45 +00006733 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
6734 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth6a577462010-12-13 01:44:01 +00006735
6736 bool HasNonRecordCandidateType = false;
6737 bool HasArithmeticOrEnumeralCandidateType = false;
Chris Lattner5f9e2722011-07-23 10:55:15 +00006738 SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
Douglas Gregorfec56e72010-11-03 17:00:07 +00006739 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
6740 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
6741 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
6742 OpLoc,
6743 true,
6744 (Op == OO_Exclaim ||
6745 Op == OO_AmpAmp ||
6746 Op == OO_PipePipe),
6747 VisibleTypeConversionsQuals);
Chandler Carruth6a577462010-12-13 01:44:01 +00006748 HasNonRecordCandidateType = HasNonRecordCandidateType ||
6749 CandidateTypes[ArgIdx].hasNonRecordTypes();
6750 HasArithmeticOrEnumeralCandidateType =
6751 HasArithmeticOrEnumeralCandidateType ||
6752 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorfec56e72010-11-03 17:00:07 +00006753 }
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006754
Chandler Carruth6a577462010-12-13 01:44:01 +00006755 // Exit early when no non-record types have been added to the candidate set
6756 // for any of the arguments to the operator.
Douglas Gregor25aaff92011-10-10 14:05:31 +00006757 //
6758 // We can't exit early for !, ||, or &&, since there we have always have
6759 // 'bool' overloads.
6760 if (!HasNonRecordCandidateType &&
6761 !(Op == OO_Exclaim || Op == OO_AmpAmp || Op == OO_PipePipe))
Chandler Carruth6a577462010-12-13 01:44:01 +00006762 return;
6763
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006764 // Setup an object to manage the common state for building overloads.
6765 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
6766 VisibleTypeConversionsQuals,
Chandler Carruth6a577462010-12-13 01:44:01 +00006767 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006768 CandidateTypes, CandidateSet);
6769
6770 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006771 switch (Op) {
6772 case OO_None:
6773 case NUM_OVERLOADED_OPERATORS:
David Blaikieb219cfc2011-09-23 05:06:16 +00006774 llvm_unreachable("Expected an overloaded operator");
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006775
Chandler Carruthabb71842010-12-12 08:51:33 +00006776 case OO_New:
6777 case OO_Delete:
6778 case OO_Array_New:
6779 case OO_Array_Delete:
6780 case OO_Call:
David Blaikieb219cfc2011-09-23 05:06:16 +00006781 llvm_unreachable(
6782 "Special operators don't use AddBuiltinOperatorCandidates");
Chandler Carruthabb71842010-12-12 08:51:33 +00006783
6784 case OO_Comma:
6785 case OO_Arrow:
6786 // C++ [over.match.oper]p3:
6787 // -- For the operator ',', the unary operator '&', or the
6788 // operator '->', the built-in candidates set is empty.
Douglas Gregor74253732008-11-19 15:42:04 +00006789 break;
6790
6791 case OO_Plus: // '+' is either unary or binary
Chandler Carruth32fe0d02010-12-12 08:41:34 +00006792 if (NumArgs == 1)
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006793 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth32fe0d02010-12-12 08:41:34 +00006794 // Fall through.
Douglas Gregor74253732008-11-19 15:42:04 +00006795
6796 case OO_Minus: // '-' is either unary or binary
Chandler Carruthfe622742010-12-12 08:39:38 +00006797 if (NumArgs == 1) {
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006798 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00006799 } else {
6800 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
6801 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6802 }
Douglas Gregor74253732008-11-19 15:42:04 +00006803 break;
6804
Chandler Carruthabb71842010-12-12 08:51:33 +00006805 case OO_Star: // '*' is either unary or binary
Douglas Gregor74253732008-11-19 15:42:04 +00006806 if (NumArgs == 1)
Chandler Carruthabb71842010-12-12 08:51:33 +00006807 OpBuilder.addUnaryStarPointerOverloads();
6808 else
6809 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6810 break;
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006811
Chandler Carruthabb71842010-12-12 08:51:33 +00006812 case OO_Slash:
6813 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruthc1409462010-12-12 08:45:02 +00006814 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006815
6816 case OO_PlusPlus:
6817 case OO_MinusMinus:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006818 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
6819 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregor74253732008-11-19 15:42:04 +00006820 break;
6821
Douglas Gregor19b7b152009-08-24 13:43:27 +00006822 case OO_EqualEqual:
6823 case OO_ExclaimEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006824 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00006825 // Fall through.
Chandler Carruthc1409462010-12-12 08:45:02 +00006826
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006827 case OO_Less:
6828 case OO_Greater:
6829 case OO_LessEqual:
6830 case OO_GreaterEqual:
Chandler Carruth7b80b4b2010-12-12 09:14:11 +00006831 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruthdaf55d32010-12-12 08:32:28 +00006832 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
6833 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006834
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006835 case OO_Percent:
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006836 case OO_Caret:
6837 case OO_Pipe:
6838 case OO_LessLess:
6839 case OO_GreaterGreater:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006840 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006841 break;
6842
Chandler Carruthabb71842010-12-12 08:51:33 +00006843 case OO_Amp: // '&' is either unary or binary
6844 if (NumArgs == 1)
6845 // C++ [over.match.oper]p3:
6846 // -- For the operator ',', the unary operator '&', or the
6847 // operator '->', the built-in candidates set is empty.
6848 break;
6849
6850 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
6851 break;
6852
6853 case OO_Tilde:
6854 OpBuilder.addUnaryTildePromotedIntegralOverloads();
6855 break;
6856
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006857 case OO_Equal:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006858 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregor26bcf672010-05-19 03:21:00 +00006859 // Fall through.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006860
6861 case OO_PlusEqual:
6862 case OO_MinusEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006863 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006864 // Fall through.
6865
6866 case OO_StarEqual:
6867 case OO_SlashEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006868 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006869 break;
6870
6871 case OO_PercentEqual:
6872 case OO_LessLessEqual:
6873 case OO_GreaterGreaterEqual:
6874 case OO_AmpEqual:
6875 case OO_CaretEqual:
6876 case OO_PipeEqual:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006877 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006878 break;
6879
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006880 case OO_Exclaim:
6881 OpBuilder.addExclaimOverload();
Douglas Gregor74253732008-11-19 15:42:04 +00006882 break;
Douglas Gregor74253732008-11-19 15:42:04 +00006883
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006884 case OO_AmpAmp:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006885 case OO_PipePipe:
6886 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006887 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006888
6889 case OO_Subscript:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006890 OpBuilder.addSubscriptOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006891 break;
6892
6893 case OO_ArrowStar:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006894 OpBuilder.addArrowStarOverloads();
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006895 break;
Sebastian Redl3201f6b2009-04-16 17:51:27 +00006896
6897 case OO_Conditional:
Chandler Carruth3a0f3ef2010-12-12 08:11:30 +00006898 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthfe622742010-12-12 08:39:38 +00006899 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
6900 break;
Douglas Gregoreb8f3062008-11-12 17:17:38 +00006901 }
6902}
6903
Douglas Gregorfa047642009-02-04 00:32:51 +00006904/// \brief Add function candidates found via argument-dependent lookup
6905/// to the set of overloading candidates.
6906///
6907/// This routine performs argument-dependent name lookup based on the
6908/// given function name (which may also be an operator name) and adds
6909/// all of the overload candidates found by ADL to the overload
6910/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump1eb44332009-09-09 15:08:12 +00006911void
Douglas Gregorfa047642009-02-04 00:32:51 +00006912Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall6e266892010-01-26 03:27:55 +00006913 bool Operator,
Douglas Gregorfa047642009-02-04 00:32:51 +00006914 Expr **Args, unsigned NumArgs,
Douglas Gregor67714232011-03-03 02:41:12 +00006915 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006916 OverloadCandidateSet& CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00006917 bool PartialOverloading,
6918 bool StdNamespaceIsAssociated) {
John McCall7edb5fd2010-01-26 07:16:45 +00006919 ADLResult Fns;
Douglas Gregorfa047642009-02-04 00:32:51 +00006920
John McCalla113e722010-01-26 06:04:06 +00006921 // FIXME: This approach for uniquing ADL results (and removing
6922 // redundant candidates from the set) relies on pointer-equality,
6923 // which means we need to key off the canonical decl. However,
6924 // always going back to the canonical decl might not get us the
6925 // right set of default arguments. What default arguments are
6926 // we supposed to consider on ADL candidates, anyway?
6927
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006928 // FIXME: Pass in the explicit template arguments?
Richard Smithad762fc2011-04-14 22:09:26 +00006929 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns,
6930 StdNamespaceIsAssociated);
Douglas Gregorfa047642009-02-04 00:32:51 +00006931
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006932 // Erase all of the candidates we already knew about.
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006933 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
6934 CandEnd = CandidateSet.end();
6935 Cand != CandEnd; ++Cand)
Douglas Gregor364e0212009-06-27 21:05:07 +00006936 if (Cand->Function) {
John McCall7edb5fd2010-01-26 07:16:45 +00006937 Fns.erase(Cand->Function);
Douglas Gregor364e0212009-06-27 21:05:07 +00006938 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall7edb5fd2010-01-26 07:16:45 +00006939 Fns.erase(FunTmpl);
Douglas Gregor364e0212009-06-27 21:05:07 +00006940 }
Douglas Gregor3fd95ce2009-03-13 00:33:25 +00006941
6942 // For each of the ADL candidates we found, add it to the overload
6943 // set.
John McCall7edb5fd2010-01-26 07:16:45 +00006944 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCall9aa472c2010-03-19 07:35:19 +00006945 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall6e266892010-01-26 03:27:55 +00006946 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCalld5532b62009-11-23 01:53:49 +00006947 if (ExplicitTemplateArgs)
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006948 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00006949
John McCall9aa472c2010-03-19 07:35:19 +00006950 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00006951 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00006952 } else
John McCall6e266892010-01-26 03:27:55 +00006953 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCall9aa472c2010-03-19 07:35:19 +00006954 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor6db8ed42009-06-30 23:57:56 +00006955 Args, NumArgs, CandidateSet);
Douglas Gregor364e0212009-06-27 21:05:07 +00006956 }
Douglas Gregorfa047642009-02-04 00:32:51 +00006957}
6958
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006959/// isBetterOverloadCandidate - Determines whether the first overload
6960/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump1eb44332009-09-09 15:08:12 +00006961bool
John McCall120d63c2010-08-24 20:38:10 +00006962isBetterOverloadCandidate(Sema &S,
Nick Lewycky7663f392010-11-20 01:29:55 +00006963 const OverloadCandidate &Cand1,
6964 const OverloadCandidate &Cand2,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00006965 SourceLocation Loc,
6966 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006967 // Define viable functions to be better candidates than non-viable
6968 // functions.
6969 if (!Cand2.Viable)
6970 return Cand1.Viable;
6971 else if (!Cand1.Viable)
6972 return false;
6973
Douglas Gregor88a35142008-12-22 05:46:06 +00006974 // C++ [over.match.best]p1:
6975 //
6976 // -- if F is a static member function, ICS1(F) is defined such
6977 // that ICS1(F) is neither better nor worse than ICS1(G) for
6978 // any function G, and, symmetrically, ICS1(G) is neither
6979 // better nor worse than ICS1(F).
6980 unsigned StartArg = 0;
6981 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
6982 StartArg = 1;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006983
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006984 // C++ [over.match.best]p1:
Mike Stump1eb44332009-09-09 15:08:12 +00006985 // A viable function F1 is defined to be a better function than another
6986 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregor3e15cc32009-07-07 23:38:56 +00006987 // conversion sequence than ICSi(F2), and then...
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006988 unsigned NumArgs = Cand1.Conversions.size();
6989 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
6990 bool HasBetterConversion = false;
Douglas Gregor88a35142008-12-22 05:46:06 +00006991 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall120d63c2010-08-24 20:38:10 +00006992 switch (CompareImplicitConversionSequences(S,
6993 Cand1.Conversions[ArgIdx],
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00006994 Cand2.Conversions[ArgIdx])) {
6995 case ImplicitConversionSequence::Better:
6996 // Cand1 has a better conversion sequence.
6997 HasBetterConversion = true;
6998 break;
6999
7000 case ImplicitConversionSequence::Worse:
7001 // Cand1 can't be better than Cand2.
7002 return false;
7003
7004 case ImplicitConversionSequence::Indistinguishable:
7005 // Do nothing.
7006 break;
7007 }
7008 }
7009
Mike Stump1eb44332009-09-09 15:08:12 +00007010 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007011 // ICSj(F2), or, if not that,
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007012 if (HasBetterConversion)
7013 return true;
7014
Mike Stump1eb44332009-09-09 15:08:12 +00007015 // - F1 is a non-template function and F2 is a function template
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007016 // specialization, or, if not that,
Douglas Gregorccd47132010-06-08 21:03:17 +00007017 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007018 Cand2.Function && Cand2.Function->getPrimaryTemplate())
7019 return true;
Mike Stump1eb44332009-09-09 15:08:12 +00007020
7021 // -- F1 and F2 are function template specializations, and the function
7022 // template for F1 is more specialized than the template for F2
7023 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregor3e15cc32009-07-07 23:38:56 +00007024 // if not that,
Douglas Gregor1f561c12009-08-02 23:46:29 +00007025 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregordfc331e2011-01-19 23:54:39 +00007026 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007027 if (FunctionTemplateDecl *BetterTemplate
John McCall120d63c2010-08-24 20:38:10 +00007028 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
7029 Cand2.Function->getPrimaryTemplate(),
7030 Loc,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007031 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregor5c7bf422011-01-11 17:34:58 +00007032 : TPOC_Call,
Douglas Gregordfc331e2011-01-19 23:54:39 +00007033 Cand1.ExplicitCallArguments))
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00007034 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregordfc331e2011-01-19 23:54:39 +00007035 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007036
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007037 // -- the context is an initialization by user-defined conversion
7038 // (see 8.5, 13.3.1.5) and the standard conversion sequence
7039 // from the return type of F1 to the destination type (i.e.,
7040 // the type of the entity being initialized) is a better
7041 // conversion sequence than the standard conversion sequence
7042 // from the return type of F2 to the destination type.
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007043 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump1eb44332009-09-09 15:08:12 +00007044 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007045 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall120d63c2010-08-24 20:38:10 +00007046 switch (CompareStandardConversionSequences(S,
7047 Cand1.FinalConversion,
Douglas Gregorf1991ea2008-11-07 22:36:19 +00007048 Cand2.FinalConversion)) {
7049 case ImplicitConversionSequence::Better:
7050 // Cand1 has a better conversion sequence.
7051 return true;
7052
7053 case ImplicitConversionSequence::Worse:
7054 // Cand1 can't be better than Cand2.
7055 return false;
7056
7057 case ImplicitConversionSequence::Indistinguishable:
7058 // Do nothing
7059 break;
7060 }
7061 }
7062
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007063 return false;
7064}
7065
Mike Stump1eb44332009-09-09 15:08:12 +00007066/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregore0762c92009-06-19 23:52:42 +00007067/// within an overload candidate set.
7068///
7069/// \param CandidateSet the set of candidate functions.
7070///
7071/// \param Loc the location of the function name (or operator symbol) for
7072/// which overload resolution occurs.
7073///
Mike Stump1eb44332009-09-09 15:08:12 +00007074/// \param Best f overload resolution was successful or found a deleted
Douglas Gregore0762c92009-06-19 23:52:42 +00007075/// function, Best points to the candidate function found.
7076///
7077/// \returns The result of overload resolution.
John McCall120d63c2010-08-24 20:38:10 +00007078OverloadingResult
7079OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky7663f392010-11-20 01:29:55 +00007080 iterator &Best,
Chandler Carruth25ca4212011-02-25 19:41:05 +00007081 bool UserDefinedConversion) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007082 // Find the best viable function.
John McCall120d63c2010-08-24 20:38:10 +00007083 Best = end();
7084 for (iterator Cand = begin(); Cand != end(); ++Cand) {
7085 if (Cand->Viable)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007086 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007087 UserDefinedConversion))
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007088 Best = Cand;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007089 }
7090
7091 // If we didn't find any viable functions, abort.
John McCall120d63c2010-08-24 20:38:10 +00007092 if (Best == end())
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007093 return OR_No_Viable_Function;
7094
7095 // Make sure that this function is better than every other viable
7096 // function. If not, we have an ambiguity.
John McCall120d63c2010-08-24 20:38:10 +00007097 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump1eb44332009-09-09 15:08:12 +00007098 if (Cand->Viable &&
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007099 Cand != Best &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007100 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
Douglas Gregor8fcc5162010-09-12 08:07:23 +00007101 UserDefinedConversion)) {
John McCall120d63c2010-08-24 20:38:10 +00007102 Best = end();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007103 return OR_Ambiguous;
Douglas Gregor106c6eb2008-11-19 22:57:39 +00007104 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007105 }
Mike Stump1eb44332009-09-09 15:08:12 +00007106
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007107 // Best is the best viable function.
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007108 if (Best->Function &&
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007109 (Best->Function->isDeleted() ||
7110 S.isFunctionConsideredUnavailable(Best->Function)))
Douglas Gregor48f3bb92009-02-18 21:56:37 +00007111 return OR_Deleted;
7112
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007113 return OR_Success;
7114}
7115
John McCall3c80f572010-01-12 02:15:36 +00007116namespace {
7117
7118enum OverloadCandidateKind {
7119 oc_function,
7120 oc_method,
7121 oc_constructor,
John McCall220ccbf2010-01-13 00:25:19 +00007122 oc_function_template,
7123 oc_method_template,
7124 oc_constructor_template,
John McCall3c80f572010-01-12 02:15:36 +00007125 oc_implicit_default_constructor,
7126 oc_implicit_copy_constructor,
Sean Hunt82713172011-05-25 23:16:36 +00007127 oc_implicit_move_constructor,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007128 oc_implicit_copy_assignment,
Sean Hunt82713172011-05-25 23:16:36 +00007129 oc_implicit_move_assignment,
Sebastian Redlf677ea32011-02-05 19:23:19 +00007130 oc_implicit_inherited_constructor
John McCall3c80f572010-01-12 02:15:36 +00007131};
7132
John McCall220ccbf2010-01-13 00:25:19 +00007133OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
7134 FunctionDecl *Fn,
7135 std::string &Description) {
7136 bool isTemplate = false;
7137
7138 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
7139 isTemplate = true;
7140 Description = S.getTemplateArgumentBindingsText(
7141 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
7142 }
John McCallb1622a12010-01-06 09:43:14 +00007143
7144 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall3c80f572010-01-12 02:15:36 +00007145 if (!Ctor->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007146 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007147
Sebastian Redlf677ea32011-02-05 19:23:19 +00007148 if (Ctor->getInheritedConstructor())
7149 return oc_implicit_inherited_constructor;
7150
Sean Hunt82713172011-05-25 23:16:36 +00007151 if (Ctor->isDefaultConstructor())
7152 return oc_implicit_default_constructor;
7153
7154 if (Ctor->isMoveConstructor())
7155 return oc_implicit_move_constructor;
7156
7157 assert(Ctor->isCopyConstructor() &&
7158 "unexpected sort of implicit constructor");
7159 return oc_implicit_copy_constructor;
John McCallb1622a12010-01-06 09:43:14 +00007160 }
7161
7162 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
7163 // This actually gets spelled 'candidate function' for now, but
7164 // it doesn't hurt to split it out.
John McCall3c80f572010-01-12 02:15:36 +00007165 if (!Meth->isImplicit())
John McCall220ccbf2010-01-13 00:25:19 +00007166 return isTemplate ? oc_method_template : oc_method;
John McCallb1622a12010-01-06 09:43:14 +00007167
Sean Hunt82713172011-05-25 23:16:36 +00007168 if (Meth->isMoveAssignmentOperator())
7169 return oc_implicit_move_assignment;
7170
Douglas Gregor3e9438b2010-09-27 22:37:28 +00007171 assert(Meth->isCopyAssignmentOperator()
John McCallb1622a12010-01-06 09:43:14 +00007172 && "implicit method is not copy assignment operator?");
John McCall3c80f572010-01-12 02:15:36 +00007173 return oc_implicit_copy_assignment;
7174 }
7175
John McCall220ccbf2010-01-13 00:25:19 +00007176 return isTemplate ? oc_function_template : oc_function;
John McCall3c80f572010-01-12 02:15:36 +00007177}
7178
Sebastian Redlf677ea32011-02-05 19:23:19 +00007179void MaybeEmitInheritedConstructorNote(Sema &S, FunctionDecl *Fn) {
7180 const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn);
7181 if (!Ctor) return;
7182
7183 Ctor = Ctor->getInheritedConstructor();
7184 if (!Ctor) return;
7185
7186 S.Diag(Ctor->getLocation(), diag::note_ovl_candidate_inherited_constructor);
7187}
7188
John McCall3c80f572010-01-12 02:15:36 +00007189} // end anonymous namespace
7190
7191// Notes the location of an overload candidate.
Richard Trieu6efd4c52011-11-23 22:32:32 +00007192void Sema::NoteOverloadCandidate(FunctionDecl *Fn, QualType DestType) {
John McCall220ccbf2010-01-13 00:25:19 +00007193 std::string FnDesc;
7194 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
Richard Trieu6efd4c52011-11-23 22:32:32 +00007195 PartialDiagnostic PD = PDiag(diag::note_ovl_candidate)
7196 << (unsigned) K << FnDesc;
7197 HandleFunctionTypeMismatch(PD, Fn->getType(), DestType);
7198 Diag(Fn->getLocation(), PD);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007199 MaybeEmitInheritedConstructorNote(*this, Fn);
John McCallb1622a12010-01-06 09:43:14 +00007200}
7201
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007202//Notes the location of all overload candidates designated through
7203// OverloadedExpr
Richard Trieu6efd4c52011-11-23 22:32:32 +00007204void Sema::NoteAllOverloadCandidates(Expr* OverloadedExpr, QualType DestType) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007205 assert(OverloadedExpr->getType() == Context.OverloadTy);
7206
7207 OverloadExpr::FindResult Ovl = OverloadExpr::find(OverloadedExpr);
7208 OverloadExpr *OvlExpr = Ovl.Expression;
7209
7210 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7211 IEnd = OvlExpr->decls_end();
7212 I != IEnd; ++I) {
7213 if (FunctionTemplateDecl *FunTmpl =
7214 dyn_cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007215 NoteOverloadCandidate(FunTmpl->getTemplatedDecl(), DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007216 } else if (FunctionDecl *Fun
7217 = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()) ) {
Richard Trieu6efd4c52011-11-23 22:32:32 +00007218 NoteOverloadCandidate(Fun, DestType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00007219 }
7220 }
7221}
7222
John McCall1d318332010-01-12 00:44:57 +00007223/// Diagnoses an ambiguous conversion. The partial diagnostic is the
7224/// "lead" diagnostic; it will be given two arguments, the source and
7225/// target types of the conversion.
John McCall120d63c2010-08-24 20:38:10 +00007226void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
7227 Sema &S,
7228 SourceLocation CaretLoc,
7229 const PartialDiagnostic &PDiag) const {
7230 S.Diag(CaretLoc, PDiag)
7231 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall1d318332010-01-12 00:44:57 +00007232 for (AmbiguousConversionSequence::const_iterator
John McCall120d63c2010-08-24 20:38:10 +00007233 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
7234 S.NoteOverloadCandidate(*I);
John McCall1d318332010-01-12 00:44:57 +00007235 }
John McCall81201622010-01-08 04:41:39 +00007236}
7237
John McCall1d318332010-01-12 00:44:57 +00007238namespace {
7239
John McCalladbb8f82010-01-13 09:16:55 +00007240void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
7241 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
7242 assert(Conv.isBad());
John McCall220ccbf2010-01-13 00:25:19 +00007243 assert(Cand->Function && "for now, candidate must be a function");
7244 FunctionDecl *Fn = Cand->Function;
7245
7246 // There's a conversion slot for the object argument if this is a
7247 // non-constructor method. Note that 'I' corresponds the
7248 // conversion-slot index.
John McCalladbb8f82010-01-13 09:16:55 +00007249 bool isObjectArgument = false;
John McCall220ccbf2010-01-13 00:25:19 +00007250 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCalladbb8f82010-01-13 09:16:55 +00007251 if (I == 0)
7252 isObjectArgument = true;
7253 else
7254 I--;
John McCall220ccbf2010-01-13 00:25:19 +00007255 }
7256
John McCall220ccbf2010-01-13 00:25:19 +00007257 std::string FnDesc;
7258 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
7259
John McCalladbb8f82010-01-13 09:16:55 +00007260 Expr *FromExpr = Conv.Bad.FromExpr;
7261 QualType FromTy = Conv.Bad.getFromType();
7262 QualType ToTy = Conv.Bad.getToType();
John McCall220ccbf2010-01-13 00:25:19 +00007263
John McCall5920dbb2010-02-02 02:42:52 +00007264 if (FromTy == S.Context.OverloadTy) {
John McCallb1bdc622010-02-25 01:37:24 +00007265 assert(FromExpr && "overload set argument came from implicit argument?");
John McCall5920dbb2010-02-02 02:42:52 +00007266 Expr *E = FromExpr->IgnoreParens();
7267 if (isa<UnaryOperator>(E))
7268 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall7bb12da2010-02-02 06:20:04 +00007269 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCall5920dbb2010-02-02 02:42:52 +00007270
7271 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
7272 << (unsigned) FnKind << FnDesc
7273 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7274 << ToTy << Name << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007275 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall5920dbb2010-02-02 02:42:52 +00007276 return;
7277 }
7278
John McCall258b2032010-01-23 08:10:49 +00007279 // Do some hand-waving analysis to see if the non-viability is due
7280 // to a qualifier mismatch.
John McCall651f3ee2010-01-14 03:28:57 +00007281 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
7282 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
7283 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
7284 CToTy = RT->getPointeeType();
7285 else {
7286 // TODO: detect and diagnose the full richness of const mismatches.
7287 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
7288 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
7289 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
7290 }
7291
7292 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
7293 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
7294 // It is dumb that we have to do this here.
7295 while (isa<ArrayType>(CFromTy))
7296 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
7297 while (isa<ArrayType>(CToTy))
7298 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
7299
7300 Qualifiers FromQs = CFromTy.getQualifiers();
7301 Qualifiers ToQs = CToTy.getQualifiers();
7302
7303 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
7304 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
7305 << (unsigned) FnKind << FnDesc
7306 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7307 << FromTy
7308 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
7309 << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007310 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007311 return;
7312 }
7313
John McCallf85e1932011-06-15 23:02:42 +00007314 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
Argyrios Kyrtzidisb8b03132011-06-24 00:08:59 +00007315 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_ownership)
John McCallf85e1932011-06-15 23:02:42 +00007316 << (unsigned) FnKind << FnDesc
7317 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7318 << FromTy
7319 << FromQs.getObjCLifetime() << ToQs.getObjCLifetime()
7320 << (unsigned) isObjectArgument << I+1;
7321 MaybeEmitInheritedConstructorNote(S, Fn);
7322 return;
7323 }
7324
Douglas Gregor028ea4b2011-04-26 23:16:46 +00007325 if (FromQs.getObjCGCAttr() != ToQs.getObjCGCAttr()) {
7326 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_gc)
7327 << (unsigned) FnKind << FnDesc
7328 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7329 << FromTy
7330 << FromQs.getObjCGCAttr() << ToQs.getObjCGCAttr()
7331 << (unsigned) isObjectArgument << I+1;
7332 MaybeEmitInheritedConstructorNote(S, Fn);
7333 return;
7334 }
7335
John McCall651f3ee2010-01-14 03:28:57 +00007336 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
7337 assert(CVR && "unexpected qualifiers mismatch");
7338
7339 if (isObjectArgument) {
7340 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
7341 << (unsigned) FnKind << FnDesc
7342 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7343 << FromTy << (CVR - 1);
7344 } else {
7345 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
7346 << (unsigned) FnKind << FnDesc
7347 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7348 << FromTy << (CVR - 1) << I+1;
7349 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00007350 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall651f3ee2010-01-14 03:28:57 +00007351 return;
7352 }
7353
Sebastian Redlfd2a00a2011-09-24 17:48:32 +00007354 // Special diagnostic for failure to convert an initializer list, since
7355 // telling the user that it has type void is not useful.
7356 if (FromExpr && isa<InitListExpr>(FromExpr)) {
7357 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_list_argument)
7358 << (unsigned) FnKind << FnDesc
7359 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7360 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7361 MaybeEmitInheritedConstructorNote(S, Fn);
7362 return;
7363 }
7364
John McCall258b2032010-01-23 08:10:49 +00007365 // Diagnose references or pointers to incomplete types differently,
7366 // since it's far from impossible that the incompleteness triggered
7367 // the failure.
7368 QualType TempFromTy = FromTy.getNonReferenceType();
7369 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
7370 TempFromTy = PTy->getPointeeType();
7371 if (TempFromTy->isIncompleteType()) {
7372 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
7373 << (unsigned) FnKind << FnDesc
7374 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7375 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007376 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall258b2032010-01-23 08:10:49 +00007377 return;
7378 }
7379
Douglas Gregor85789812010-06-30 23:01:39 +00007380 // Diagnose base -> derived pointer conversions.
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007381 unsigned BaseToDerivedConversion = 0;
Douglas Gregor85789812010-06-30 23:01:39 +00007382 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
7383 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
7384 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7385 FromPtrTy->getPointeeType()) &&
7386 !FromPtrTy->getPointeeType()->isIncompleteType() &&
7387 !ToPtrTy->getPointeeType()->isIncompleteType() &&
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007388 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
Douglas Gregor85789812010-06-30 23:01:39 +00007389 FromPtrTy->getPointeeType()))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007390 BaseToDerivedConversion = 1;
Douglas Gregor85789812010-06-30 23:01:39 +00007391 }
7392 } else if (const ObjCObjectPointerType *FromPtrTy
7393 = FromTy->getAs<ObjCObjectPointerType>()) {
7394 if (const ObjCObjectPointerType *ToPtrTy
7395 = ToTy->getAs<ObjCObjectPointerType>())
7396 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
7397 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
7398 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
7399 FromPtrTy->getPointeeType()) &&
7400 FromIface->isSuperClassOf(ToIface))
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007401 BaseToDerivedConversion = 2;
7402 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
7403 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
7404 !FromTy->isIncompleteType() &&
7405 !ToRefTy->getPointeeType()->isIncompleteType() &&
7406 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
7407 BaseToDerivedConversion = 3;
7408 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007409
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007410 if (BaseToDerivedConversion) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007411 S.Diag(Fn->getLocation(),
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007412 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor85789812010-06-30 23:01:39 +00007413 << (unsigned) FnKind << FnDesc
7414 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregor2f9d8742010-07-01 02:14:45 +00007415 << (BaseToDerivedConversion - 1)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007416 << FromTy << ToTy << I+1;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007417 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregor85789812010-06-30 23:01:39 +00007418 return;
7419 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007420
Fariborz Jahanian909bcb32011-07-20 17:14:09 +00007421 if (isa<ObjCObjectPointerType>(CFromTy) &&
7422 isa<PointerType>(CToTy)) {
7423 Qualifiers FromQs = CFromTy.getQualifiers();
7424 Qualifiers ToQs = CToTy.getQualifiers();
7425 if (FromQs.getObjCLifetime() != ToQs.getObjCLifetime()) {
7426 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_arc_conv)
7427 << (unsigned) FnKind << FnDesc
7428 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
7429 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
7430 MaybeEmitInheritedConstructorNote(S, Fn);
7431 return;
7432 }
7433 }
7434
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007435 // Emit the generic diagnostic and, optionally, add the hints to it.
7436 PartialDiagnostic FDiag = S.PDiag(diag::note_ovl_candidate_bad_conv);
7437 FDiag << (unsigned) FnKind << FnDesc
John McCalladbb8f82010-01-13 09:16:55 +00007438 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007439 << FromTy << ToTy << (unsigned) isObjectArgument << I + 1
7440 << (unsigned) (Cand->Fix.Kind);
7441
7442 // If we can fix the conversion, suggest the FixIts.
Chris Lattner5f9e2722011-07-23 10:55:15 +00007443 for (SmallVector<FixItHint, 1>::iterator
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007444 HI = Cand->Fix.Hints.begin(), HE = Cand->Fix.Hints.end();
7445 HI != HE; ++HI)
7446 FDiag << *HI;
7447 S.Diag(Fn->getLocation(), FDiag);
7448
Sebastian Redlf677ea32011-02-05 19:23:19 +00007449 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalladbb8f82010-01-13 09:16:55 +00007450}
7451
7452void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
7453 unsigned NumFormalArgs) {
7454 // TODO: treat calls to a missing default constructor as a special case
7455
7456 FunctionDecl *Fn = Cand->Function;
7457 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
7458
7459 unsigned MinParams = Fn->getMinRequiredArguments();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007460
Douglas Gregor439d3c32011-05-05 00:13:13 +00007461 // With invalid overloaded operators, it's possible that we think we
7462 // have an arity mismatch when it fact it looks like we have the
7463 // right number of arguments, because only overloaded operators have
7464 // the weird behavior of overloading member and non-member functions.
7465 // Just don't report anything.
7466 if (Fn->isInvalidDecl() &&
7467 Fn->getDeclName().getNameKind() == DeclarationName::CXXOperatorName)
7468 return;
7469
John McCalladbb8f82010-01-13 09:16:55 +00007470 // at least / at most / exactly
7471 unsigned mode, modeCount;
7472 if (NumFormalArgs < MinParams) {
Douglas Gregora18592e2010-05-08 18:13:28 +00007473 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
7474 (Cand->FailureKind == ovl_fail_bad_deduction &&
7475 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007476 if (MinParams != FnTy->getNumArgs() ||
Douglas Gregorf5c65ff2011-01-06 22:09:01 +00007477 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCalladbb8f82010-01-13 09:16:55 +00007478 mode = 0; // "at least"
7479 else
7480 mode = 2; // "exactly"
7481 modeCount = MinParams;
7482 } else {
Douglas Gregora18592e2010-05-08 18:13:28 +00007483 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
7484 (Cand->FailureKind == ovl_fail_bad_deduction &&
7485 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCalladbb8f82010-01-13 09:16:55 +00007486 if (MinParams != FnTy->getNumArgs())
7487 mode = 1; // "at most"
7488 else
7489 mode = 2; // "exactly"
7490 modeCount = FnTy->getNumArgs();
7491 }
7492
7493 std::string Description;
7494 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
7495
7496 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007497 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
Douglas Gregora18592e2010-05-08 18:13:28 +00007498 << modeCount << NumFormalArgs;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007499 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall220ccbf2010-01-13 00:25:19 +00007500}
7501
John McCall342fec42010-02-01 18:53:26 +00007502/// Diagnose a failed template-argument deduction.
7503void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
7504 Expr **Args, unsigned NumArgs) {
7505 FunctionDecl *Fn = Cand->Function; // pattern
7506
Douglas Gregora9333192010-05-08 17:41:32 +00007507 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregorf1a84452010-05-08 19:15:54 +00007508 NamedDecl *ParamD;
7509 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
7510 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
7511 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall342fec42010-02-01 18:53:26 +00007512 switch (Cand->DeductionFailure.Result) {
7513 case Sema::TDK_Success:
7514 llvm_unreachable("TDK_success while diagnosing bad deduction");
7515
7516 case Sema::TDK_Incomplete: {
John McCall342fec42010-02-01 18:53:26 +00007517 assert(ParamD && "no parameter found for incomplete deduction result");
7518 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
7519 << ParamD->getDeclName();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007520 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00007521 return;
7522 }
7523
John McCall57e97782010-08-05 09:05:08 +00007524 case Sema::TDK_Underqualified: {
7525 assert(ParamD && "no parameter found for bad qualifiers deduction result");
7526 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
7527
7528 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
7529
7530 // Param will have been canonicalized, but it should just be a
7531 // qualified version of ParamD, so move the qualifiers to that.
John McCall49f4e1c2010-12-10 11:01:00 +00007532 QualifierCollector Qs;
John McCall57e97782010-08-05 09:05:08 +00007533 Qs.strip(Param);
John McCall49f4e1c2010-12-10 11:01:00 +00007534 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall57e97782010-08-05 09:05:08 +00007535 assert(S.Context.hasSameType(Param, NonCanonParam));
7536
7537 // Arg has also been canonicalized, but there's nothing we can do
7538 // about that. It also doesn't matter as much, because it won't
7539 // have any template parameters in it (because deduction isn't
7540 // done on dependent types).
7541 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
7542
7543 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
7544 << ParamD->getDeclName() << Arg << NonCanonParam;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007545 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall57e97782010-08-05 09:05:08 +00007546 return;
7547 }
7548
7549 case Sema::TDK_Inconsistent: {
Chandler Carruth6df868e2010-12-12 08:17:55 +00007550 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregora9333192010-05-08 17:41:32 +00007551 int which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00007552 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00007553 which = 0;
Douglas Gregorf1a84452010-05-08 19:15:54 +00007554 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregora9333192010-05-08 17:41:32 +00007555 which = 1;
7556 else {
Douglas Gregora9333192010-05-08 17:41:32 +00007557 which = 2;
7558 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007559
Douglas Gregora9333192010-05-08 17:41:32 +00007560 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007561 << which << ParamD->getDeclName()
Douglas Gregora9333192010-05-08 17:41:32 +00007562 << *Cand->DeductionFailure.getFirstArg()
7563 << *Cand->DeductionFailure.getSecondArg();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007564 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregora9333192010-05-08 17:41:32 +00007565 return;
7566 }
Douglas Gregora18592e2010-05-08 18:13:28 +00007567
Douglas Gregorf1a84452010-05-08 19:15:54 +00007568 case Sema::TDK_InvalidExplicitArguments:
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007569 assert(ParamD && "no parameter found for invalid explicit arguments");
Douglas Gregorf1a84452010-05-08 19:15:54 +00007570 if (ParamD->getDeclName())
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007571 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00007572 diag::note_ovl_candidate_explicit_arg_mismatch_named)
7573 << ParamD->getDeclName();
7574 else {
7575 int index = 0;
7576 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
7577 index = TTP->getIndex();
7578 else if (NonTypeTemplateParmDecl *NTTP
7579 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
7580 index = NTTP->getIndex();
7581 else
7582 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007583 S.Diag(Fn->getLocation(),
Douglas Gregorf1a84452010-05-08 19:15:54 +00007584 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
7585 << (index + 1);
7586 }
Sebastian Redlf677ea32011-02-05 19:23:19 +00007587 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorf1a84452010-05-08 19:15:54 +00007588 return;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007589
Douglas Gregora18592e2010-05-08 18:13:28 +00007590 case Sema::TDK_TooManyArguments:
7591 case Sema::TDK_TooFewArguments:
7592 DiagnoseArityMismatch(S, Cand, NumArgs);
7593 return;
Douglas Gregorec20f462010-05-08 20:07:26 +00007594
7595 case Sema::TDK_InstantiationDepth:
7596 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007597 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00007598 return;
7599
7600 case Sema::TDK_SubstitutionFailure: {
7601 std::string ArgString;
7602 if (TemplateArgumentList *Args
7603 = Cand->DeductionFailure.getTemplateArgumentList())
7604 ArgString = S.getTemplateArgumentBindingsText(
7605 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
7606 *Args);
7607 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
7608 << ArgString;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007609 MaybeEmitInheritedConstructorNote(S, Fn);
Douglas Gregorec20f462010-05-08 20:07:26 +00007610 return;
7611 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007612
John McCall342fec42010-02-01 18:53:26 +00007613 // TODO: diagnose these individually, then kill off
7614 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall342fec42010-02-01 18:53:26 +00007615 case Sema::TDK_NonDeducedMismatch:
John McCall342fec42010-02-01 18:53:26 +00007616 case Sema::TDK_FailedOverloadResolution:
7617 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
Sebastian Redlf677ea32011-02-05 19:23:19 +00007618 MaybeEmitInheritedConstructorNote(S, Fn);
John McCall342fec42010-02-01 18:53:26 +00007619 return;
7620 }
7621}
7622
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00007623/// CUDA: diagnose an invalid call across targets.
7624void DiagnoseBadTarget(Sema &S, OverloadCandidate *Cand) {
7625 FunctionDecl *Caller = cast<FunctionDecl>(S.CurContext);
7626 FunctionDecl *Callee = Cand->Function;
7627
7628 Sema::CUDAFunctionTarget CallerTarget = S.IdentifyCUDATarget(Caller),
7629 CalleeTarget = S.IdentifyCUDATarget(Callee);
7630
7631 std::string FnDesc;
7632 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Callee, FnDesc);
7633
7634 S.Diag(Callee->getLocation(), diag::note_ovl_candidate_bad_target)
7635 << (unsigned) FnKind << CalleeTarget << CallerTarget;
7636}
7637
John McCall342fec42010-02-01 18:53:26 +00007638/// Generates a 'note' diagnostic for an overload candidate. We've
7639/// already generated a primary error at the call site.
7640///
7641/// It really does need to be a single diagnostic with its caret
7642/// pointed at the candidate declaration. Yes, this creates some
7643/// major challenges of technical writing. Yes, this makes pointing
7644/// out problems with specific arguments quite awkward. It's still
7645/// better than generating twenty screens of text for every failed
7646/// overload.
7647///
7648/// It would be great to be able to express per-candidate problems
7649/// more richly for those diagnostic clients that cared, but we'd
7650/// still have to be just as careful with the default diagnostics.
John McCall220ccbf2010-01-13 00:25:19 +00007651void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
7652 Expr **Args, unsigned NumArgs) {
John McCall3c80f572010-01-12 02:15:36 +00007653 FunctionDecl *Fn = Cand->Function;
7654
John McCall81201622010-01-08 04:41:39 +00007655 // Note deleted candidates, but only if they're viable.
Argyrios Kyrtzidis572bbec2011-06-23 00:41:50 +00007656 if (Cand->Viable && (Fn->isDeleted() ||
7657 S.isFunctionConsideredUnavailable(Fn))) {
John McCall220ccbf2010-01-13 00:25:19 +00007658 std::string FnDesc;
7659 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall3c80f572010-01-12 02:15:36 +00007660
7661 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCall220ccbf2010-01-13 00:25:19 +00007662 << FnKind << FnDesc << Fn->isDeleted();
Sebastian Redlf677ea32011-02-05 19:23:19 +00007663 MaybeEmitInheritedConstructorNote(S, Fn);
John McCalla1d7d622010-01-08 00:58:21 +00007664 return;
John McCall81201622010-01-08 04:41:39 +00007665 }
7666
John McCall220ccbf2010-01-13 00:25:19 +00007667 // We don't really have anything else to say about viable candidates.
7668 if (Cand->Viable) {
7669 S.NoteOverloadCandidate(Fn);
7670 return;
7671 }
John McCall1d318332010-01-12 00:44:57 +00007672
John McCalladbb8f82010-01-13 09:16:55 +00007673 switch (Cand->FailureKind) {
7674 case ovl_fail_too_many_arguments:
7675 case ovl_fail_too_few_arguments:
7676 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCall220ccbf2010-01-13 00:25:19 +00007677
John McCalladbb8f82010-01-13 09:16:55 +00007678 case ovl_fail_bad_deduction:
John McCall342fec42010-02-01 18:53:26 +00007679 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
7680
John McCall717e8912010-01-23 05:17:32 +00007681 case ovl_fail_trivial_conversion:
7682 case ovl_fail_bad_final_conversion:
Douglas Gregorc520c842010-04-12 23:42:09 +00007683 case ovl_fail_final_conversion_not_exact:
John McCalladbb8f82010-01-13 09:16:55 +00007684 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00007685
John McCallb1bdc622010-02-25 01:37:24 +00007686 case ovl_fail_bad_conversion: {
7687 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
7688 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCalladbb8f82010-01-13 09:16:55 +00007689 if (Cand->Conversions[I].isBad())
7690 return DiagnoseBadConversion(S, Cand, I);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007691
John McCalladbb8f82010-01-13 09:16:55 +00007692 // FIXME: this currently happens when we're called from SemaInit
7693 // when user-conversion overload fails. Figure out how to handle
7694 // those conditions and diagnose them well.
7695 return S.NoteOverloadCandidate(Fn);
John McCall220ccbf2010-01-13 00:25:19 +00007696 }
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00007697
7698 case ovl_fail_bad_target:
7699 return DiagnoseBadTarget(S, Cand);
John McCallb1bdc622010-02-25 01:37:24 +00007700 }
John McCalla1d7d622010-01-08 00:58:21 +00007701}
7702
7703void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
7704 // Desugar the type of the surrogate down to a function type,
7705 // retaining as many typedefs as possible while still showing
7706 // the function type (and, therefore, its parameter types).
7707 QualType FnType = Cand->Surrogate->getConversionType();
7708 bool isLValueReference = false;
7709 bool isRValueReference = false;
7710 bool isPointer = false;
7711 if (const LValueReferenceType *FnTypeRef =
7712 FnType->getAs<LValueReferenceType>()) {
7713 FnType = FnTypeRef->getPointeeType();
7714 isLValueReference = true;
7715 } else if (const RValueReferenceType *FnTypeRef =
7716 FnType->getAs<RValueReferenceType>()) {
7717 FnType = FnTypeRef->getPointeeType();
7718 isRValueReference = true;
7719 }
7720 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
7721 FnType = FnTypePtr->getPointeeType();
7722 isPointer = true;
7723 }
7724 // Desugar down to a function type.
7725 FnType = QualType(FnType->getAs<FunctionType>(), 0);
7726 // Reconstruct the pointer/reference as appropriate.
7727 if (isPointer) FnType = S.Context.getPointerType(FnType);
7728 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
7729 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
7730
7731 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
7732 << FnType;
Sebastian Redlf677ea32011-02-05 19:23:19 +00007733 MaybeEmitInheritedConstructorNote(S, Cand->Surrogate);
John McCalla1d7d622010-01-08 00:58:21 +00007734}
7735
7736void NoteBuiltinOperatorCandidate(Sema &S,
7737 const char *Opc,
7738 SourceLocation OpLoc,
7739 OverloadCandidate *Cand) {
7740 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
7741 std::string TypeStr("operator");
7742 TypeStr += Opc;
7743 TypeStr += "(";
7744 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
7745 if (Cand->Conversions.size() == 1) {
7746 TypeStr += ")";
7747 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
7748 } else {
7749 TypeStr += ", ";
7750 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
7751 TypeStr += ")";
7752 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
7753 }
7754}
7755
7756void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
7757 OverloadCandidate *Cand) {
7758 unsigned NoOperands = Cand->Conversions.size();
7759 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
7760 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall1d318332010-01-12 00:44:57 +00007761 if (ICS.isBad()) break; // all meaningless after first invalid
7762 if (!ICS.isAmbiguous()) continue;
7763
John McCall120d63c2010-08-24 20:38:10 +00007764 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00007765 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalla1d7d622010-01-08 00:58:21 +00007766 }
7767}
7768
John McCall1b77e732010-01-15 23:32:50 +00007769SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
7770 if (Cand->Function)
7771 return Cand->Function->getLocation();
John McCallf3cf22b2010-01-16 03:50:16 +00007772 if (Cand->IsSurrogate)
John McCall1b77e732010-01-15 23:32:50 +00007773 return Cand->Surrogate->getLocation();
7774 return SourceLocation();
7775}
7776
Benjamin Kramerafc5b152011-09-10 21:52:04 +00007777static unsigned
7778RankDeductionFailure(const OverloadCandidate::DeductionFailureInfo &DFI) {
Chandler Carruth78bf6802011-09-10 00:51:24 +00007779 switch ((Sema::TemplateDeductionResult)DFI.Result) {
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007780 case Sema::TDK_Success:
David Blaikieb219cfc2011-09-23 05:06:16 +00007781 llvm_unreachable("TDK_success while diagnosing bad deduction");
Benjamin Kramerafc5b152011-09-10 21:52:04 +00007782
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007783 case Sema::TDK_Incomplete:
7784 return 1;
7785
7786 case Sema::TDK_Underqualified:
7787 case Sema::TDK_Inconsistent:
7788 return 2;
7789
7790 case Sema::TDK_SubstitutionFailure:
7791 case Sema::TDK_NonDeducedMismatch:
7792 return 3;
7793
7794 case Sema::TDK_InstantiationDepth:
7795 case Sema::TDK_FailedOverloadResolution:
7796 return 4;
7797
7798 case Sema::TDK_InvalidExplicitArguments:
7799 return 5;
7800
7801 case Sema::TDK_TooManyArguments:
7802 case Sema::TDK_TooFewArguments:
7803 return 6;
7804 }
Benjamin Kramerafc5b152011-09-10 21:52:04 +00007805 llvm_unreachable("Unhandled deduction result");
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007806}
7807
John McCallbf65c0b2010-01-12 00:48:53 +00007808struct CompareOverloadCandidatesForDisplay {
7809 Sema &S;
7810 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall81201622010-01-08 04:41:39 +00007811
7812 bool operator()(const OverloadCandidate *L,
7813 const OverloadCandidate *R) {
John McCallf3cf22b2010-01-16 03:50:16 +00007814 // Fast-path this check.
7815 if (L == R) return false;
7816
John McCall81201622010-01-08 04:41:39 +00007817 // Order first by viability.
John McCallbf65c0b2010-01-12 00:48:53 +00007818 if (L->Viable) {
7819 if (!R->Viable) return true;
7820
7821 // TODO: introduce a tri-valued comparison for overload
7822 // candidates. Would be more worthwhile if we had a sort
7823 // that could exploit it.
John McCall120d63c2010-08-24 20:38:10 +00007824 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
7825 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallbf65c0b2010-01-12 00:48:53 +00007826 } else if (R->Viable)
7827 return false;
John McCall81201622010-01-08 04:41:39 +00007828
John McCall1b77e732010-01-15 23:32:50 +00007829 assert(L->Viable == R->Viable);
John McCall81201622010-01-08 04:41:39 +00007830
John McCall1b77e732010-01-15 23:32:50 +00007831 // Criteria by which we can sort non-viable candidates:
7832 if (!L->Viable) {
7833 // 1. Arity mismatches come after other candidates.
7834 if (L->FailureKind == ovl_fail_too_many_arguments ||
7835 L->FailureKind == ovl_fail_too_few_arguments)
7836 return false;
7837 if (R->FailureKind == ovl_fail_too_many_arguments ||
7838 R->FailureKind == ovl_fail_too_few_arguments)
7839 return true;
John McCall81201622010-01-08 04:41:39 +00007840
John McCall717e8912010-01-23 05:17:32 +00007841 // 2. Bad conversions come first and are ordered by the number
7842 // of bad conversions and quality of good conversions.
7843 if (L->FailureKind == ovl_fail_bad_conversion) {
7844 if (R->FailureKind != ovl_fail_bad_conversion)
7845 return true;
7846
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007847 // The conversion that can be fixed with a smaller number of changes,
7848 // comes first.
7849 unsigned numLFixes = L->Fix.NumConversionsFixed;
7850 unsigned numRFixes = R->Fix.NumConversionsFixed;
7851 numLFixes = (numLFixes == 0) ? UINT_MAX : numLFixes;
7852 numRFixes = (numRFixes == 0) ? UINT_MAX : numRFixes;
Anna Zaksffe9edd2011-07-21 00:34:39 +00007853 if (numLFixes != numRFixes) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007854 if (numLFixes < numRFixes)
7855 return true;
7856 else
7857 return false;
Anna Zaksffe9edd2011-07-21 00:34:39 +00007858 }
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007859
John McCall717e8912010-01-23 05:17:32 +00007860 // If there's any ordering between the defined conversions...
7861 // FIXME: this might not be transitive.
7862 assert(L->Conversions.size() == R->Conversions.size());
7863
7864 int leftBetter = 0;
John McCall3a813372010-02-25 10:46:05 +00007865 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
7866 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall120d63c2010-08-24 20:38:10 +00007867 switch (CompareImplicitConversionSequences(S,
7868 L->Conversions[I],
7869 R->Conversions[I])) {
John McCall717e8912010-01-23 05:17:32 +00007870 case ImplicitConversionSequence::Better:
7871 leftBetter++;
7872 break;
7873
7874 case ImplicitConversionSequence::Worse:
7875 leftBetter--;
7876 break;
7877
7878 case ImplicitConversionSequence::Indistinguishable:
7879 break;
7880 }
7881 }
7882 if (leftBetter > 0) return true;
7883 if (leftBetter < 0) return false;
7884
7885 } else if (R->FailureKind == ovl_fail_bad_conversion)
7886 return false;
7887
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007888 if (L->FailureKind == ovl_fail_bad_deduction) {
7889 if (R->FailureKind != ovl_fail_bad_deduction)
7890 return true;
7891
7892 if (L->DeductionFailure.Result != R->DeductionFailure.Result)
7893 return RankDeductionFailure(L->DeductionFailure)
Eli Friedmance1846e2011-10-14 23:10:30 +00007894 < RankDeductionFailure(R->DeductionFailure);
Eli Friedman1c522f72011-10-14 21:52:24 +00007895 } else if (R->FailureKind == ovl_fail_bad_deduction)
7896 return false;
Kaelyn Uhrainfd641f92011-09-09 21:58:49 +00007897
John McCall1b77e732010-01-15 23:32:50 +00007898 // TODO: others?
7899 }
7900
7901 // Sort everything else by location.
7902 SourceLocation LLoc = GetLocationForCandidate(L);
7903 SourceLocation RLoc = GetLocationForCandidate(R);
7904
7905 // Put candidates without locations (e.g. builtins) at the end.
7906 if (LLoc.isInvalid()) return false;
7907 if (RLoc.isInvalid()) return true;
7908
7909 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall81201622010-01-08 04:41:39 +00007910 }
7911};
7912
John McCall717e8912010-01-23 05:17:32 +00007913/// CompleteNonViableCandidate - Normally, overload resolution only
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007914/// computes up to the first. Produces the FixIt set if possible.
John McCall717e8912010-01-23 05:17:32 +00007915void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
7916 Expr **Args, unsigned NumArgs) {
7917 assert(!Cand->Viable);
7918
7919 // Don't do anything on failures other than bad conversion.
7920 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
7921
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007922 // We only want the FixIts if all the arguments can be corrected.
7923 bool Unfixable = false;
Anna Zaksf3546ee2011-07-28 19:46:48 +00007924 // Use a implicit copy initialization to check conversion fixes.
7925 Cand->Fix.setConversionChecker(TryCopyInitialization);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007926
John McCall717e8912010-01-23 05:17:32 +00007927 // Skip forward to the first bad conversion.
John McCallb1bdc622010-02-25 01:37:24 +00007928 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCall717e8912010-01-23 05:17:32 +00007929 unsigned ConvCount = Cand->Conversions.size();
7930 while (true) {
7931 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
7932 ConvIdx++;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007933 if (Cand->Conversions[ConvIdx - 1].isBad()) {
Anna Zaksf3546ee2011-07-28 19:46:48 +00007934 Unfixable = !Cand->TryToFixBadConversion(ConvIdx - 1, S);
John McCall717e8912010-01-23 05:17:32 +00007935 break;
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007936 }
John McCall717e8912010-01-23 05:17:32 +00007937 }
7938
7939 if (ConvIdx == ConvCount)
7940 return;
7941
John McCallb1bdc622010-02-25 01:37:24 +00007942 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
7943 "remaining conversion is initialized?");
7944
Douglas Gregor23ef6c02010-04-16 17:45:54 +00007945 // FIXME: this should probably be preserved from the overload
John McCall717e8912010-01-23 05:17:32 +00007946 // operation somehow.
7947 bool SuppressUserConversions = false;
John McCall717e8912010-01-23 05:17:32 +00007948
7949 const FunctionProtoType* Proto;
7950 unsigned ArgIdx = ConvIdx;
7951
7952 if (Cand->IsSurrogate) {
7953 QualType ConvType
7954 = Cand->Surrogate->getConversionType().getNonReferenceType();
7955 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
7956 ConvType = ConvPtrType->getPointeeType();
7957 Proto = ConvType->getAs<FunctionProtoType>();
7958 ArgIdx--;
7959 } else if (Cand->Function) {
7960 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
7961 if (isa<CXXMethodDecl>(Cand->Function) &&
7962 !isa<CXXConstructorDecl>(Cand->Function))
7963 ArgIdx--;
7964 } else {
7965 // Builtin binary operator with a bad first conversion.
7966 assert(ConvCount <= 3);
7967 for (; ConvIdx != ConvCount; ++ConvIdx)
7968 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00007969 = TryCopyInitialization(S, Args[ConvIdx],
7970 Cand->BuiltinTypes.ParamTypes[ConvIdx],
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007971 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00007972 /*InOverloadResolution*/ true,
7973 /*AllowObjCWritebackConversion=*/
7974 S.getLangOptions().ObjCAutoRefCount);
John McCall717e8912010-01-23 05:17:32 +00007975 return;
7976 }
7977
7978 // Fill in the rest of the conversions.
7979 unsigned NumArgsInProto = Proto->getNumArgs();
7980 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007981 if (ArgIdx < NumArgsInProto) {
John McCall717e8912010-01-23 05:17:32 +00007982 Cand->Conversions[ConvIdx]
Douglas Gregor74eb6582010-04-16 17:51:22 +00007983 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00007984 SuppressUserConversions,
John McCallf85e1932011-06-15 23:02:42 +00007985 /*InOverloadResolution=*/true,
7986 /*AllowObjCWritebackConversion=*/
7987 S.getLangOptions().ObjCAutoRefCount);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007988 // Store the FixIt in the candidate if it exists.
7989 if (!Unfixable && Cand->Conversions[ConvIdx].isBad())
Anna Zaksf3546ee2011-07-28 19:46:48 +00007990 Unfixable = !Cand->TryToFixBadConversion(ConvIdx, S);
Anna Zaksb89fe6b2011-07-19 19:49:12 +00007991 }
John McCall717e8912010-01-23 05:17:32 +00007992 else
7993 Cand->Conversions[ConvIdx].setEllipsis();
7994 }
7995}
7996
John McCalla1d7d622010-01-08 00:58:21 +00007997} // end anonymous namespace
7998
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00007999/// PrintOverloadCandidates - When overload resolution fails, prints
8000/// diagnostic messages containing the candidates in the candidate
John McCall81201622010-01-08 04:41:39 +00008001/// set.
John McCall120d63c2010-08-24 20:38:10 +00008002void OverloadCandidateSet::NoteCandidates(Sema &S,
8003 OverloadCandidateDisplayKind OCD,
8004 Expr **Args, unsigned NumArgs,
8005 const char *Opc,
8006 SourceLocation OpLoc) {
John McCall81201622010-01-08 04:41:39 +00008007 // Sort the candidates by viability and position. Sorting directly would
8008 // be prohibitive, so we make a set of pointers and sort those.
Chris Lattner5f9e2722011-07-23 10:55:15 +00008009 SmallVector<OverloadCandidate*, 32> Cands;
John McCall120d63c2010-08-24 20:38:10 +00008010 if (OCD == OCD_AllCandidates) Cands.reserve(size());
8011 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCall717e8912010-01-23 05:17:32 +00008012 if (Cand->Viable)
John McCall81201622010-01-08 04:41:39 +00008013 Cands.push_back(Cand);
John McCall717e8912010-01-23 05:17:32 +00008014 else if (OCD == OCD_AllCandidates) {
John McCall120d63c2010-08-24 20:38:10 +00008015 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008016 if (Cand->Function || Cand->IsSurrogate)
8017 Cands.push_back(Cand);
8018 // Otherwise, this a non-viable builtin candidate. We do not, in general,
8019 // want to list every possible builtin candidate.
John McCall717e8912010-01-23 05:17:32 +00008020 }
8021 }
8022
John McCallbf65c0b2010-01-12 00:48:53 +00008023 std::sort(Cands.begin(), Cands.end(),
John McCall120d63c2010-08-24 20:38:10 +00008024 CompareOverloadCandidatesForDisplay(S));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008025
John McCall1d318332010-01-12 00:44:57 +00008026 bool ReportedAmbiguousConversions = false;
John McCalla1d7d622010-01-08 00:58:21 +00008027
Chris Lattner5f9e2722011-07-23 10:55:15 +00008028 SmallVectorImpl<OverloadCandidate*>::iterator I, E;
David Blaikied6471f72011-09-25 23:23:43 +00008029 const DiagnosticsEngine::OverloadsShown ShowOverloads =
8030 S.Diags.getShowOverloads();
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008031 unsigned CandsShown = 0;
John McCall81201622010-01-08 04:41:39 +00008032 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
8033 OverloadCandidate *Cand = *I;
Douglas Gregor621b3932008-11-21 02:54:28 +00008034
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008035 // Set an arbitrary limit on the number of candidate functions we'll spam
8036 // the user with. FIXME: This limit should depend on details of the
8037 // candidate list.
David Blaikied6471f72011-09-25 23:23:43 +00008038 if (CandsShown >= 4 && ShowOverloads == DiagnosticsEngine::Ovl_Best) {
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008039 break;
8040 }
8041 ++CandsShown;
8042
John McCalla1d7d622010-01-08 00:58:21 +00008043 if (Cand->Function)
John McCall120d63c2010-08-24 20:38:10 +00008044 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalla1d7d622010-01-08 00:58:21 +00008045 else if (Cand->IsSurrogate)
John McCall120d63c2010-08-24 20:38:10 +00008046 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008047 else {
8048 assert(Cand->Viable &&
8049 "Non-viable built-in candidates are not added to Cands.");
John McCall1d318332010-01-12 00:44:57 +00008050 // Generally we only see ambiguities including viable builtin
8051 // operators if overload resolution got screwed up by an
8052 // ambiguous user-defined conversion.
8053 //
8054 // FIXME: It's quite possible for different conversions to see
8055 // different ambiguities, though.
8056 if (!ReportedAmbiguousConversions) {
John McCall120d63c2010-08-24 20:38:10 +00008057 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall1d318332010-01-12 00:44:57 +00008058 ReportedAmbiguousConversions = true;
8059 }
John McCalla1d7d622010-01-08 00:58:21 +00008060
John McCall1d318332010-01-12 00:44:57 +00008061 // If this is a viable builtin, print it.
John McCall120d63c2010-08-24 20:38:10 +00008062 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregoreb8f3062008-11-12 17:17:38 +00008063 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008064 }
Jeffrey Yasskin5edbdcc2010-06-11 05:57:47 +00008065
8066 if (I != E)
John McCall120d63c2010-08-24 20:38:10 +00008067 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00008068}
8069
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008070// [PossiblyAFunctionType] --> [Return]
8071// NonFunctionType --> NonFunctionType
8072// R (A) --> R(A)
8073// R (*)(A) --> R (A)
8074// R (&)(A) --> R (A)
8075// R (S::*)(A) --> R (A)
8076QualType Sema::ExtractUnqualifiedFunctionType(QualType PossiblyAFunctionType) {
8077 QualType Ret = PossiblyAFunctionType;
8078 if (const PointerType *ToTypePtr =
8079 PossiblyAFunctionType->getAs<PointerType>())
8080 Ret = ToTypePtr->getPointeeType();
8081 else if (const ReferenceType *ToTypeRef =
8082 PossiblyAFunctionType->getAs<ReferenceType>())
8083 Ret = ToTypeRef->getPointeeType();
Sebastian Redl33b399a2009-02-04 21:23:32 +00008084 else if (const MemberPointerType *MemTypePtr =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008085 PossiblyAFunctionType->getAs<MemberPointerType>())
8086 Ret = MemTypePtr->getPointeeType();
8087 Ret =
8088 Context.getCanonicalType(Ret).getUnqualifiedType();
8089 return Ret;
8090}
Douglas Gregor904eed32008-11-10 20:40:00 +00008091
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008092// A helper class to help with address of function resolution
8093// - allows us to avoid passing around all those ugly parameters
8094class AddressOfFunctionResolver
8095{
8096 Sema& S;
8097 Expr* SourceExpr;
8098 const QualType& TargetType;
8099 QualType TargetFunctionType; // Extracted function type from target type
8100
8101 bool Complain;
8102 //DeclAccessPair& ResultFunctionAccessPair;
8103 ASTContext& Context;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008104
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008105 bool TargetTypeIsNonStaticMemberFunction;
8106 bool FoundNonTemplateFunction;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008107
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008108 OverloadExpr::FindResult OvlExprInfo;
8109 OverloadExpr *OvlExpr;
8110 TemplateArgumentListInfo OvlExplicitTemplateArgs;
Chris Lattner5f9e2722011-07-23 10:55:15 +00008111 SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008112
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008113public:
8114 AddressOfFunctionResolver(Sema &S, Expr* SourceExpr,
8115 const QualType& TargetType, bool Complain)
8116 : S(S), SourceExpr(SourceExpr), TargetType(TargetType),
8117 Complain(Complain), Context(S.getASTContext()),
8118 TargetTypeIsNonStaticMemberFunction(
8119 !!TargetType->getAs<MemberPointerType>()),
8120 FoundNonTemplateFunction(false),
8121 OvlExprInfo(OverloadExpr::find(SourceExpr)),
8122 OvlExpr(OvlExprInfo.Expression)
8123 {
8124 ExtractUnqualifiedFunctionTypeFromTargetType();
8125
8126 if (!TargetFunctionType->isFunctionType()) {
8127 if (OvlExpr->hasExplicitTemplateArgs()) {
8128 DeclAccessPair dap;
John McCall864c0412011-04-26 20:42:42 +00008129 if (FunctionDecl* Fn = S.ResolveSingleFunctionTemplateSpecialization(
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008130 OvlExpr, false, &dap) ) {
Chandler Carruth90434232011-03-29 08:08:18 +00008131
8132 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8133 if (!Method->isStatic()) {
8134 // If the target type is a non-function type and the function
8135 // found is a non-static member function, pretend as if that was
8136 // the target, it's the only possible type to end up with.
8137 TargetTypeIsNonStaticMemberFunction = true;
8138
8139 // And skip adding the function if its not in the proper form.
8140 // We'll diagnose this due to an empty set of functions.
8141 if (!OvlExprInfo.HasFormOfMemberPointer)
8142 return;
8143 }
8144 }
8145
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008146 Matches.push_back(std::make_pair(dap,Fn));
8147 }
Douglas Gregor83314aa2009-07-08 20:55:45 +00008148 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008149 return;
Douglas Gregor83314aa2009-07-08 20:55:45 +00008150 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008151
8152 if (OvlExpr->hasExplicitTemplateArgs())
8153 OvlExpr->getExplicitTemplateArgs().copyInto(OvlExplicitTemplateArgs);
Mike Stump1eb44332009-09-09 15:08:12 +00008154
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008155 if (FindAllFunctionsThatMatchTargetTypeExactly()) {
8156 // C++ [over.over]p4:
8157 // If more than one function is selected, [...]
8158 if (Matches.size() > 1) {
8159 if (FoundNonTemplateFunction)
8160 EliminateAllTemplateMatches();
8161 else
8162 EliminateAllExceptMostSpecializedTemplate();
8163 }
8164 }
8165 }
8166
8167private:
8168 bool isTargetTypeAFunction() const {
8169 return TargetFunctionType->isFunctionType();
8170 }
8171
8172 // [ToType] [Return]
8173
8174 // R (*)(A) --> R (A), IsNonStaticMemberFunction = false
8175 // R (&)(A) --> R (A), IsNonStaticMemberFunction = false
8176 // R (S::*)(A) --> R (A), IsNonStaticMemberFunction = true
8177 void inline ExtractUnqualifiedFunctionTypeFromTargetType() {
8178 TargetFunctionType = S.ExtractUnqualifiedFunctionType(TargetType);
8179 }
8180
8181 // return true if any matching specializations were found
8182 bool AddMatchingTemplateFunction(FunctionTemplateDecl* FunctionTemplate,
8183 const DeclAccessPair& CurAccessFunPair) {
8184 if (CXXMethodDecl *Method
8185 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
8186 // Skip non-static function templates when converting to pointer, and
8187 // static when converting to member pointer.
8188 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8189 return false;
8190 }
8191 else if (TargetTypeIsNonStaticMemberFunction)
8192 return false;
8193
8194 // C++ [over.over]p2:
8195 // If the name is a function template, template argument deduction is
8196 // done (14.8.2.2), and if the argument deduction succeeds, the
8197 // resulting template argument list is used to generate a single
8198 // function template specialization, which is added to the set of
8199 // overloaded functions considered.
8200 FunctionDecl *Specialization = 0;
8201 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
8202 if (Sema::TemplateDeductionResult Result
8203 = S.DeduceTemplateArguments(FunctionTemplate,
8204 &OvlExplicitTemplateArgs,
8205 TargetFunctionType, Specialization,
8206 Info)) {
8207 // FIXME: make a note of the failed deduction for diagnostics.
8208 (void)Result;
8209 return false;
8210 }
8211
8212 // Template argument deduction ensures that we have an exact match.
8213 // This function template specicalization works.
8214 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
8215 assert(TargetFunctionType
8216 == Context.getCanonicalType(Specialization->getType()));
8217 Matches.push_back(std::make_pair(CurAccessFunPair, Specialization));
8218 return true;
8219 }
8220
8221 bool AddMatchingNonTemplateFunction(NamedDecl* Fn,
8222 const DeclAccessPair& CurAccessFunPair) {
Chandler Carruthbd647292009-12-29 06:17:27 +00008223 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl33b399a2009-02-04 21:23:32 +00008224 // Skip non-static functions when converting to pointer, and static
8225 // when converting to member pointer.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008226 if (Method->isStatic() == TargetTypeIsNonStaticMemberFunction)
8227 return false;
8228 }
8229 else if (TargetTypeIsNonStaticMemberFunction)
8230 return false;
Douglas Gregor904eed32008-11-10 20:40:00 +00008231
Chandler Carruthbd647292009-12-29 06:17:27 +00008232 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Peter Collingbourne78dd67e2011-10-02 23:49:40 +00008233 if (S.getLangOptions().CUDA)
8234 if (FunctionDecl *Caller = dyn_cast<FunctionDecl>(S.CurContext))
8235 if (S.CheckCUDATarget(Caller, FunDecl))
8236 return false;
8237
Douglas Gregor43c79c22009-12-09 00:47:37 +00008238 QualType ResultTy;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008239 if (Context.hasSameUnqualifiedType(TargetFunctionType,
8240 FunDecl->getType()) ||
Chandler Carruth18e04612011-06-18 01:19:03 +00008241 S.IsNoReturnConversion(FunDecl->getType(), TargetFunctionType,
8242 ResultTy)) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008243 Matches.push_back(std::make_pair(CurAccessFunPair,
8244 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregor00aeb522009-07-08 23:33:52 +00008245 FoundNonTemplateFunction = true;
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008246 return true;
Douglas Gregor00aeb522009-07-08 23:33:52 +00008247 }
Mike Stump1eb44332009-09-09 15:08:12 +00008248 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008249
8250 return false;
8251 }
8252
8253 bool FindAllFunctionsThatMatchTargetTypeExactly() {
8254 bool Ret = false;
8255
8256 // If the overload expression doesn't have the form of a pointer to
8257 // member, don't try to convert it to a pointer-to-member type.
8258 if (IsInvalidFormOfPointerToMemberFunction())
8259 return false;
8260
8261 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
8262 E = OvlExpr->decls_end();
8263 I != E; ++I) {
8264 // Look through any using declarations to find the underlying function.
8265 NamedDecl *Fn = (*I)->getUnderlyingDecl();
8266
8267 // C++ [over.over]p3:
8268 // Non-member functions and static member functions match
8269 // targets of type "pointer-to-function" or "reference-to-function."
8270 // Nonstatic member functions match targets of
8271 // type "pointer-to-member-function."
8272 // Note that according to DR 247, the containing class does not matter.
8273 if (FunctionTemplateDecl *FunctionTemplate
8274 = dyn_cast<FunctionTemplateDecl>(Fn)) {
8275 if (AddMatchingTemplateFunction(FunctionTemplate, I.getPair()))
8276 Ret = true;
8277 }
8278 // If we have explicit template arguments supplied, skip non-templates.
8279 else if (!OvlExpr->hasExplicitTemplateArgs() &&
8280 AddMatchingNonTemplateFunction(Fn, I.getPair()))
8281 Ret = true;
8282 }
8283 assert(Ret || Matches.empty());
8284 return Ret;
Douglas Gregor904eed32008-11-10 20:40:00 +00008285 }
8286
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008287 void EliminateAllExceptMostSpecializedTemplate() {
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00008288 // [...] and any given function template specialization F1 is
8289 // eliminated if the set contains a second function template
8290 // specialization whose function template is more specialized
8291 // than the function template of F1 according to the partial
8292 // ordering rules of 14.5.5.2.
8293
8294 // The algorithm specified above is quadratic. We instead use a
8295 // two-pass algorithm (similar to the one used to identify the
8296 // best viable function in an overload set) that identifies the
8297 // best function template (if it exists).
John McCall9aa472c2010-03-19 07:35:19 +00008298
8299 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
8300 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
8301 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008302
John McCallc373d482010-01-27 01:50:18 +00008303 UnresolvedSetIterator Result =
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008304 S.getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
8305 TPOC_Other, 0, SourceExpr->getLocStart(),
8306 S.PDiag(),
8307 S.PDiag(diag::err_addr_ovl_ambiguous)
8308 << Matches[0].second->getDeclName(),
8309 S.PDiag(diag::note_ovl_candidate)
8310 << (unsigned) oc_function_template,
Richard Trieu6efd4c52011-11-23 22:32:32 +00008311 Complain, TargetFunctionType);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008312
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008313 if (Result != MatchesCopy.end()) {
8314 // Make it the first and only element
8315 Matches[0].first = Matches[Result - MatchesCopy.begin()].first;
8316 Matches[0].second = cast<FunctionDecl>(*Result);
8317 Matches.resize(1);
John McCallc373d482010-01-27 01:50:18 +00008318 }
8319 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008320
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008321 void EliminateAllTemplateMatches() {
8322 // [...] any function template specializations in the set are
8323 // eliminated if the set also contains a non-template function, [...]
8324 for (unsigned I = 0, N = Matches.size(); I != N; ) {
8325 if (Matches[I].second->getPrimaryTemplate() == 0)
8326 ++I;
8327 else {
8328 Matches[I] = Matches[--N];
8329 Matches.set_size(N);
8330 }
8331 }
8332 }
8333
8334public:
8335 void ComplainNoMatchesFound() const {
8336 assert(Matches.empty());
8337 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_no_viable)
8338 << OvlExpr->getName() << TargetFunctionType
8339 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00008340 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008341 }
8342
8343 bool IsInvalidFormOfPointerToMemberFunction() const {
8344 return TargetTypeIsNonStaticMemberFunction &&
8345 !OvlExprInfo.HasFormOfMemberPointer;
8346 }
8347
8348 void ComplainIsInvalidFormOfPointerToMemberFunction() const {
8349 // TODO: Should we condition this on whether any functions might
8350 // have matched, or is it more appropriate to do that in callers?
8351 // TODO: a fixit wouldn't hurt.
8352 S.Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
8353 << TargetType << OvlExpr->getSourceRange();
8354 }
8355
8356 void ComplainOfInvalidConversion() const {
8357 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
8358 << OvlExpr->getName() << TargetType;
8359 }
8360
8361 void ComplainMultipleMatchesFound() const {
8362 assert(Matches.size() > 1);
8363 S.Diag(OvlExpr->getLocStart(), diag::err_addr_ovl_ambiguous)
8364 << OvlExpr->getName()
8365 << OvlExpr->getSourceRange();
Richard Trieu6efd4c52011-11-23 22:32:32 +00008366 S.NoteAllOverloadCandidates(OvlExpr, TargetFunctionType);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008367 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008368
8369 bool hadMultipleCandidates() const { return (OvlExpr->getNumDecls() > 1); }
8370
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008371 int getNumMatches() const { return Matches.size(); }
8372
8373 FunctionDecl* getMatchingFunctionDecl() const {
8374 if (Matches.size() != 1) return 0;
8375 return Matches[0].second;
8376 }
8377
8378 const DeclAccessPair* getMatchingFunctionAccessPair() const {
8379 if (Matches.size() != 1) return 0;
8380 return &Matches[0].first;
8381 }
8382};
8383
8384/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
8385/// an overloaded function (C++ [over.over]), where @p From is an
8386/// expression with overloaded function type and @p ToType is the type
8387/// we're trying to resolve to. For example:
8388///
8389/// @code
8390/// int f(double);
8391/// int f(int);
8392///
8393/// int (*pfd)(double) = f; // selects f(double)
8394/// @endcode
8395///
8396/// This routine returns the resulting FunctionDecl if it could be
8397/// resolved, and NULL otherwise. When @p Complain is true, this
8398/// routine will emit diagnostics if there is an error.
8399FunctionDecl *
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008400Sema::ResolveAddressOfOverloadedFunction(Expr *AddressOfExpr,
8401 QualType TargetType,
8402 bool Complain,
8403 DeclAccessPair &FoundResult,
8404 bool *pHadMultipleCandidates) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008405 assert(AddressOfExpr->getType() == Context.OverloadTy);
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008406
8407 AddressOfFunctionResolver Resolver(*this, AddressOfExpr, TargetType,
8408 Complain);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008409 int NumMatches = Resolver.getNumMatches();
8410 FunctionDecl* Fn = 0;
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008411 if (NumMatches == 0 && Complain) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008412 if (Resolver.IsInvalidFormOfPointerToMemberFunction())
8413 Resolver.ComplainIsInvalidFormOfPointerToMemberFunction();
8414 else
8415 Resolver.ComplainNoMatchesFound();
8416 }
8417 else if (NumMatches > 1 && Complain)
8418 Resolver.ComplainMultipleMatchesFound();
8419 else if (NumMatches == 1) {
8420 Fn = Resolver.getMatchingFunctionDecl();
8421 assert(Fn);
8422 FoundResult = *Resolver.getMatchingFunctionAccessPair();
8423 MarkDeclarationReferenced(AddressOfExpr->getLocStart(), Fn);
Douglas Gregor9b623632010-10-12 23:32:35 +00008424 if (Complain)
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008425 CheckAddressOfMemberAccess(AddressOfExpr, FoundResult);
Sebastian Redl07ab2022009-10-17 21:12:09 +00008426 }
Abramo Bagnara22c107b2011-11-19 11:44:21 +00008427
8428 if (pHadMultipleCandidates)
8429 *pHadMultipleCandidates = Resolver.hadMultipleCandidates();
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008430 return Fn;
Douglas Gregor904eed32008-11-10 20:40:00 +00008431}
8432
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008433/// \brief Given an expression that refers to an overloaded function, try to
Douglas Gregor4b52e252009-12-21 23:17:24 +00008434/// resolve that overloaded function expression down to a single function.
8435///
8436/// This routine can only resolve template-ids that refer to a single function
8437/// template, where that template-id refers to a single template whose template
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008438/// arguments are either provided by the template-id or have defaults,
Douglas Gregor4b52e252009-12-21 23:17:24 +00008439/// as described in C++0x [temp.arg.explicit]p3.
John McCall864c0412011-04-26 20:42:42 +00008440FunctionDecl *
8441Sema::ResolveSingleFunctionTemplateSpecialization(OverloadExpr *ovl,
8442 bool Complain,
8443 DeclAccessPair *FoundResult) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00008444 // C++ [over.over]p1:
8445 // [...] [Note: any redundant set of parentheses surrounding the
8446 // overloaded function name is ignored (5.1). ]
Douglas Gregor4b52e252009-12-21 23:17:24 +00008447 // C++ [over.over]p1:
8448 // [...] The overloaded function name can be preceded by the &
8449 // operator.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008450
Douglas Gregor4b52e252009-12-21 23:17:24 +00008451 // If we didn't actually find any template-ids, we're done.
John McCall864c0412011-04-26 20:42:42 +00008452 if (!ovl->hasExplicitTemplateArgs())
Douglas Gregor4b52e252009-12-21 23:17:24 +00008453 return 0;
John McCall7bb12da2010-02-02 06:20:04 +00008454
8455 TemplateArgumentListInfo ExplicitTemplateArgs;
John McCall864c0412011-04-26 20:42:42 +00008456 ovl->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008457
Douglas Gregor4b52e252009-12-21 23:17:24 +00008458 // Look through all of the overloaded functions, searching for one
8459 // whose type matches exactly.
8460 FunctionDecl *Matched = 0;
John McCall864c0412011-04-26 20:42:42 +00008461 for (UnresolvedSetIterator I = ovl->decls_begin(),
8462 E = ovl->decls_end(); I != E; ++I) {
Douglas Gregor4b52e252009-12-21 23:17:24 +00008463 // C++0x [temp.arg.explicit]p3:
8464 // [...] In contexts where deduction is done and fails, or in contexts
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008465 // where deduction is not done, if a template argument list is
8466 // specified and it, along with any default template arguments,
8467 // identifies a single function template specialization, then the
Douglas Gregor4b52e252009-12-21 23:17:24 +00008468 // template-id is an lvalue for the function template specialization.
Douglas Gregor66a8c9a2010-07-14 23:20:53 +00008469 FunctionTemplateDecl *FunctionTemplate
8470 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008471
Douglas Gregor4b52e252009-12-21 23:17:24 +00008472 // C++ [over.over]p2:
8473 // If the name is a function template, template argument deduction is
8474 // done (14.8.2.2), and if the argument deduction succeeds, the
8475 // resulting template argument list is used to generate a single
8476 // function template specialization, which is added to the set of
8477 // overloaded functions considered.
Douglas Gregor4b52e252009-12-21 23:17:24 +00008478 FunctionDecl *Specialization = 0;
John McCall864c0412011-04-26 20:42:42 +00008479 TemplateDeductionInfo Info(Context, ovl->getNameLoc());
Douglas Gregor4b52e252009-12-21 23:17:24 +00008480 if (TemplateDeductionResult Result
8481 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
8482 Specialization, Info)) {
8483 // FIXME: make a note of the failed deduction for diagnostics.
8484 (void)Result;
8485 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008486 }
8487
John McCall864c0412011-04-26 20:42:42 +00008488 assert(Specialization && "no specialization and no error?");
8489
Douglas Gregor4b52e252009-12-21 23:17:24 +00008490 // Multiple matches; we can't resolve to a single declaration.
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008491 if (Matched) {
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008492 if (Complain) {
John McCall864c0412011-04-26 20:42:42 +00008493 Diag(ovl->getExprLoc(), diag::err_addr_ovl_ambiguous)
8494 << ovl->getName();
8495 NoteAllOverloadCandidates(ovl);
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008496 }
Douglas Gregor4b52e252009-12-21 23:17:24 +00008497 return 0;
John McCall864c0412011-04-26 20:42:42 +00008498 }
Douglas Gregor1be8eec2011-02-19 21:32:49 +00008499
John McCall864c0412011-04-26 20:42:42 +00008500 Matched = Specialization;
8501 if (FoundResult) *FoundResult = I.getPair();
Douglas Gregor4b52e252009-12-21 23:17:24 +00008502 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008503
Douglas Gregor4b52e252009-12-21 23:17:24 +00008504 return Matched;
8505}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008506
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008507
8508
8509
John McCall6dbba4f2011-10-11 23:14:30 +00008510// Resolve and fix an overloaded expression that can be resolved
8511// because it identifies a single function template specialization.
8512//
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008513// Last three arguments should only be supplied if Complain = true
John McCall6dbba4f2011-10-11 23:14:30 +00008514//
8515// Return true if it was logically possible to so resolve the
8516// expression, regardless of whether or not it succeeded. Always
8517// returns true if 'complain' is set.
8518bool Sema::ResolveAndFixSingleFunctionTemplateSpecialization(
8519 ExprResult &SrcExpr, bool doFunctionPointerConverion,
8520 bool complain, const SourceRange& OpRangeForComplaining,
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008521 QualType DestTypeForComplaining,
John McCall864c0412011-04-26 20:42:42 +00008522 unsigned DiagIDForComplaining) {
John McCall6dbba4f2011-10-11 23:14:30 +00008523 assert(SrcExpr.get()->getType() == Context.OverloadTy);
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008524
John McCall6dbba4f2011-10-11 23:14:30 +00008525 OverloadExpr::FindResult ovl = OverloadExpr::find(SrcExpr.get());
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008526
John McCall864c0412011-04-26 20:42:42 +00008527 DeclAccessPair found;
8528 ExprResult SingleFunctionExpression;
8529 if (FunctionDecl *fn = ResolveSingleFunctionTemplateSpecialization(
8530 ovl.Expression, /*complain*/ false, &found)) {
John McCall6dbba4f2011-10-11 23:14:30 +00008531 if (DiagnoseUseOfDecl(fn, SrcExpr.get()->getSourceRange().getBegin())) {
8532 SrcExpr = ExprError();
8533 return true;
8534 }
John McCall864c0412011-04-26 20:42:42 +00008535
8536 // It is only correct to resolve to an instance method if we're
8537 // resolving a form that's permitted to be a pointer to member.
8538 // Otherwise we'll end up making a bound member expression, which
8539 // is illegal in all the contexts we resolve like this.
8540 if (!ovl.HasFormOfMemberPointer &&
8541 isa<CXXMethodDecl>(fn) &&
8542 cast<CXXMethodDecl>(fn)->isInstance()) {
John McCall6dbba4f2011-10-11 23:14:30 +00008543 if (!complain) return false;
8544
8545 Diag(ovl.Expression->getExprLoc(),
8546 diag::err_bound_member_function)
8547 << 0 << ovl.Expression->getSourceRange();
8548
8549 // TODO: I believe we only end up here if there's a mix of
8550 // static and non-static candidates (otherwise the expression
8551 // would have 'bound member' type, not 'overload' type).
8552 // Ideally we would note which candidate was chosen and why
8553 // the static candidates were rejected.
8554 SrcExpr = ExprError();
8555 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008556 }
Douglas Gregordb2eae62011-03-16 19:16:25 +00008557
John McCall864c0412011-04-26 20:42:42 +00008558 // Fix the expresion to refer to 'fn'.
8559 SingleFunctionExpression =
John McCall6dbba4f2011-10-11 23:14:30 +00008560 Owned(FixOverloadedFunctionReference(SrcExpr.take(), found, fn));
John McCall864c0412011-04-26 20:42:42 +00008561
8562 // If desired, do function-to-pointer decay.
John McCall6dbba4f2011-10-11 23:14:30 +00008563 if (doFunctionPointerConverion) {
John McCall864c0412011-04-26 20:42:42 +00008564 SingleFunctionExpression =
8565 DefaultFunctionArrayLvalueConversion(SingleFunctionExpression.take());
John McCall6dbba4f2011-10-11 23:14:30 +00008566 if (SingleFunctionExpression.isInvalid()) {
8567 SrcExpr = ExprError();
8568 return true;
8569 }
8570 }
John McCall864c0412011-04-26 20:42:42 +00008571 }
8572
8573 if (!SingleFunctionExpression.isUsable()) {
8574 if (complain) {
8575 Diag(OpRangeForComplaining.getBegin(), DiagIDForComplaining)
8576 << ovl.Expression->getName()
8577 << DestTypeForComplaining
8578 << OpRangeForComplaining
8579 << ovl.Expression->getQualifierLoc().getSourceRange();
John McCall6dbba4f2011-10-11 23:14:30 +00008580 NoteAllOverloadCandidates(SrcExpr.get());
8581
8582 SrcExpr = ExprError();
8583 return true;
8584 }
8585
8586 return false;
John McCall864c0412011-04-26 20:42:42 +00008587 }
8588
John McCall6dbba4f2011-10-11 23:14:30 +00008589 SrcExpr = SingleFunctionExpression;
8590 return true;
Douglas Gregorfadb53b2011-03-12 01:48:56 +00008591}
8592
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008593/// \brief Add a single candidate to the overload set.
8594static void AddOverloadedCallCandidate(Sema &S,
John McCall9aa472c2010-03-19 07:35:19 +00008595 DeclAccessPair FoundDecl,
Douglas Gregor67714232011-03-03 02:41:12 +00008596 TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008597 Expr **Args, unsigned NumArgs,
8598 OverloadCandidateSet &CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00008599 bool PartialOverloading,
8600 bool KnownValid) {
John McCall9aa472c2010-03-19 07:35:19 +00008601 NamedDecl *Callee = FoundDecl.getDecl();
John McCallba135432009-11-21 08:51:07 +00008602 if (isa<UsingShadowDecl>(Callee))
8603 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
8604
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008605 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
Richard Smith2ced0442011-06-26 22:19:54 +00008606 if (ExplicitTemplateArgs) {
8607 assert(!KnownValid && "Explicit template arguments?");
8608 return;
8609 }
John McCall9aa472c2010-03-19 07:35:19 +00008610 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorc27d6c52010-04-16 17:41:49 +00008611 false, PartialOverloading);
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008612 return;
John McCallba135432009-11-21 08:51:07 +00008613 }
8614
8615 if (FunctionTemplateDecl *FuncTemplate
8616 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCall9aa472c2010-03-19 07:35:19 +00008617 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
8618 ExplicitTemplateArgs,
John McCallba135432009-11-21 08:51:07 +00008619 Args, NumArgs, CandidateSet);
John McCallba135432009-11-21 08:51:07 +00008620 return;
8621 }
8622
Richard Smith2ced0442011-06-26 22:19:54 +00008623 assert(!KnownValid && "unhandled case in overloaded call candidate");
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008624}
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008625
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008626/// \brief Add the overload candidates named by callee and/or found by argument
8627/// dependent lookup to the given overload set.
John McCall3b4294e2009-12-16 12:17:52 +00008628void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008629 Expr **Args, unsigned NumArgs,
8630 OverloadCandidateSet &CandidateSet,
8631 bool PartialOverloading) {
John McCallba135432009-11-21 08:51:07 +00008632
8633#ifndef NDEBUG
8634 // Verify that ArgumentDependentLookup is consistent with the rules
8635 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008636 //
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008637 // Let X be the lookup set produced by unqualified lookup (3.4.1)
8638 // and let Y be the lookup set produced by argument dependent
8639 // lookup (defined as follows). If X contains
8640 //
8641 // -- a declaration of a class member, or
8642 //
8643 // -- a block-scope function declaration that is not a
John McCallba135432009-11-21 08:51:07 +00008644 // using-declaration, or
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008645 //
8646 // -- a declaration that is neither a function or a function
8647 // template
8648 //
8649 // then Y is empty.
John McCallba135432009-11-21 08:51:07 +00008650
John McCall3b4294e2009-12-16 12:17:52 +00008651 if (ULE->requiresADL()) {
8652 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8653 E = ULE->decls_end(); I != E; ++I) {
8654 assert(!(*I)->getDeclContext()->isRecord());
8655 assert(isa<UsingShadowDecl>(*I) ||
8656 !(*I)->getDeclContext()->isFunctionOrMethod());
8657 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCallba135432009-11-21 08:51:07 +00008658 }
8659 }
8660#endif
8661
John McCall3b4294e2009-12-16 12:17:52 +00008662 // It would be nice to avoid this copy.
8663 TemplateArgumentListInfo TABuffer;
Douglas Gregor67714232011-03-03 02:41:12 +00008664 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00008665 if (ULE->hasExplicitTemplateArgs()) {
8666 ULE->copyTemplateArgumentsInto(TABuffer);
8667 ExplicitTemplateArgs = &TABuffer;
8668 }
8669
8670 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
8671 E = ULE->decls_end(); I != E; ++I)
John McCall9aa472c2010-03-19 07:35:19 +00008672 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008673 Args, NumArgs, CandidateSet,
Richard Smith2ced0442011-06-26 22:19:54 +00008674 PartialOverloading, /*KnownValid*/ true);
John McCallba135432009-11-21 08:51:07 +00008675
John McCall3b4294e2009-12-16 12:17:52 +00008676 if (ULE->requiresADL())
John McCall6e266892010-01-26 03:27:55 +00008677 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
8678 Args, NumArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008679 ExplicitTemplateArgs,
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008680 CandidateSet,
Richard Smithad762fc2011-04-14 22:09:26 +00008681 PartialOverloading,
8682 ULE->isStdAssociatedNamespace());
Douglas Gregor9c6a0e92009-09-22 15:41:20 +00008683}
John McCall578b69b2009-12-16 08:11:27 +00008684
Richard Smithf50e88a2011-06-05 22:42:48 +00008685/// Attempt to recover from an ill-formed use of a non-dependent name in a
8686/// template, where the non-dependent name was declared after the template
8687/// was defined. This is common in code written for a compilers which do not
8688/// correctly implement two-stage name lookup.
8689///
8690/// Returns true if a viable candidate was found and a diagnostic was issued.
8691static bool
8692DiagnoseTwoPhaseLookup(Sema &SemaRef, SourceLocation FnLoc,
8693 const CXXScopeSpec &SS, LookupResult &R,
8694 TemplateArgumentListInfo *ExplicitTemplateArgs,
8695 Expr **Args, unsigned NumArgs) {
8696 if (SemaRef.ActiveTemplateInstantiations.empty() || !SS.isEmpty())
8697 return false;
8698
8699 for (DeclContext *DC = SemaRef.CurContext; DC; DC = DC->getParent()) {
8700 SemaRef.LookupQualifiedName(R, DC);
8701
8702 if (!R.empty()) {
8703 R.suppressDiagnostics();
8704
8705 if (isa<CXXRecordDecl>(DC)) {
8706 // Don't diagnose names we find in classes; we get much better
8707 // diagnostics for these from DiagnoseEmptyLookup.
8708 R.clear();
8709 return false;
8710 }
8711
8712 OverloadCandidateSet Candidates(FnLoc);
8713 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
8714 AddOverloadedCallCandidate(SemaRef, I.getPair(),
8715 ExplicitTemplateArgs, Args, NumArgs,
Richard Smith2ced0442011-06-26 22:19:54 +00008716 Candidates, false, /*KnownValid*/ false);
Richard Smithf50e88a2011-06-05 22:42:48 +00008717
8718 OverloadCandidateSet::iterator Best;
Richard Smith2ced0442011-06-26 22:19:54 +00008719 if (Candidates.BestViableFunction(SemaRef, FnLoc, Best) != OR_Success) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008720 // No viable functions. Don't bother the user with notes for functions
8721 // which don't work and shouldn't be found anyway.
Richard Smith2ced0442011-06-26 22:19:54 +00008722 R.clear();
Richard Smithf50e88a2011-06-05 22:42:48 +00008723 return false;
Richard Smith2ced0442011-06-26 22:19:54 +00008724 }
Richard Smithf50e88a2011-06-05 22:42:48 +00008725
8726 // Find the namespaces where ADL would have looked, and suggest
8727 // declaring the function there instead.
8728 Sema::AssociatedNamespaceSet AssociatedNamespaces;
8729 Sema::AssociatedClassSet AssociatedClasses;
8730 SemaRef.FindAssociatedClassesAndNamespaces(Args, NumArgs,
8731 AssociatedNamespaces,
8732 AssociatedClasses);
8733 // Never suggest declaring a function within namespace 'std'.
Chandler Carruth74d487e2011-06-05 23:36:55 +00008734 Sema::AssociatedNamespaceSet SuggestedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00008735 if (DeclContext *Std = SemaRef.getStdNamespace()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008736 for (Sema::AssociatedNamespaceSet::iterator
8737 it = AssociatedNamespaces.begin(),
Chandler Carruth74d487e2011-06-05 23:36:55 +00008738 end = AssociatedNamespaces.end(); it != end; ++it) {
8739 if (!Std->Encloses(*it))
8740 SuggestedNamespaces.insert(*it);
8741 }
Chandler Carruth45cad4a2011-06-08 10:13:17 +00008742 } else {
8743 // Lacking the 'std::' namespace, use all of the associated namespaces.
8744 SuggestedNamespaces = AssociatedNamespaces;
Richard Smithf50e88a2011-06-05 22:42:48 +00008745 }
8746
8747 SemaRef.Diag(R.getNameLoc(), diag::err_not_found_by_two_phase_lookup)
8748 << R.getLookupName();
Chandler Carruth74d487e2011-06-05 23:36:55 +00008749 if (SuggestedNamespaces.empty()) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008750 SemaRef.Diag(Best->Function->getLocation(),
8751 diag::note_not_found_by_two_phase_lookup)
8752 << R.getLookupName() << 0;
Chandler Carruth74d487e2011-06-05 23:36:55 +00008753 } else if (SuggestedNamespaces.size() == 1) {
Richard Smithf50e88a2011-06-05 22:42:48 +00008754 SemaRef.Diag(Best->Function->getLocation(),
8755 diag::note_not_found_by_two_phase_lookup)
Chandler Carruth74d487e2011-06-05 23:36:55 +00008756 << R.getLookupName() << 1 << *SuggestedNamespaces.begin();
Richard Smithf50e88a2011-06-05 22:42:48 +00008757 } else {
8758 // FIXME: It would be useful to list the associated namespaces here,
8759 // but the diagnostics infrastructure doesn't provide a way to produce
8760 // a localized representation of a list of items.
8761 SemaRef.Diag(Best->Function->getLocation(),
8762 diag::note_not_found_by_two_phase_lookup)
8763 << R.getLookupName() << 2;
8764 }
8765
8766 // Try to recover by calling this function.
8767 return true;
8768 }
8769
8770 R.clear();
8771 }
8772
8773 return false;
8774}
8775
8776/// Attempt to recover from ill-formed use of a non-dependent operator in a
8777/// template, where the non-dependent operator was declared after the template
8778/// was defined.
8779///
8780/// Returns true if a viable candidate was found and a diagnostic was issued.
8781static bool
8782DiagnoseTwoPhaseOperatorLookup(Sema &SemaRef, OverloadedOperatorKind Op,
8783 SourceLocation OpLoc,
8784 Expr **Args, unsigned NumArgs) {
8785 DeclarationName OpName =
8786 SemaRef.Context.DeclarationNames.getCXXOperatorName(Op);
8787 LookupResult R(SemaRef, OpName, OpLoc, Sema::LookupOperatorName);
8788 return DiagnoseTwoPhaseLookup(SemaRef, OpLoc, CXXScopeSpec(), R,
8789 /*ExplicitTemplateArgs=*/0, Args, NumArgs);
8790}
8791
John McCall578b69b2009-12-16 08:11:27 +00008792/// Attempts to recover from a call where no functions were found.
8793///
8794/// Returns true if new candidates were found.
John McCall60d7b3a2010-08-24 06:29:42 +00008795static ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00008796BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall3b4294e2009-12-16 12:17:52 +00008797 UnresolvedLookupExpr *ULE,
8798 SourceLocation LParenLoc,
8799 Expr **Args, unsigned NumArgs,
Richard Smithf50e88a2011-06-05 22:42:48 +00008800 SourceLocation RParenLoc,
8801 bool EmptyLookup) {
John McCall578b69b2009-12-16 08:11:27 +00008802
8803 CXXScopeSpec SS;
Douglas Gregor4c9be892011-02-28 20:01:57 +00008804 SS.Adopt(ULE->getQualifierLoc());
John McCall578b69b2009-12-16 08:11:27 +00008805
John McCall3b4294e2009-12-16 12:17:52 +00008806 TemplateArgumentListInfo TABuffer;
Richard Smithf50e88a2011-06-05 22:42:48 +00008807 TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
John McCall3b4294e2009-12-16 12:17:52 +00008808 if (ULE->hasExplicitTemplateArgs()) {
8809 ULE->copyTemplateArgumentsInto(TABuffer);
8810 ExplicitTemplateArgs = &TABuffer;
8811 }
8812
John McCall578b69b2009-12-16 08:11:27 +00008813 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
8814 Sema::LookupOrdinaryName);
Richard Smithf50e88a2011-06-05 22:42:48 +00008815 if (!DiagnoseTwoPhaseLookup(SemaRef, Fn->getExprLoc(), SS, R,
8816 ExplicitTemplateArgs, Args, NumArgs) &&
8817 (!EmptyLookup ||
Kaelyn Uhrainf0c1d8f2011-08-03 20:36:05 +00008818 SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression,
Kaelyn Uhrainace5e762011-08-05 00:09:52 +00008819 ExplicitTemplateArgs, Args, NumArgs)))
John McCallf312b1e2010-08-26 23:41:50 +00008820 return ExprError();
John McCall578b69b2009-12-16 08:11:27 +00008821
John McCall3b4294e2009-12-16 12:17:52 +00008822 assert(!R.empty() && "lookup results empty despite recovery");
8823
8824 // Build an implicit member call if appropriate. Just drop the
8825 // casts and such from the call, we don't really care.
John McCallf312b1e2010-08-26 23:41:50 +00008826 ExprResult NewFn = ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00008827 if ((*R.begin())->isCXXClassMember())
Chandler Carruth6df868e2010-12-12 08:17:55 +00008828 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
8829 ExplicitTemplateArgs);
John McCall3b4294e2009-12-16 12:17:52 +00008830 else if (ExplicitTemplateArgs)
8831 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
8832 else
8833 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
8834
8835 if (NewFn.isInvalid())
John McCallf312b1e2010-08-26 23:41:50 +00008836 return ExprError();
John McCall3b4294e2009-12-16 12:17:52 +00008837
8838 // This shouldn't cause an infinite loop because we're giving it
Richard Smithf50e88a2011-06-05 22:42:48 +00008839 // an expression with viable lookup results, which should never
John McCall3b4294e2009-12-16 12:17:52 +00008840 // end up here.
John McCall9ae2f072010-08-23 23:25:46 +00008841 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregora1a04782010-09-09 16:33:13 +00008842 MultiExprArg(Args, NumArgs), RParenLoc);
John McCall578b69b2009-12-16 08:11:27 +00008843}
Douglas Gregord7a95972010-06-08 17:35:15 +00008844
Douglas Gregorf6b89692008-11-26 05:54:23 +00008845/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregorfa047642009-02-04 00:32:51 +00008846/// (which eventually refers to the declaration Func) and the call
8847/// arguments Args/NumArgs, attempt to resolve the function call down
8848/// to a specific function. If overload resolution succeeds, returns
8849/// the function declaration produced by overload
Douglas Gregor0a396682008-11-26 06:01:48 +00008850/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregorf6b89692008-11-26 05:54:23 +00008851/// arguments and Fn, and returns NULL.
John McCall60d7b3a2010-08-24 06:29:42 +00008852ExprResult
Douglas Gregor1aae80b2010-04-14 20:27:54 +00008853Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall3b4294e2009-12-16 12:17:52 +00008854 SourceLocation LParenLoc,
8855 Expr **Args, unsigned NumArgs,
Peter Collingbournee08ce652011-02-09 21:07:24 +00008856 SourceLocation RParenLoc,
8857 Expr *ExecConfig) {
John McCall3b4294e2009-12-16 12:17:52 +00008858#ifndef NDEBUG
8859 if (ULE->requiresADL()) {
8860 // To do ADL, we must have found an unqualified name.
8861 assert(!ULE->getQualifier() && "qualified name with ADL");
8862
8863 // We don't perform ADL for implicit declarations of builtins.
8864 // Verify that this was correctly set up.
8865 FunctionDecl *F;
8866 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
8867 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
8868 F->getBuiltinID() && F->isImplicit())
David Blaikieb219cfc2011-09-23 05:06:16 +00008869 llvm_unreachable("performing ADL for builtin");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00008870
John McCall3b4294e2009-12-16 12:17:52 +00008871 // We don't perform ADL in C.
8872 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
Richard Smithad762fc2011-04-14 22:09:26 +00008873 } else
8874 assert(!ULE->isStdAssociatedNamespace() &&
8875 "std is associated namespace but not doing ADL");
John McCall3b4294e2009-12-16 12:17:52 +00008876#endif
8877
John McCall5acb0c92011-10-17 18:40:02 +00008878 UnbridgedCastsSet UnbridgedCasts;
8879 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
8880 return ExprError();
8881
John McCall5769d612010-02-08 23:07:23 +00008882 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregor17330012009-02-04 15:01:18 +00008883
John McCall3b4294e2009-12-16 12:17:52 +00008884 // Add the functions denoted by the callee to the set of candidate
8885 // functions, including those from argument-dependent lookup.
8886 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCall578b69b2009-12-16 08:11:27 +00008887
8888 // If we found nothing, try to recover.
Richard Smithf50e88a2011-06-05 22:42:48 +00008889 // BuildRecoveryCallExpr diagnoses the error itself, so we just bail
8890 // out if it fails.
Francois Pichet0f74d1e2011-09-07 00:14:57 +00008891 if (CandidateSet.empty()) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00008892 // In Microsoft mode, if we are inside a template class member function then
8893 // create a type dependent CallExpr. The goal is to postpone name lookup
Francois Pichet0f74d1e2011-09-07 00:14:57 +00008894 // to instantiation time to be able to search into type dependent base
Sebastian Redl14b0c192011-09-24 17:48:00 +00008895 // classes.
Francois Pichetef04ecf2011-11-11 00:12:11 +00008896 if (getLangOptions().MicrosoftMode && CurContext->isDependentContext() &&
Francois Pichetc8ff9152011-11-25 01:10:54 +00008897 (isa<FunctionDecl>(CurContext) || isa<CXXRecordDecl>(CurContext))) {
Sebastian Redl14b0c192011-09-24 17:48:00 +00008898 CallExpr *CE = new (Context) CallExpr(Context, Fn, Args, NumArgs,
8899 Context.DependentTy, VK_RValue,
8900 RParenLoc);
8901 CE->setTypeDependent(true);
8902 return Owned(CE);
8903 }
Douglas Gregor1aae80b2010-04-14 20:27:54 +00008904 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Richard Smithf50e88a2011-06-05 22:42:48 +00008905 RParenLoc, /*EmptyLookup=*/true);
Francois Pichet0f74d1e2011-09-07 00:14:57 +00008906 }
John McCall578b69b2009-12-16 08:11:27 +00008907
John McCall5acb0c92011-10-17 18:40:02 +00008908 UnbridgedCasts.restore();
8909
Douglas Gregorf6b89692008-11-26 05:54:23 +00008910 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00008911 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall3b4294e2009-12-16 12:17:52 +00008912 case OR_Success: {
8913 FunctionDecl *FDecl = Best->Function;
Chandler Carruth25ca4212011-02-25 19:41:05 +00008914 MarkDeclarationReferenced(Fn->getExprLoc(), FDecl);
John McCall9aa472c2010-03-19 07:35:19 +00008915 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
John McCall5acb0c92011-10-17 18:40:02 +00008916 DiagnoseUseOfDecl(FDecl, ULE->getNameLoc());
John McCall6bb80172010-03-30 21:47:33 +00008917 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Peter Collingbournee08ce652011-02-09 21:07:24 +00008918 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs, RParenLoc,
8919 ExecConfig);
John McCall3b4294e2009-12-16 12:17:52 +00008920 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00008921
Richard Smithf50e88a2011-06-05 22:42:48 +00008922 case OR_No_Viable_Function: {
8923 // Try to recover by looking for viable functions which the user might
8924 // have meant to call.
8925 ExprResult Recovery = BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc,
8926 Args, NumArgs, RParenLoc,
8927 /*EmptyLookup=*/false);
8928 if (!Recovery.isInvalid())
8929 return Recovery;
8930
Chris Lattner4330d652009-02-17 07:29:20 +00008931 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregorf6b89692008-11-26 05:54:23 +00008932 diag::err_ovl_no_viable_function_in_call)
John McCall3b4294e2009-12-16 12:17:52 +00008933 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008934 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00008935 break;
Richard Smithf50e88a2011-06-05 22:42:48 +00008936 }
Douglas Gregorf6b89692008-11-26 05:54:23 +00008937
8938 case OR_Ambiguous:
8939 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall3b4294e2009-12-16 12:17:52 +00008940 << ULE->getName() << Fn->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00008941 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf6b89692008-11-26 05:54:23 +00008942 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008943
8944 case OR_Deleted:
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00008945 {
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00008946 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
8947 << Best->Function->isDeleted()
8948 << ULE->getName()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00008949 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00008950 << Fn->getSourceRange();
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00008951 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Argyrios Kyrtzidis0d579b62011-11-04 15:58:13 +00008952
8953 // We emitted an error for the unvailable/deleted function call but keep
8954 // the call in the AST.
8955 FunctionDecl *FDecl = Best->Function;
8956 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
8957 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
8958 RParenLoc, ExecConfig);
Fariborz Jahanian2b982b72011-02-25 18:38:59 +00008959 }
Douglas Gregor48f3bb92009-02-18 21:56:37 +00008960 break;
Douglas Gregorf6b89692008-11-26 05:54:23 +00008961 }
8962
Douglas Gregorff331c12010-07-25 18:17:45 +00008963 // Overload resolution failed.
John McCall3b4294e2009-12-16 12:17:52 +00008964 return ExprError();
Douglas Gregorf6b89692008-11-26 05:54:23 +00008965}
8966
John McCall6e266892010-01-26 03:27:55 +00008967static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall7453ed42009-11-22 00:44:51 +00008968 return Functions.size() > 1 ||
8969 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
8970}
8971
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008972/// \brief Create a unary operation that may resolve to an overloaded
8973/// operator.
8974///
8975/// \param OpLoc The location of the operator itself (e.g., '*').
8976///
8977/// \param OpcIn The UnaryOperator::Opcode that describes this
8978/// operator.
8979///
8980/// \param Functions The set of non-member functions that will be
8981/// considered by overload resolution. The caller needs to build this
8982/// set based on the context using, e.g.,
8983/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
8984/// set should not contain any member functions; those will be added
8985/// by CreateOverloadedUnaryOp().
8986///
8987/// \param input The input argument.
John McCall60d7b3a2010-08-24 06:29:42 +00008988ExprResult
John McCall6e266892010-01-26 03:27:55 +00008989Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
8990 const UnresolvedSetImpl &Fns,
John McCall9ae2f072010-08-23 23:25:46 +00008991 Expr *Input) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008992 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008993
8994 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
8995 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
8996 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnara25777432010-08-11 22:01:17 +00008997 // TODO: provide better source location info.
8998 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00008999
John McCall5acb0c92011-10-17 18:40:02 +00009000 if (checkPlaceholderForOverload(*this, Input))
9001 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009002
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009003 Expr *Args[2] = { Input, 0 };
9004 unsigned NumArgs = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00009005
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009006 // For post-increment and post-decrement, add the implicit '0' as
9007 // the second argument, so that we know this is a post-increment or
9008 // post-decrement.
John McCall2de56d12010-08-25 11:45:40 +00009009 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009010 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00009011 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
9012 SourceLocation());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009013 NumArgs = 2;
9014 }
9015
9016 if (Input->isTypeDependent()) {
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009017 if (Fns.empty())
John McCall9ae2f072010-08-23 23:25:46 +00009018 return Owned(new (Context) UnaryOperator(Input,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009019 Opc,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009020 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009021 VK_RValue, OK_Ordinary,
Douglas Gregor1ec8ef72010-06-17 15:46:20 +00009022 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009023
John McCallc373d482010-01-27 01:50:18 +00009024 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCallba135432009-11-21 08:51:07 +00009025 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009026 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009027 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009028 /*ADL*/ true, IsOverloaded(Fns),
9029 Fns.begin(), Fns.end());
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009030 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009031 &Args[0], NumArgs,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009032 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009033 VK_RValue,
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009034 OpLoc));
9035 }
9036
9037 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009038 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009039
9040 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00009041 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009042
9043 // Add operator candidates that are member functions.
9044 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
9045
John McCall6e266892010-01-26 03:27:55 +00009046 // Add candidates from ADL.
9047 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregordc81c882010-02-05 05:15:43 +00009048 Args, NumArgs,
John McCall6e266892010-01-26 03:27:55 +00009049 /*ExplicitTemplateArgs*/ 0,
9050 CandidateSet);
9051
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009052 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009053 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009054
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009055 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9056
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009057 // Perform overload resolution.
9058 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009059 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009060 case OR_Success: {
9061 // We found a built-in operator or an overloaded operator.
9062 FunctionDecl *FnDecl = Best->Function;
Mike Stump1eb44332009-09-09 15:08:12 +00009063
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009064 if (FnDecl) {
9065 // We matched an overloaded operator. Build a call to that
9066 // operator.
Mike Stump1eb44332009-09-09 15:08:12 +00009067
Chandler Carruth25ca4212011-02-25 19:41:05 +00009068 MarkDeclarationReferenced(OpLoc, FnDecl);
9069
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009070 // Convert the arguments.
9071 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall9aa472c2010-03-19 07:35:19 +00009072 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009073
John Wiegley429bb272011-04-08 18:41:53 +00009074 ExprResult InputRes =
9075 PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
9076 Best->FoundDecl, Method);
9077 if (InputRes.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009078 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009079 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009080 } else {
9081 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00009082 ExprResult InputInit
Douglas Gregore1a5c172009-12-23 17:40:29 +00009083 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009084 Context,
Douglas Gregorbaecfed2009-12-23 00:02:00 +00009085 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009086 SourceLocation(),
John McCall9ae2f072010-08-23 23:25:46 +00009087 Input);
Douglas Gregore1a5c172009-12-23 17:40:29 +00009088 if (InputInit.isInvalid())
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009089 return ExprError();
John McCall9ae2f072010-08-23 23:25:46 +00009090 Input = InputInit.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009091 }
9092
John McCallb697e082010-05-06 18:15:07 +00009093 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9094
John McCallf89e55a2010-11-18 06:31:45 +00009095 // Determine the result type.
9096 QualType ResultTy = FnDecl->getResultType();
9097 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9098 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump1eb44332009-09-09 15:08:12 +00009099
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009100 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009101 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9102 HadMultipleCandidates);
John Wiegley429bb272011-04-08 18:41:53 +00009103 if (FnExpr.isInvalid())
9104 return ExprError();
Mike Stump1eb44332009-09-09 15:08:12 +00009105
Eli Friedman4c3b8962009-11-18 03:58:17 +00009106 Args[0] = Input;
John McCall9ae2f072010-08-23 23:25:46 +00009107 CallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009108 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009109 Args, NumArgs, ResultTy, VK, OpLoc);
John McCallb697e082010-05-06 18:15:07 +00009110
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009111 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson26a2a072009-10-13 21:19:37 +00009112 FnDecl))
9113 return ExprError();
9114
John McCall9ae2f072010-08-23 23:25:46 +00009115 return MaybeBindToTemporary(TheCall);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009116 } else {
9117 // We matched a built-in operator. Convert the arguments, then
9118 // break out so that we will build the appropriate built-in
9119 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009120 ExprResult InputRes =
9121 PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
9122 Best->Conversions[0], AA_Passing);
9123 if (InputRes.isInvalid())
9124 return ExprError();
9125 Input = InputRes.take();
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009126 break;
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009127 }
John Wiegley429bb272011-04-08 18:41:53 +00009128 }
9129
9130 case OR_No_Viable_Function:
Richard Smithf50e88a2011-06-05 22:42:48 +00009131 // This is an erroneous use of an operator which can be overloaded by
9132 // a non-member function. Check for non-member operators which were
9133 // defined too late to be candidates.
9134 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, NumArgs))
9135 // FIXME: Recover by calling the found function.
9136 return ExprError();
9137
John Wiegley429bb272011-04-08 18:41:53 +00009138 // No viable function; fall through to handling this as a
9139 // built-in operator, which will produce an error message for us.
9140 break;
9141
9142 case OR_Ambiguous:
9143 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
9144 << UnaryOperator::getOpcodeStr(Opc)
9145 << Input->getType()
9146 << Input->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00009147 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs,
John Wiegley429bb272011-04-08 18:41:53 +00009148 UnaryOperator::getOpcodeStr(Opc), OpLoc);
9149 return ExprError();
9150
9151 case OR_Deleted:
9152 Diag(OpLoc, diag::err_ovl_deleted_oper)
9153 << Best->Function->isDeleted()
9154 << UnaryOperator::getOpcodeStr(Opc)
9155 << getDeletedOrUnavailableSuffix(Best->Function)
9156 << Input->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00009157 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs,
9158 UnaryOperator::getOpcodeStr(Opc), OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009159 return ExprError();
9160 }
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009161
9162 // Either we found no viable overloaded operator or we matched a
9163 // built-in operator. In either case, fall through to trying to
9164 // build a built-in operation.
John McCall9ae2f072010-08-23 23:25:46 +00009165 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009166}
9167
Douglas Gregor063daf62009-03-13 18:40:31 +00009168/// \brief Create a binary operation that may resolve to an overloaded
9169/// operator.
9170///
9171/// \param OpLoc The location of the operator itself (e.g., '+').
9172///
9173/// \param OpcIn The BinaryOperator::Opcode that describes this
9174/// operator.
9175///
9176/// \param Functions The set of non-member functions that will be
9177/// considered by overload resolution. The caller needs to build this
9178/// set based on the context using, e.g.,
9179/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
9180/// set should not contain any member functions; those will be added
9181/// by CreateOverloadedBinOp().
9182///
9183/// \param LHS Left-hand argument.
9184/// \param RHS Right-hand argument.
John McCall60d7b3a2010-08-24 06:29:42 +00009185ExprResult
Douglas Gregor063daf62009-03-13 18:40:31 +00009186Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00009187 unsigned OpcIn,
John McCall6e266892010-01-26 03:27:55 +00009188 const UnresolvedSetImpl &Fns,
Douglas Gregor063daf62009-03-13 18:40:31 +00009189 Expr *LHS, Expr *RHS) {
Douglas Gregor063daf62009-03-13 18:40:31 +00009190 Expr *Args[2] = { LHS, RHS };
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009191 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor063daf62009-03-13 18:40:31 +00009192
9193 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
9194 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
9195 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
9196
9197 // If either side is type-dependent, create an appropriate dependent
9198 // expression.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009199 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall6e266892010-01-26 03:27:55 +00009200 if (Fns.empty()) {
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009201 // If there are no functions to store, just build a dependent
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009202 // BinaryOperator or CompoundAssignment.
John McCall2de56d12010-08-25 11:45:40 +00009203 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009204 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCallf89e55a2010-11-18 06:31:45 +00009205 Context.DependentTy,
9206 VK_RValue, OK_Ordinary,
9207 OpLoc));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009208
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009209 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
9210 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009211 VK_LValue,
9212 OK_Ordinary,
Douglas Gregor6ca7cfb2009-11-05 00:51:44 +00009213 Context.DependentTy,
9214 Context.DependentTy,
9215 OpLoc));
9216 }
John McCall6e266892010-01-26 03:27:55 +00009217
9218 // FIXME: save results of ADL from here?
John McCallc373d482010-01-27 01:50:18 +00009219 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00009220 // TODO: provide better source location info in DNLoc component.
9221 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCallba135432009-11-21 08:51:07 +00009222 UnresolvedLookupExpr *Fn
Douglas Gregor4c9be892011-02-28 20:01:57 +00009223 = UnresolvedLookupExpr::Create(Context, NamingClass,
9224 NestedNameSpecifierLoc(), OpNameInfo,
9225 /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009226 Fns.begin(), Fns.end());
Douglas Gregor063daf62009-03-13 18:40:31 +00009227 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump1eb44332009-09-09 15:08:12 +00009228 Args, 2,
Douglas Gregor063daf62009-03-13 18:40:31 +00009229 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009230 VK_RValue,
Douglas Gregor063daf62009-03-13 18:40:31 +00009231 OpLoc));
9232 }
9233
John McCall5acb0c92011-10-17 18:40:02 +00009234 // Always do placeholder-like conversions on the RHS.
9235 if (checkPlaceholderForOverload(*this, Args[1]))
9236 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009237
John McCall3c3b7f92011-10-25 17:37:35 +00009238 // Do placeholder-like conversion on the LHS; note that we should
9239 // not get here with a PseudoObject LHS.
9240 assert(Args[0]->getObjectKind() != OK_ObjCProperty);
John McCall5acb0c92011-10-17 18:40:02 +00009241 if (checkPlaceholderForOverload(*this, Args[0]))
9242 return ExprError();
9243
Sebastian Redl275c2b42009-11-18 23:10:33 +00009244 // If this is the assignment operator, we only perform overload resolution
9245 // if the left-hand side is a class or enumeration type. This is actually
9246 // a hack. The standard requires that we do overload resolution between the
9247 // various built-in candidates, but as DR507 points out, this can lead to
9248 // problems. So we do it this way, which pretty much follows what GCC does.
9249 // Note that we go the traditional code path for compound assignment forms.
John McCall2de56d12010-08-25 11:45:40 +00009250 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009251 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00009252
John McCall0e800c92010-12-04 08:14:53 +00009253 // If this is the .* operator, which is not overloadable, just
9254 // create a built-in binary operator.
9255 if (Opc == BO_PtrMemD)
9256 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
9257
Douglas Gregorbc736fc2009-03-13 23:49:33 +00009258 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009259 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009260
9261 // Add the candidates from the given function set.
John McCall6e266892010-01-26 03:27:55 +00009262 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor063daf62009-03-13 18:40:31 +00009263
9264 // Add operator candidates that are member functions.
9265 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
9266
John McCall6e266892010-01-26 03:27:55 +00009267 // Add candidates from ADL.
9268 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
9269 Args, 2,
9270 /*ExplicitTemplateArgs*/ 0,
9271 CandidateSet);
9272
Douglas Gregor063daf62009-03-13 18:40:31 +00009273 // Add builtin operator candidates.
Douglas Gregor573d9c32009-10-21 23:19:44 +00009274 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor063daf62009-03-13 18:40:31 +00009275
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009276 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9277
Douglas Gregor063daf62009-03-13 18:40:31 +00009278 // Perform overload resolution.
9279 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009280 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl3201f6b2009-04-16 17:51:27 +00009281 case OR_Success: {
Douglas Gregor063daf62009-03-13 18:40:31 +00009282 // We found a built-in operator or an overloaded operator.
9283 FunctionDecl *FnDecl = Best->Function;
9284
9285 if (FnDecl) {
9286 // We matched an overloaded operator. Build a call to that
9287 // operator.
9288
Chandler Carruth25ca4212011-02-25 19:41:05 +00009289 MarkDeclarationReferenced(OpLoc, FnDecl);
9290
Douglas Gregor063daf62009-03-13 18:40:31 +00009291 // Convert the arguments.
9292 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCall5357b612010-01-28 01:42:12 +00009293 // Best->Access is only meaningful for class members.
John McCall9aa472c2010-03-19 07:35:19 +00009294 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCall5357b612010-01-28 01:42:12 +00009295
Chandler Carruth6df868e2010-12-12 08:17:55 +00009296 ExprResult Arg1 =
9297 PerformCopyInitialization(
9298 InitializedEntity::InitializeParameter(Context,
9299 FnDecl->getParamDecl(0)),
9300 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009301 if (Arg1.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009302 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009303
John Wiegley429bb272011-04-08 18:41:53 +00009304 ExprResult Arg0 =
9305 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9306 Best->FoundDecl, Method);
9307 if (Arg0.isInvalid())
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009308 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009309 Args[0] = Arg0.takeAs<Expr>();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009310 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00009311 } else {
9312 // Convert the arguments.
Chandler Carruth6df868e2010-12-12 08:17:55 +00009313 ExprResult Arg0 = PerformCopyInitialization(
9314 InitializedEntity::InitializeParameter(Context,
9315 FnDecl->getParamDecl(0)),
9316 SourceLocation(), Owned(Args[0]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009317 if (Arg0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009318 return ExprError();
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009319
Chandler Carruth6df868e2010-12-12 08:17:55 +00009320 ExprResult Arg1 =
9321 PerformCopyInitialization(
9322 InitializedEntity::InitializeParameter(Context,
9323 FnDecl->getParamDecl(1)),
9324 SourceLocation(), Owned(Args[1]));
Douglas Gregor4c2458a2009-12-22 21:44:34 +00009325 if (Arg1.isInvalid())
9326 return ExprError();
9327 Args[0] = LHS = Arg0.takeAs<Expr>();
9328 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor063daf62009-03-13 18:40:31 +00009329 }
9330
John McCallb697e082010-05-06 18:15:07 +00009331 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
9332
John McCallf89e55a2010-11-18 06:31:45 +00009333 // Determine the result type.
9334 QualType ResultTy = FnDecl->getResultType();
9335 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9336 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor063daf62009-03-13 18:40:31 +00009337
9338 // Build the actual expression node.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009339 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9340 HadMultipleCandidates, OpLoc);
John Wiegley429bb272011-04-08 18:41:53 +00009341 if (FnExpr.isInvalid())
9342 return ExprError();
Douglas Gregor063daf62009-03-13 18:40:31 +00009343
John McCall9ae2f072010-08-23 23:25:46 +00009344 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +00009345 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +00009346 Args, 2, ResultTy, VK, OpLoc);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009347
9348 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +00009349 FnDecl))
9350 return ExprError();
9351
John McCall9ae2f072010-08-23 23:25:46 +00009352 return MaybeBindToTemporary(TheCall);
Douglas Gregor063daf62009-03-13 18:40:31 +00009353 } else {
9354 // We matched a built-in operator. Convert the arguments, then
9355 // break out so that we will build the appropriate built-in
9356 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009357 ExprResult ArgsRes0 =
9358 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9359 Best->Conversions[0], AA_Passing);
9360 if (ArgsRes0.isInvalid())
Douglas Gregor063daf62009-03-13 18:40:31 +00009361 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009362 Args[0] = ArgsRes0.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00009363
John Wiegley429bb272011-04-08 18:41:53 +00009364 ExprResult ArgsRes1 =
9365 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9366 Best->Conversions[1], AA_Passing);
9367 if (ArgsRes1.isInvalid())
9368 return ExprError();
9369 Args[1] = ArgsRes1.take();
Douglas Gregor063daf62009-03-13 18:40:31 +00009370 break;
9371 }
9372 }
9373
Douglas Gregor33074752009-09-30 21:46:01 +00009374 case OR_No_Viable_Function: {
9375 // C++ [over.match.oper]p9:
9376 // If the operator is the operator , [...] and there are no
9377 // viable functions, then the operator is assumed to be the
9378 // built-in operator and interpreted according to clause 5.
John McCall2de56d12010-08-25 11:45:40 +00009379 if (Opc == BO_Comma)
Douglas Gregor33074752009-09-30 21:46:01 +00009380 break;
9381
Chandler Carruth6df868e2010-12-12 08:17:55 +00009382 // For class as left operand for assignment or compound assigment
9383 // operator do not fall through to handling in built-in, but report that
9384 // no overloaded assignment operator found
John McCall60d7b3a2010-08-24 06:29:42 +00009385 ExprResult Result = ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009386 if (Args[0]->getType()->isRecordType() &&
John McCall2de56d12010-08-25 11:45:40 +00009387 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl8593c782009-05-21 11:50:50 +00009388 Diag(OpLoc, diag::err_ovl_no_viable_oper)
9389 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009390 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor33074752009-09-30 21:46:01 +00009391 } else {
Richard Smithf50e88a2011-06-05 22:42:48 +00009392 // This is an erroneous use of an operator which can be overloaded by
9393 // a non-member function. Check for non-member operators which were
9394 // defined too late to be candidates.
9395 if (DiagnoseTwoPhaseOperatorLookup(*this, Op, OpLoc, Args, 2))
9396 // FIXME: Recover by calling the found function.
9397 return ExprError();
9398
Douglas Gregor33074752009-09-30 21:46:01 +00009399 // No viable function; try to create a built-in operation, which will
9400 // produce an error. Then, show the non-viable candidates.
9401 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl8593c782009-05-21 11:50:50 +00009402 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009403 assert(Result.isInvalid() &&
Douglas Gregor33074752009-09-30 21:46:01 +00009404 "C++ binary operator overloading is missing candidates!");
9405 if (Result.isInvalid())
John McCall120d63c2010-08-24 20:38:10 +00009406 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9407 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor33074752009-09-30 21:46:01 +00009408 return move(Result);
9409 }
Douglas Gregor063daf62009-03-13 18:40:31 +00009410
9411 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00009412 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor063daf62009-03-13 18:40:31 +00009413 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregorae2cf762010-11-13 20:06:38 +00009414 << Args[0]->getType() << Args[1]->getType()
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009415 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009416 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9417 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009418 return ExprError();
9419
9420 case OR_Deleted:
9421 Diag(OpLoc, diag::err_ovl_deleted_oper)
9422 << Best->Function->isDeleted()
9423 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009424 << getDeletedOrUnavailableSuffix(Best->Function)
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009425 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Eli Friedman1795d372011-08-26 19:46:22 +00009426 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9427 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor063daf62009-03-13 18:40:31 +00009428 return ExprError();
John McCall1d318332010-01-12 00:44:57 +00009429 }
Douglas Gregor063daf62009-03-13 18:40:31 +00009430
Douglas Gregor33074752009-09-30 21:46:01 +00009431 // We matched a built-in operator; build it.
Douglas Gregorc3384cb2009-08-26 17:08:25 +00009432 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor063daf62009-03-13 18:40:31 +00009433}
9434
John McCall60d7b3a2010-08-24 06:29:42 +00009435ExprResult
Sebastian Redlf322ed62009-10-29 20:17:01 +00009436Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
9437 SourceLocation RLoc,
John McCall9ae2f072010-08-23 23:25:46 +00009438 Expr *Base, Expr *Idx) {
9439 Expr *Args[2] = { Base, Idx };
Sebastian Redlf322ed62009-10-29 20:17:01 +00009440 DeclarationName OpName =
9441 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
9442
9443 // If either side is type-dependent, create an appropriate dependent
9444 // expression.
9445 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
9446
John McCallc373d482010-01-27 01:50:18 +00009447 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnara25777432010-08-11 22:01:17 +00009448 // CHECKME: no 'operator' keyword?
9449 DeclarationNameInfo OpNameInfo(OpName, LLoc);
9450 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCallba135432009-11-21 08:51:07 +00009451 UnresolvedLookupExpr *Fn
Douglas Gregorbebbe0d2010-12-15 01:34:56 +00009452 = UnresolvedLookupExpr::Create(Context, NamingClass,
Douglas Gregor4c9be892011-02-28 20:01:57 +00009453 NestedNameSpecifierLoc(), OpNameInfo,
Douglas Gregor5a84dec2010-05-23 18:57:34 +00009454 /*ADL*/ true, /*Overloaded*/ false,
9455 UnresolvedSetIterator(),
9456 UnresolvedSetIterator());
John McCallf7a1a742009-11-24 19:00:30 +00009457 // Can't add any actual overloads yet
Sebastian Redlf322ed62009-10-29 20:17:01 +00009458
Sebastian Redlf322ed62009-10-29 20:17:01 +00009459 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
9460 Args, 2,
9461 Context.DependentTy,
John McCallf89e55a2010-11-18 06:31:45 +00009462 VK_RValue,
Sebastian Redlf322ed62009-10-29 20:17:01 +00009463 RLoc));
9464 }
9465
John McCall5acb0c92011-10-17 18:40:02 +00009466 // Handle placeholders on both operands.
9467 if (checkPlaceholderForOverload(*this, Args[0]))
9468 return ExprError();
9469 if (checkPlaceholderForOverload(*this, Args[1]))
9470 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009471
Sebastian Redlf322ed62009-10-29 20:17:01 +00009472 // Build an empty overload set.
John McCall5769d612010-02-08 23:07:23 +00009473 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009474
9475 // Subscript can only be overloaded as a member function.
9476
9477 // Add operator candidates that are member functions.
9478 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9479
9480 // Add builtin operator candidates.
9481 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
9482
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009483 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9484
Sebastian Redlf322ed62009-10-29 20:17:01 +00009485 // Perform overload resolution.
9486 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009487 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redlf322ed62009-10-29 20:17:01 +00009488 case OR_Success: {
9489 // We found a built-in operator or an overloaded operator.
9490 FunctionDecl *FnDecl = Best->Function;
9491
9492 if (FnDecl) {
9493 // We matched an overloaded operator. Build a call to that
9494 // operator.
9495
Chandler Carruth25ca4212011-02-25 19:41:05 +00009496 MarkDeclarationReferenced(LLoc, FnDecl);
9497
John McCall9aa472c2010-03-19 07:35:19 +00009498 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009499 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCallc373d482010-01-27 01:50:18 +00009500
Sebastian Redlf322ed62009-10-29 20:17:01 +00009501 // Convert the arguments.
9502 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
John Wiegley429bb272011-04-08 18:41:53 +00009503 ExprResult Arg0 =
9504 PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
9505 Best->FoundDecl, Method);
9506 if (Arg0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +00009507 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009508 Args[0] = Arg0.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +00009509
Anders Carlsson38f88ab2010-01-29 18:37:50 +00009510 // Convert the arguments.
John McCall60d7b3a2010-08-24 06:29:42 +00009511 ExprResult InputInit
Anders Carlsson38f88ab2010-01-29 18:37:50 +00009512 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +00009513 Context,
Anders Carlsson38f88ab2010-01-29 18:37:50 +00009514 FnDecl->getParamDecl(0)),
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009515 SourceLocation(),
Anders Carlsson38f88ab2010-01-29 18:37:50 +00009516 Owned(Args[1]));
9517 if (InputInit.isInvalid())
9518 return ExprError();
9519
9520 Args[1] = InputInit.takeAs<Expr>();
9521
Sebastian Redlf322ed62009-10-29 20:17:01 +00009522 // Determine the result type
John McCallf89e55a2010-11-18 06:31:45 +00009523 QualType ResultTy = FnDecl->getResultType();
9524 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
9525 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009526
9527 // Build the actual expression node.
Douglas Gregor5b8968c2011-07-15 16:25:15 +00009528 DeclarationNameLoc LocInfo;
9529 LocInfo.CXXOperatorName.BeginOpNameLoc = LLoc.getRawEncoding();
9530 LocInfo.CXXOperatorName.EndOpNameLoc = RLoc.getRawEncoding();
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009531 ExprResult FnExpr = CreateFunctionRefExpr(*this, FnDecl,
9532 HadMultipleCandidates,
9533 LLoc, LocInfo);
John Wiegley429bb272011-04-08 18:41:53 +00009534 if (FnExpr.isInvalid())
9535 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00009536
John McCall9ae2f072010-08-23 23:25:46 +00009537 CXXOperatorCallExpr *TheCall =
9538 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
John Wiegley429bb272011-04-08 18:41:53 +00009539 FnExpr.take(), Args, 2,
John McCallf89e55a2010-11-18 06:31:45 +00009540 ResultTy, VK, RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009541
John McCall9ae2f072010-08-23 23:25:46 +00009542 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redlf322ed62009-10-29 20:17:01 +00009543 FnDecl))
9544 return ExprError();
9545
John McCall9ae2f072010-08-23 23:25:46 +00009546 return MaybeBindToTemporary(TheCall);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009547 } else {
9548 // We matched a built-in operator. Convert the arguments, then
9549 // break out so that we will build the appropriate built-in
9550 // operator node.
John Wiegley429bb272011-04-08 18:41:53 +00009551 ExprResult ArgsRes0 =
9552 PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
9553 Best->Conversions[0], AA_Passing);
9554 if (ArgsRes0.isInvalid())
Sebastian Redlf322ed62009-10-29 20:17:01 +00009555 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009556 Args[0] = ArgsRes0.take();
9557
9558 ExprResult ArgsRes1 =
9559 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
9560 Best->Conversions[1], AA_Passing);
9561 if (ArgsRes1.isInvalid())
9562 return ExprError();
9563 Args[1] = ArgsRes1.take();
Sebastian Redlf322ed62009-10-29 20:17:01 +00009564
9565 break;
9566 }
9567 }
9568
9569 case OR_No_Viable_Function: {
John McCall1eb3e102010-01-07 02:04:15 +00009570 if (CandidateSet.empty())
9571 Diag(LLoc, diag::err_ovl_no_oper)
9572 << Args[0]->getType() << /*subscript*/ 0
9573 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
9574 else
9575 Diag(LLoc, diag::err_ovl_no_viable_subscript)
9576 << Args[0]->getType()
9577 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009578 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9579 "[]", LLoc);
John McCall1eb3e102010-01-07 02:04:15 +00009580 return ExprError();
Sebastian Redlf322ed62009-10-29 20:17:01 +00009581 }
9582
9583 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +00009584 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009585 << "[]"
Douglas Gregorae2cf762010-11-13 20:06:38 +00009586 << Args[0]->getType() << Args[1]->getType()
9587 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009588 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
9589 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009590 return ExprError();
9591
9592 case OR_Deleted:
9593 Diag(LLoc, diag::err_ovl_deleted_oper)
9594 << Best->Function->isDeleted() << "[]"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009595 << getDeletedOrUnavailableSuffix(Best->Function)
Sebastian Redlf322ed62009-10-29 20:17:01 +00009596 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009597 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
9598 "[]", LLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009599 return ExprError();
9600 }
9601
9602 // We matched a built-in operator; build it.
John McCall9ae2f072010-08-23 23:25:46 +00009603 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redlf322ed62009-10-29 20:17:01 +00009604}
9605
Douglas Gregor88a35142008-12-22 05:46:06 +00009606/// BuildCallToMemberFunction - Build a call to a member
9607/// function. MemExpr is the expression that refers to the member
9608/// function (and includes the object parameter), Args/NumArgs are the
9609/// arguments to the function call (not including the object
9610/// parameter). The caller needs to validate that the member
John McCall864c0412011-04-26 20:42:42 +00009611/// expression refers to a non-static member function or an overloaded
9612/// member function.
John McCall60d7b3a2010-08-24 06:29:42 +00009613ExprResult
Mike Stump1eb44332009-09-09 15:08:12 +00009614Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
9615 SourceLocation LParenLoc, Expr **Args,
Douglas Gregora1a04782010-09-09 16:33:13 +00009616 unsigned NumArgs, SourceLocation RParenLoc) {
John McCall864c0412011-04-26 20:42:42 +00009617 assert(MemExprE->getType() == Context.BoundMemberTy ||
9618 MemExprE->getType() == Context.OverloadTy);
9619
Douglas Gregor88a35142008-12-22 05:46:06 +00009620 // Dig out the member expression. This holds both the object
9621 // argument and the member function we're referring to.
John McCall129e2df2009-11-30 22:42:35 +00009622 Expr *NakedMemExpr = MemExprE->IgnoreParens();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009623
John McCall864c0412011-04-26 20:42:42 +00009624 // Determine whether this is a call to a pointer-to-member function.
9625 if (BinaryOperator *op = dyn_cast<BinaryOperator>(NakedMemExpr)) {
9626 assert(op->getType() == Context.BoundMemberTy);
9627 assert(op->getOpcode() == BO_PtrMemD || op->getOpcode() == BO_PtrMemI);
9628
9629 QualType fnType =
9630 op->getRHS()->getType()->castAs<MemberPointerType>()->getPointeeType();
9631
9632 const FunctionProtoType *proto = fnType->castAs<FunctionProtoType>();
9633 QualType resultType = proto->getCallResultType(Context);
9634 ExprValueKind valueKind = Expr::getValueKindForType(proto->getResultType());
9635
9636 // Check that the object type isn't more qualified than the
9637 // member function we're calling.
9638 Qualifiers funcQuals = Qualifiers::fromCVRMask(proto->getTypeQuals());
9639
9640 QualType objectType = op->getLHS()->getType();
9641 if (op->getOpcode() == BO_PtrMemI)
9642 objectType = objectType->castAs<PointerType>()->getPointeeType();
9643 Qualifiers objectQuals = objectType.getQualifiers();
9644
9645 Qualifiers difference = objectQuals - funcQuals;
9646 difference.removeObjCGCAttr();
9647 difference.removeAddressSpace();
9648 if (difference) {
9649 std::string qualsString = difference.getAsString();
9650 Diag(LParenLoc, diag::err_pointer_to_member_call_drops_quals)
9651 << fnType.getUnqualifiedType()
9652 << qualsString
9653 << (qualsString.find(' ') == std::string::npos ? 1 : 2);
9654 }
9655
9656 CXXMemberCallExpr *call
9657 = new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
9658 resultType, valueKind, RParenLoc);
9659
9660 if (CheckCallReturnType(proto->getResultType(),
9661 op->getRHS()->getSourceRange().getBegin(),
9662 call, 0))
9663 return ExprError();
9664
9665 if (ConvertArgumentsForCall(call, op, 0, proto, Args, NumArgs, RParenLoc))
9666 return ExprError();
9667
9668 return MaybeBindToTemporary(call);
9669 }
9670
John McCall5acb0c92011-10-17 18:40:02 +00009671 UnbridgedCastsSet UnbridgedCasts;
9672 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9673 return ExprError();
9674
John McCall129e2df2009-11-30 22:42:35 +00009675 MemberExpr *MemExpr;
Douglas Gregor88a35142008-12-22 05:46:06 +00009676 CXXMethodDecl *Method = 0;
John McCallbb6fb462010-04-08 00:13:37 +00009677 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregor5fccd362010-03-03 23:55:11 +00009678 NestedNameSpecifier *Qualifier = 0;
John McCall129e2df2009-11-30 22:42:35 +00009679 if (isa<MemberExpr>(NakedMemExpr)) {
9680 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall129e2df2009-11-30 22:42:35 +00009681 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall6bb80172010-03-30 21:47:33 +00009682 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregor5fccd362010-03-03 23:55:11 +00009683 Qualifier = MemExpr->getQualifier();
John McCall5acb0c92011-10-17 18:40:02 +00009684 UnbridgedCasts.restore();
John McCall129e2df2009-11-30 22:42:35 +00009685 } else {
9686 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregor5fccd362010-03-03 23:55:11 +00009687 Qualifier = UnresExpr->getQualifier();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009688
John McCall701c89e2009-12-03 04:06:58 +00009689 QualType ObjectType = UnresExpr->getBaseType();
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009690 Expr::Classification ObjectClassification
9691 = UnresExpr->isArrow()? Expr::Classification::makeSimpleLValue()
9692 : UnresExpr->getBase()->Classify(Context);
John McCall129e2df2009-11-30 22:42:35 +00009693
Douglas Gregor88a35142008-12-22 05:46:06 +00009694 // Add overload candidates
John McCall5769d612010-02-08 23:07:23 +00009695 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump1eb44332009-09-09 15:08:12 +00009696
John McCallaa81e162009-12-01 22:10:20 +00009697 // FIXME: avoid copy.
9698 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
9699 if (UnresExpr->hasExplicitTemplateArgs()) {
9700 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
9701 TemplateArgs = &TemplateArgsBuffer;
9702 }
9703
John McCall129e2df2009-11-30 22:42:35 +00009704 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
9705 E = UnresExpr->decls_end(); I != E; ++I) {
9706
John McCall701c89e2009-12-03 04:06:58 +00009707 NamedDecl *Func = *I;
9708 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
9709 if (isa<UsingShadowDecl>(Func))
9710 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
9711
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009712
Francois Pichetdbee3412011-01-18 05:04:39 +00009713 // Microsoft supports direct constructor calls.
Francois Pichet62ec1f22011-09-17 17:15:52 +00009714 if (getLangOptions().MicrosoftExt && isa<CXXConstructorDecl>(Func)) {
Francois Pichetdbee3412011-01-18 05:04:39 +00009715 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
9716 CandidateSet);
9717 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00009718 // If explicit template arguments were provided, we can't call a
9719 // non-template member function.
John McCallaa81e162009-12-01 22:10:20 +00009720 if (TemplateArgs)
Douglas Gregor3eefb1c2009-10-24 04:59:53 +00009721 continue;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009722
John McCall9aa472c2010-03-19 07:35:19 +00009723 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009724 ObjectClassification,
9725 Args, NumArgs, CandidateSet,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009726 /*SuppressUserConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00009727 } else {
John McCall129e2df2009-11-30 22:42:35 +00009728 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCall9aa472c2010-03-19 07:35:19 +00009729 I.getPair(), ActingDC, TemplateArgs,
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009730 ObjectType, ObjectClassification,
Douglas Gregor2c9a03f2011-01-26 19:30:28 +00009731 Args, NumArgs, CandidateSet,
Douglas Gregordec06662009-08-21 18:42:58 +00009732 /*SuppressUsedConversions=*/false);
John McCalld5532b62009-11-23 01:53:49 +00009733 }
Douglas Gregordec06662009-08-21 18:42:58 +00009734 }
Mike Stump1eb44332009-09-09 15:08:12 +00009735
John McCall129e2df2009-11-30 22:42:35 +00009736 DeclarationName DeclName = UnresExpr->getMemberName();
9737
John McCall5acb0c92011-10-17 18:40:02 +00009738 UnbridgedCasts.restore();
9739
Douglas Gregor88a35142008-12-22 05:46:06 +00009740 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +00009741 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky7663f392010-11-20 01:29:55 +00009742 Best)) {
Douglas Gregor88a35142008-12-22 05:46:06 +00009743 case OR_Success:
9744 Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth25ca4212011-02-25 19:41:05 +00009745 MarkDeclarationReferenced(UnresExpr->getMemberLoc(), Method);
John McCall6bb80172010-03-30 21:47:33 +00009746 FoundDecl = Best->FoundDecl;
John McCall9aa472c2010-03-19 07:35:19 +00009747 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009748 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor88a35142008-12-22 05:46:06 +00009749 break;
9750
9751 case OR_No_Viable_Function:
John McCall129e2df2009-11-30 22:42:35 +00009752 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor88a35142008-12-22 05:46:06 +00009753 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00009754 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009755 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00009756 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00009757 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00009758
9759 case OR_Ambiguous:
John McCall129e2df2009-11-30 22:42:35 +00009760 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor6b906862009-08-21 00:16:32 +00009761 << DeclName << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009762 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor88a35142008-12-22 05:46:06 +00009763 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00009764 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009765
9766 case OR_Deleted:
John McCall129e2df2009-11-30 22:42:35 +00009767 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009768 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009769 << DeclName
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009770 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +00009771 << MemExprE->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009772 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009773 // FIXME: Leaking incoming expressions!
John McCallaa81e162009-12-01 22:10:20 +00009774 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00009775 }
9776
John McCall6bb80172010-03-30 21:47:33 +00009777 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCallaa81e162009-12-01 22:10:20 +00009778
John McCallaa81e162009-12-01 22:10:20 +00009779 // If overload resolution picked a static member, build a
9780 // non-member call based on that function.
9781 if (Method->isStatic()) {
9782 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
9783 Args, NumArgs, RParenLoc);
9784 }
9785
John McCall129e2df2009-11-30 22:42:35 +00009786 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor88a35142008-12-22 05:46:06 +00009787 }
9788
John McCallf89e55a2010-11-18 06:31:45 +00009789 QualType ResultType = Method->getResultType();
9790 ExprValueKind VK = Expr::getValueKindForType(ResultType);
9791 ResultType = ResultType.getNonLValueExprType(Context);
9792
Douglas Gregor88a35142008-12-22 05:46:06 +00009793 assert(Method && "Member call to something that isn't a method?");
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009794 CXXMemberCallExpr *TheCall =
John McCall9ae2f072010-08-23 23:25:46 +00009795 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCallf89e55a2010-11-18 06:31:45 +00009796 ResultType, VK, RParenLoc);
Douglas Gregor88a35142008-12-22 05:46:06 +00009797
Anders Carlssoneed3e692009-10-10 00:06:20 +00009798 // Check for a valid return type.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009799 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCall9ae2f072010-08-23 23:25:46 +00009800 TheCall, Method))
John McCallaa81e162009-12-01 22:10:20 +00009801 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009802
Douglas Gregor88a35142008-12-22 05:46:06 +00009803 // Convert the object argument (for a non-static member function call).
John McCall6bb80172010-03-30 21:47:33 +00009804 // We only need to do this if there was actually an overload; otherwise
9805 // it was done at lookup.
John Wiegley429bb272011-04-08 18:41:53 +00009806 if (!Method->isStatic()) {
9807 ExprResult ObjectArg =
9808 PerformObjectArgumentInitialization(MemExpr->getBase(), Qualifier,
9809 FoundDecl, Method);
9810 if (ObjectArg.isInvalid())
9811 return ExprError();
9812 MemExpr->setBase(ObjectArg.take());
9813 }
Douglas Gregor88a35142008-12-22 05:46:06 +00009814
9815 // Convert the rest of the arguments
Chandler Carruth6df868e2010-12-12 08:17:55 +00009816 const FunctionProtoType *Proto =
9817 Method->getType()->getAs<FunctionProtoType>();
John McCall9ae2f072010-08-23 23:25:46 +00009818 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor88a35142008-12-22 05:46:06 +00009819 RParenLoc))
John McCallaa81e162009-12-01 22:10:20 +00009820 return ExprError();
Douglas Gregor88a35142008-12-22 05:46:06 +00009821
John McCall9ae2f072010-08-23 23:25:46 +00009822 if (CheckFunctionCall(Method, TheCall))
John McCallaa81e162009-12-01 22:10:20 +00009823 return ExprError();
Anders Carlsson6f680272009-08-16 03:42:12 +00009824
Anders Carlsson2174d4c2011-05-06 14:25:31 +00009825 if ((isa<CXXConstructorDecl>(CurContext) ||
9826 isa<CXXDestructorDecl>(CurContext)) &&
9827 TheCall->getMethodDecl()->isPure()) {
9828 const CXXMethodDecl *MD = TheCall->getMethodDecl();
9829
Chandler Carruthae198062011-06-27 08:31:58 +00009830 if (isa<CXXThisExpr>(MemExpr->getBase()->IgnoreParenCasts())) {
Anders Carlsson2174d4c2011-05-06 14:25:31 +00009831 Diag(MemExpr->getLocStart(),
9832 diag::warn_call_to_pure_virtual_member_function_from_ctor_dtor)
9833 << MD->getDeclName() << isa<CXXDestructorDecl>(CurContext)
9834 << MD->getParent()->getDeclName();
9835
9836 Diag(MD->getLocStart(), diag::note_previous_decl) << MD->getDeclName();
Chandler Carruthae198062011-06-27 08:31:58 +00009837 }
Anders Carlsson2174d4c2011-05-06 14:25:31 +00009838 }
John McCall9ae2f072010-08-23 23:25:46 +00009839 return MaybeBindToTemporary(TheCall);
Douglas Gregor88a35142008-12-22 05:46:06 +00009840}
9841
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009842/// BuildCallToObjectOfClassType - Build a call to an object of class
9843/// type (C++ [over.call.object]), which can end up invoking an
9844/// overloaded function call operator (@c operator()) or performing a
9845/// user-defined conversion on the object argument.
John McCallf312b1e2010-08-26 23:41:50 +00009846ExprResult
John Wiegley429bb272011-04-08 18:41:53 +00009847Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Obj,
Douglas Gregor5c37de72008-12-06 00:22:45 +00009848 SourceLocation LParenLoc,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009849 Expr **Args, unsigned NumArgs,
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009850 SourceLocation RParenLoc) {
John McCall5acb0c92011-10-17 18:40:02 +00009851 if (checkPlaceholderForOverload(*this, Obj))
9852 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +00009853 ExprResult Object = Owned(Obj);
John McCall5acb0c92011-10-17 18:40:02 +00009854
9855 UnbridgedCastsSet UnbridgedCasts;
9856 if (checkArgPlaceholdersForOverload(*this, Args, NumArgs, UnbridgedCasts))
9857 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +00009858
John Wiegley429bb272011-04-08 18:41:53 +00009859 assert(Object.get()->getType()->isRecordType() && "Requires object type argument");
9860 const RecordType *Record = Object.get()->getType()->getAs<RecordType>();
Mike Stump1eb44332009-09-09 15:08:12 +00009861
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009862 // C++ [over.call.object]p1:
9863 // If the primary-expression E in the function call syntax
Eli Friedman33a31382009-08-05 19:21:58 +00009864 // evaluates to a class object of type "cv T", then the set of
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009865 // candidate functions includes at least the function call
9866 // operators of T. The function call operators of T are obtained by
9867 // ordinary lookup of the name operator() in the context of
9868 // (E).operator().
John McCall5769d612010-02-08 23:07:23 +00009869 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor44b43212008-12-11 16:49:14 +00009870 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregor593564b2009-11-15 07:48:03 +00009871
John Wiegley429bb272011-04-08 18:41:53 +00009872 if (RequireCompleteType(LParenLoc, Object.get()->getType(),
Douglas Gregorfe6b2d42010-03-29 23:34:08 +00009873 PDiag(diag::err_incomplete_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00009874 << Object.get()->getSourceRange()))
Douglas Gregor593564b2009-11-15 07:48:03 +00009875 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009876
John McCalla24dc2e2009-11-17 02:14:36 +00009877 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
9878 LookupQualifiedName(R, Record->getDecl());
9879 R.suppressDiagnostics();
9880
Douglas Gregor593564b2009-11-15 07:48:03 +00009881 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor3734c212009-11-07 17:23:56 +00009882 Oper != OperEnd; ++Oper) {
John Wiegley429bb272011-04-08 18:41:53 +00009883 AddMethodCandidate(Oper.getPair(), Object.get()->getType(),
9884 Object.get()->Classify(Context), Args, NumArgs, CandidateSet,
John McCall314be4e2009-11-17 07:50:12 +00009885 /*SuppressUserConversions=*/ false);
Douglas Gregor3734c212009-11-07 17:23:56 +00009886 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009887
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009888 // C++ [over.call.object]p2:
Douglas Gregorbf6e3172011-07-23 18:59:35 +00009889 // In addition, for each (non-explicit in C++0x) conversion function
9890 // declared in T of the form
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009891 //
9892 // operator conversion-type-id () cv-qualifier;
9893 //
9894 // where cv-qualifier is the same cv-qualification as, or a
9895 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregora967a6f2008-11-20 13:33:37 +00009896 // denotes the type "pointer to function of (P1,...,Pn) returning
9897 // R", or the type "reference to pointer to function of
9898 // (P1,...,Pn) returning R", or the type "reference to function
9899 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009900 // is also considered as a candidate function. Similarly,
9901 // surrogate call functions are added to the set of candidate
9902 // functions for each conversion function declared in an
9903 // accessible base class provided the function is not hidden
9904 // within T by another intervening declaration.
John McCalleec51cf2010-01-20 00:46:10 +00009905 const UnresolvedSetImpl *Conversions
Douglas Gregor90073282010-01-11 19:36:35 +00009906 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCalleec51cf2010-01-20 00:46:10 +00009907 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCallba135432009-11-21 08:51:07 +00009908 E = Conversions->end(); I != E; ++I) {
John McCall701c89e2009-12-03 04:06:58 +00009909 NamedDecl *D = *I;
9910 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
9911 if (isa<UsingShadowDecl>(D))
9912 D = cast<UsingShadowDecl>(D)->getTargetDecl();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009913
Douglas Gregor4a27d702009-10-21 06:18:39 +00009914 // Skip over templated conversion functions; they aren't
9915 // surrogates.
John McCall701c89e2009-12-03 04:06:58 +00009916 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor4a27d702009-10-21 06:18:39 +00009917 continue;
Douglas Gregor65ec1fd2009-08-21 23:19:43 +00009918
John McCall701c89e2009-12-03 04:06:58 +00009919 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
Douglas Gregorbf6e3172011-07-23 18:59:35 +00009920 if (!Conv->isExplicit()) {
9921 // Strip the reference type (if any) and then the pointer type (if
9922 // any) to get down to what might be a function type.
9923 QualType ConvType = Conv->getConversionType().getNonReferenceType();
9924 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
9925 ConvType = ConvPtrType->getPointeeType();
John McCallba135432009-11-21 08:51:07 +00009926
Douglas Gregorbf6e3172011-07-23 18:59:35 +00009927 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
9928 {
9929 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
9930 Object.get(), Args, NumArgs, CandidateSet);
9931 }
9932 }
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009933 }
Mike Stump1eb44332009-09-09 15:08:12 +00009934
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009935 bool HadMultipleCandidates = (CandidateSet.size() > 1);
9936
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009937 // Perform overload resolution.
9938 OverloadCandidateSet::iterator Best;
John Wiegley429bb272011-04-08 18:41:53 +00009939 switch (CandidateSet.BestViableFunction(*this, Object.get()->getLocStart(),
John McCall120d63c2010-08-24 20:38:10 +00009940 Best)) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009941 case OR_Success:
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009942 // Overload resolution succeeded; we'll build the appropriate call
9943 // below.
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009944 break;
9945
9946 case OR_No_Viable_Function:
John McCall1eb3e102010-01-07 02:04:15 +00009947 if (CandidateSet.empty())
John Wiegley429bb272011-04-08 18:41:53 +00009948 Diag(Object.get()->getSourceRange().getBegin(), diag::err_ovl_no_oper)
9949 << Object.get()->getType() << /*call*/ 1
9950 << Object.get()->getSourceRange();
John McCall1eb3e102010-01-07 02:04:15 +00009951 else
John Wiegley429bb272011-04-08 18:41:53 +00009952 Diag(Object.get()->getSourceRange().getBegin(),
John McCall1eb3e102010-01-07 02:04:15 +00009953 diag::err_ovl_no_viable_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00009954 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009955 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009956 break;
9957
9958 case OR_Ambiguous:
John Wiegley429bb272011-04-08 18:41:53 +00009959 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009960 diag::err_ovl_ambiguous_object_call)
John Wiegley429bb272011-04-08 18:41:53 +00009961 << Object.get()->getType() << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009962 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009963 break;
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009964
9965 case OR_Deleted:
John Wiegley429bb272011-04-08 18:41:53 +00009966 Diag(Object.get()->getSourceRange().getBegin(),
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009967 diag::err_ovl_deleted_object_call)
9968 << Best->Function->isDeleted()
John Wiegley429bb272011-04-08 18:41:53 +00009969 << Object.get()->getType()
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00009970 << getDeletedOrUnavailableSuffix(Best->Function)
John Wiegley429bb272011-04-08 18:41:53 +00009971 << Object.get()->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +00009972 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor48f3bb92009-02-18 21:56:37 +00009973 break;
Mike Stump1eb44332009-09-09 15:08:12 +00009974 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009975
Douglas Gregorff331c12010-07-25 18:17:45 +00009976 if (Best == CandidateSet.end())
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009977 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +00009978
John McCall5acb0c92011-10-17 18:40:02 +00009979 UnbridgedCasts.restore();
9980
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009981 if (Best->Function == 0) {
9982 // Since there is no function declaration, this is one of the
9983 // surrogate candidates. Dig out the conversion function.
Mike Stump1eb44332009-09-09 15:08:12 +00009984 CXXConversionDecl *Conv
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009985 = cast<CXXConversionDecl>(
9986 Best->Conversions[0].UserDefined.ConversionFunction);
9987
John Wiegley429bb272011-04-08 18:41:53 +00009988 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +00009989 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +00009990
Douglas Gregor106c6eb2008-11-19 22:57:39 +00009991 // We selected one of the surrogate functions that converts the
9992 // object parameter to a function pointer. Perform the conversion
9993 // on the object argument, then let ActOnCallExpr finish the job.
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +00009994
Fariborz Jahaniand8307b12009-09-28 18:35:46 +00009995 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanianb7400232009-09-28 23:23:40 +00009996 // and then call it.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +00009997 ExprResult Call = BuildCXXMemberCallExpr(Object.get(), Best->FoundDecl,
9998 Conv, HadMultipleCandidates);
Douglas Gregorf2ae5262011-01-20 00:18:04 +00009999 if (Call.isInvalid())
10000 return ExprError();
Abramo Bagnara960809e2011-11-16 22:46:05 +000010001 // Record usage of conversion in an implicit cast.
10002 Call = Owned(ImplicitCastExpr::Create(Context, Call.get()->getType(),
10003 CK_UserDefinedConversion,
10004 Call.get(), 0, VK_RValue));
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010005
Douglas Gregorf2ae5262011-01-20 00:18:04 +000010006 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregora1a04782010-09-09 16:33:13 +000010007 RParenLoc);
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010008 }
10009
Chandler Carruth25ca4212011-02-25 19:41:05 +000010010 MarkDeclarationReferenced(LParenLoc, Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010011 CheckMemberOperatorAccess(LParenLoc, Object.get(), 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010012 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall41d89032010-01-28 01:54:34 +000010013
Douglas Gregor106c6eb2008-11-19 22:57:39 +000010014 // We found an overloaded operator(). Build a CXXOperatorCallExpr
10015 // that calls this method, using Object for the implicit object
10016 // parameter and passing along the remaining arguments.
10017 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth6df868e2010-12-12 08:17:55 +000010018 const FunctionProtoType *Proto =
10019 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010020
10021 unsigned NumArgsInProto = Proto->getNumArgs();
10022 unsigned NumArgsToCheck = NumArgs;
10023
10024 // Build the full argument list for the method call (the
10025 // implicit object parameter is placed at the beginning of the
10026 // list).
10027 Expr **MethodArgs;
10028 if (NumArgs < NumArgsInProto) {
10029 NumArgsToCheck = NumArgsInProto;
10030 MethodArgs = new Expr*[NumArgsInProto + 1];
10031 } else {
10032 MethodArgs = new Expr*[NumArgs + 1];
10033 }
John Wiegley429bb272011-04-08 18:41:53 +000010034 MethodArgs[0] = Object.get();
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010035 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
10036 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump1eb44332009-09-09 15:08:12 +000010037
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010038 ExprResult NewFn = CreateFunctionRefExpr(*this, Method,
10039 HadMultipleCandidates);
John Wiegley429bb272011-04-08 18:41:53 +000010040 if (NewFn.isInvalid())
10041 return true;
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010042
10043 // Once we've built TheCall, all of the expressions are properly
10044 // owned.
John McCallf89e55a2010-11-18 06:31:45 +000010045 QualType ResultTy = Method->getResultType();
10046 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10047 ResultTy = ResultTy.getNonLValueExprType(Context);
10048
John McCall9ae2f072010-08-23 23:25:46 +000010049 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010050 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn.take(),
John McCall9ae2f072010-08-23 23:25:46 +000010051 MethodArgs, NumArgs + 1,
John McCallf89e55a2010-11-18 06:31:45 +000010052 ResultTy, VK, RParenLoc);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010053 delete [] MethodArgs;
10054
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010055 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson07d68f12009-10-13 21:49:31 +000010056 Method))
10057 return true;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010058
Douglas Gregor518fda12009-01-13 05:10:00 +000010059 // We may have default arguments. If so, we need to allocate more
10060 // slots in the call for them.
10061 if (NumArgs < NumArgsInProto)
Ted Kremenek8189cde2009-02-07 01:47:29 +000010062 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor518fda12009-01-13 05:10:00 +000010063 else if (NumArgs > NumArgsInProto)
10064 NumArgsToCheck = NumArgsInProto;
10065
Chris Lattner312531a2009-04-12 08:11:20 +000010066 bool IsError = false;
10067
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010068 // Initialize the implicit object parameter.
John Wiegley429bb272011-04-08 18:41:53 +000010069 ExprResult ObjRes =
10070 PerformObjectArgumentInitialization(Object.get(), /*Qualifier=*/0,
10071 Best->FoundDecl, Method);
10072 if (ObjRes.isInvalid())
10073 IsError = true;
10074 else
10075 Object = move(ObjRes);
10076 TheCall->setArg(0, Object.take());
Chris Lattner312531a2009-04-12 08:11:20 +000010077
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010078 // Check the argument types.
10079 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010080 Expr *Arg;
Douglas Gregor518fda12009-01-13 05:10:00 +000010081 if (i < NumArgs) {
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010082 Arg = Args[i];
Mike Stump1eb44332009-09-09 15:08:12 +000010083
Douglas Gregor518fda12009-01-13 05:10:00 +000010084 // Pass the argument.
Anders Carlsson3faa4862010-01-29 18:43:53 +000010085
John McCall60d7b3a2010-08-24 06:29:42 +000010086 ExprResult InputInit
Anders Carlsson3faa4862010-01-29 18:43:53 +000010087 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian745da3a2010-09-24 17:30:16 +000010088 Context,
Anders Carlsson3faa4862010-01-29 18:43:53 +000010089 Method->getParamDecl(i)),
John McCall9ae2f072010-08-23 23:25:46 +000010090 SourceLocation(), Arg);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010091
Anders Carlsson3faa4862010-01-29 18:43:53 +000010092 IsError |= InputInit.isInvalid();
10093 Arg = InputInit.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010094 } else {
John McCall60d7b3a2010-08-24 06:29:42 +000010095 ExprResult DefArg
Douglas Gregord47c47d2009-11-09 19:27:57 +000010096 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
10097 if (DefArg.isInvalid()) {
10098 IsError = true;
10099 break;
10100 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010101
Douglas Gregord47c47d2009-11-09 19:27:57 +000010102 Arg = DefArg.takeAs<Expr>();
Douglas Gregor518fda12009-01-13 05:10:00 +000010103 }
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010104
10105 TheCall->setArg(i + 1, Arg);
10106 }
10107
10108 // If this is a variadic call, handle args passed through "...".
10109 if (Proto->isVariadic()) {
10110 // Promote the arguments (C99 6.5.2.2p7).
10111 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
John Wiegley429bb272011-04-08 18:41:53 +000010112 ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0);
10113 IsError |= Arg.isInvalid();
10114 TheCall->setArg(i + 1, Arg.take());
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010115 }
10116 }
10117
Chris Lattner312531a2009-04-12 08:11:20 +000010118 if (IsError) return true;
10119
John McCall9ae2f072010-08-23 23:25:46 +000010120 if (CheckFunctionCall(Method, TheCall))
Anders Carlssond406bf02009-08-16 01:56:34 +000010121 return true;
10122
John McCall182f7092010-08-24 06:09:16 +000010123 return MaybeBindToTemporary(TheCall);
Douglas Gregorf9eb9052008-11-19 21:05:33 +000010124}
10125
Douglas Gregor8ba10742008-11-20 16:27:02 +000010126/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump1eb44332009-09-09 15:08:12 +000010127/// (if one exists), where @c Base is an expression of class type and
Douglas Gregor8ba10742008-11-20 16:27:02 +000010128/// @c Member is the name of the member we're trying to find.
John McCall60d7b3a2010-08-24 06:29:42 +000010129ExprResult
John McCall9ae2f072010-08-23 23:25:46 +000010130Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth6df868e2010-12-12 08:17:55 +000010131 assert(Base->getType()->isRecordType() &&
10132 "left-hand side must have class type");
Mike Stump1eb44332009-09-09 15:08:12 +000010133
John McCall5acb0c92011-10-17 18:40:02 +000010134 if (checkPlaceholderForOverload(*this, Base))
10135 return ExprError();
John McCall0e800c92010-12-04 08:14:53 +000010136
John McCall5769d612010-02-08 23:07:23 +000010137 SourceLocation Loc = Base->getExprLoc();
10138
Douglas Gregor8ba10742008-11-20 16:27:02 +000010139 // C++ [over.ref]p1:
10140 //
10141 // [...] An expression x->m is interpreted as (x.operator->())->m
10142 // for a class object x of type T if T::operator->() exists and if
10143 // the operator is selected as the best match function by the
10144 // overload resolution mechanism (13.3).
Chandler Carruth6df868e2010-12-12 08:17:55 +000010145 DeclarationName OpName =
10146 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCall5769d612010-02-08 23:07:23 +000010147 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenek6217b802009-07-29 21:53:49 +000010148 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010149
John McCall5769d612010-02-08 23:07:23 +000010150 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedmanf43fb722009-11-18 01:28:03 +000010151 PDiag(diag::err_typecheck_incomplete_tag)
10152 << Base->getSourceRange()))
10153 return ExprError();
10154
John McCalla24dc2e2009-11-17 02:14:36 +000010155 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
10156 LookupQualifiedName(R, BaseRecord->getDecl());
10157 R.suppressDiagnostics();
Anders Carlssone30572a2009-09-10 23:18:36 +000010158
10159 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall701c89e2009-12-03 04:06:58 +000010160 Oper != OperEnd; ++Oper) {
Douglas Gregor2c9a03f2011-01-26 19:30:28 +000010161 AddMethodCandidate(Oper.getPair(), Base->getType(), Base->Classify(Context),
10162 0, 0, CandidateSet, /*SuppressUserConversions=*/false);
John McCall701c89e2009-12-03 04:06:58 +000010163 }
Douglas Gregor8ba10742008-11-20 16:27:02 +000010164
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010165 bool HadMultipleCandidates = (CandidateSet.size() > 1);
10166
Douglas Gregor8ba10742008-11-20 16:27:02 +000010167 // Perform overload resolution.
10168 OverloadCandidateSet::iterator Best;
John McCall120d63c2010-08-24 20:38:10 +000010169 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor8ba10742008-11-20 16:27:02 +000010170 case OR_Success:
10171 // Overload resolution succeeded; we'll build the call below.
10172 break;
10173
10174 case OR_No_Viable_Function:
10175 if (CandidateSet.empty())
10176 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010177 << Base->getType() << Base->getSourceRange();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010178 else
10179 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010180 << "operator->" << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010181 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010182 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010183
10184 case OR_Ambiguous:
Douglas Gregorae2cf762010-11-13 20:06:38 +000010185 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
10186 << "->" << Base->getType() << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010187 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010188 return ExprError();
Douglas Gregor48f3bb92009-02-18 21:56:37 +000010189
10190 case OR_Deleted:
10191 Diag(OpLoc, diag::err_ovl_deleted_oper)
10192 << Best->Function->isDeleted()
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010193 << "->"
Douglas Gregor0a0d2b12011-03-23 00:50:03 +000010194 << getDeletedOrUnavailableSuffix(Best->Function)
Fariborz Jahanian5e24f2a2011-02-25 20:51:14 +000010195 << Base->getSourceRange();
John McCall120d63c2010-08-24 20:38:10 +000010196 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010197 return ExprError();
Douglas Gregor8ba10742008-11-20 16:27:02 +000010198 }
10199
Chandler Carruth25ca4212011-02-25 19:41:05 +000010200 MarkDeclarationReferenced(OpLoc, Best->Function);
John McCall9aa472c2010-03-19 07:35:19 +000010201 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCallb697e082010-05-06 18:15:07 +000010202 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCall9aa472c2010-03-19 07:35:19 +000010203
Douglas Gregor8ba10742008-11-20 16:27:02 +000010204 // Convert the object parameter.
10205 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John Wiegley429bb272011-04-08 18:41:53 +000010206 ExprResult BaseResult =
10207 PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
10208 Best->FoundDecl, Method);
10209 if (BaseResult.isInvalid())
Douglas Gregorfe85ced2009-08-06 03:17:00 +000010210 return ExprError();
John Wiegley429bb272011-04-08 18:41:53 +000010211 Base = BaseResult.take();
Douglas Gregorfc195ef2008-11-21 03:04:22 +000010212
Douglas Gregor8ba10742008-11-20 16:27:02 +000010213 // Build the operator call.
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010214 ExprResult FnExpr = CreateFunctionRefExpr(*this, Method,
10215 HadMultipleCandidates);
John Wiegley429bb272011-04-08 18:41:53 +000010216 if (FnExpr.isInvalid())
10217 return ExprError();
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010218
John McCallf89e55a2010-11-18 06:31:45 +000010219 QualType ResultTy = Method->getResultType();
10220 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
10221 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCall9ae2f072010-08-23 23:25:46 +000010222 CXXOperatorCallExpr *TheCall =
John Wiegley429bb272011-04-08 18:41:53 +000010223 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr.take(),
John McCallf89e55a2010-11-18 06:31:45 +000010224 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlsson15ea3782009-10-13 22:43:21 +000010225
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010226 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlsson15ea3782009-10-13 22:43:21 +000010227 Method))
10228 return ExprError();
Eli Friedmand5931902011-04-04 01:18:25 +000010229
10230 return MaybeBindToTemporary(TheCall);
Douglas Gregor8ba10742008-11-20 16:27:02 +000010231}
10232
Douglas Gregor904eed32008-11-10 20:40:00 +000010233/// FixOverloadedFunctionReference - E is an expression that refers to
10234/// a C++ overloaded function (possibly with some parentheses and
10235/// perhaps a '&' around it). We have resolved the overloaded function
10236/// to the function declaration Fn, so patch up the expression E to
Anders Carlsson96ad5332009-10-21 17:16:23 +000010237/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCall161755a2010-04-06 21:38:20 +000010238Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall6bb80172010-03-30 21:47:33 +000010239 FunctionDecl *Fn) {
Douglas Gregor904eed32008-11-10 20:40:00 +000010240 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000010241 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
10242 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000010243 if (SubExpr == PE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010244 return PE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010245
Douglas Gregor699ee522009-11-20 19:42:02 +000010246 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010247 }
10248
Douglas Gregor699ee522009-11-20 19:42:02 +000010249 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall6bb80172010-03-30 21:47:33 +000010250 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
10251 Found, Fn);
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010252 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor699ee522009-11-20 19:42:02 +000010253 SubExpr->getType()) &&
Douglas Gregor097bfb12009-10-23 22:18:25 +000010254 "Implicit cast type cannot be determined from overload");
John McCallf871d0c2010-08-07 06:22:56 +000010255 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor699ee522009-11-20 19:42:02 +000010256 if (SubExpr == ICE->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010257 return ICE;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010258
10259 return ImplicitCastExpr::Create(Context, ICE->getType(),
John McCallf871d0c2010-08-07 06:22:56 +000010260 ICE->getCastKind(),
10261 SubExpr, 0,
John McCall5baba9d2010-08-25 10:28:54 +000010262 ICE->getValueKind());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010263 }
10264
Douglas Gregor699ee522009-11-20 19:42:02 +000010265 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCall2de56d12010-08-25 11:45:40 +000010266 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregor904eed32008-11-10 20:40:00 +000010267 "Can only take the address of an overloaded function");
Douglas Gregorb86b0572009-02-11 01:18:59 +000010268 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
10269 if (Method->isStatic()) {
10270 // Do nothing: static member functions aren't any different
10271 // from non-member functions.
John McCallba135432009-11-21 08:51:07 +000010272 } else {
John McCallf7a1a742009-11-24 19:00:30 +000010273 // Fix the sub expression, which really has to be an
10274 // UnresolvedLookupExpr holding an overloaded member function
10275 // or template.
John McCall6bb80172010-03-30 21:47:33 +000010276 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10277 Found, Fn);
John McCallba135432009-11-21 08:51:07 +000010278 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010279 return UnOp;
Douglas Gregor699ee522009-11-20 19:42:02 +000010280
John McCallba135432009-11-21 08:51:07 +000010281 assert(isa<DeclRefExpr>(SubExpr)
10282 && "fixed to something other than a decl ref");
10283 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
10284 && "fixed to a member ref with no nested name qualifier");
10285
10286 // We have taken the address of a pointer to member
10287 // function. Perform the computation here so that we get the
10288 // appropriate pointer to member type.
10289 QualType ClassType
10290 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
10291 QualType MemPtrType
10292 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
10293
John McCallf89e55a2010-11-18 06:31:45 +000010294 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
10295 VK_RValue, OK_Ordinary,
10296 UnOp->getOperatorLoc());
Douglas Gregorb86b0572009-02-11 01:18:59 +000010297 }
10298 }
John McCall6bb80172010-03-30 21:47:33 +000010299 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
10300 Found, Fn);
Douglas Gregor699ee522009-11-20 19:42:02 +000010301 if (SubExpr == UnOp->getSubExpr())
John McCall3fa5cae2010-10-26 07:05:15 +000010302 return UnOp;
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010303
John McCall2de56d12010-08-25 11:45:40 +000010304 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor699ee522009-11-20 19:42:02 +000010305 Context.getPointerType(SubExpr->getType()),
John McCallf89e55a2010-11-18 06:31:45 +000010306 VK_RValue, OK_Ordinary,
Douglas Gregor699ee522009-11-20 19:42:02 +000010307 UnOp->getOperatorLoc());
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010308 }
John McCallba135432009-11-21 08:51:07 +000010309
10310 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCallaa81e162009-12-01 22:10:20 +000010311 // FIXME: avoid copy.
10312 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCallf7a1a742009-11-24 19:00:30 +000010313 if (ULE->hasExplicitTemplateArgs()) {
John McCallaa81e162009-12-01 22:10:20 +000010314 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
10315 TemplateArgs = &TemplateArgsBuffer;
John McCallf7a1a742009-11-24 19:00:30 +000010316 }
10317
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010318 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10319 ULE->getQualifierLoc(),
10320 Fn,
10321 ULE->getNameLoc(),
10322 Fn->getType(),
10323 VK_LValue,
10324 Found.getDecl(),
10325 TemplateArgs);
10326 DRE->setHadMultipleCandidates(ULE->getNumDecls() > 1);
10327 return DRE;
John McCallba135432009-11-21 08:51:07 +000010328 }
10329
John McCall129e2df2009-11-30 22:42:35 +000010330 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCalld5532b62009-11-23 01:53:49 +000010331 // FIXME: avoid copy.
John McCallaa81e162009-12-01 22:10:20 +000010332 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
10333 if (MemExpr->hasExplicitTemplateArgs()) {
10334 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
10335 TemplateArgs = &TemplateArgsBuffer;
10336 }
John McCalld5532b62009-11-23 01:53:49 +000010337
John McCallaa81e162009-12-01 22:10:20 +000010338 Expr *Base;
10339
John McCallf89e55a2010-11-18 06:31:45 +000010340 // If we're filling in a static method where we used to have an
10341 // implicit member access, rewrite to a simple decl ref.
John McCallaa81e162009-12-01 22:10:20 +000010342 if (MemExpr->isImplicitAccess()) {
10343 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010344 DeclRefExpr *DRE = DeclRefExpr::Create(Context,
10345 MemExpr->getQualifierLoc(),
10346 Fn,
10347 MemExpr->getMemberLoc(),
10348 Fn->getType(),
10349 VK_LValue,
10350 Found.getDecl(),
10351 TemplateArgs);
10352 DRE->setHadMultipleCandidates(MemExpr->getNumDecls() > 1);
10353 return DRE;
Douglas Gregor828a1972010-01-07 23:12:05 +000010354 } else {
10355 SourceLocation Loc = MemExpr->getMemberLoc();
10356 if (MemExpr->getQualifier())
Douglas Gregor4c9be892011-02-28 20:01:57 +000010357 Loc = MemExpr->getQualifierLoc().getBeginLoc();
Douglas Gregor828a1972010-01-07 23:12:05 +000010358 Base = new (Context) CXXThisExpr(Loc,
10359 MemExpr->getBaseType(),
10360 /*isImplicit=*/true);
10361 }
John McCallaa81e162009-12-01 22:10:20 +000010362 } else
John McCall3fa5cae2010-10-26 07:05:15 +000010363 Base = MemExpr->getBase();
John McCallaa81e162009-12-01 22:10:20 +000010364
John McCallf5307512011-04-27 00:36:17 +000010365 ExprValueKind valueKind;
10366 QualType type;
10367 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
10368 valueKind = VK_LValue;
10369 type = Fn->getType();
10370 } else {
10371 valueKind = VK_RValue;
10372 type = Context.BoundMemberTy;
10373 }
10374
Abramo Bagnara7cc58b42011-10-05 07:56:41 +000010375 MemberExpr *ME = MemberExpr::Create(Context, Base,
10376 MemExpr->isArrow(),
10377 MemExpr->getQualifierLoc(),
10378 Fn,
10379 Found,
10380 MemExpr->getMemberNameInfo(),
10381 TemplateArgs,
10382 type, valueKind, OK_Ordinary);
10383 ME->setHadMultipleCandidates(true);
10384 return ME;
Douglas Gregor699ee522009-11-20 19:42:02 +000010385 }
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010386
John McCall3fa5cae2010-10-26 07:05:15 +000010387 llvm_unreachable("Invalid reference to overloaded function");
10388 return E;
Douglas Gregor904eed32008-11-10 20:40:00 +000010389}
10390
NAKAMURA Takumidfbb02a2011-01-27 07:10:08 +000010391ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
John McCall60d7b3a2010-08-24 06:29:42 +000010392 DeclAccessPair Found,
10393 FunctionDecl *Fn) {
John McCall6bb80172010-03-30 21:47:33 +000010394 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor20093b42009-12-09 23:02:17 +000010395}
10396
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000010397} // end namespace clang