blob: c6150d91ecefdff50ccfff64993d97b6ba4f6bff [file] [log] [blame]
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001//===--- SemaOverload.cpp - C++ Overloading ---------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file provides Sema routines for C++ overloading.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Douglas Gregorc3a6ade2010-08-12 20:07:10 +000015#include "clang/Sema/Lookup.h"
16#include "clang/Sema/Initialization.h"
John McCallde6836a2010-08-24 07:21:54 +000017#include "clang/Sema/Template.h"
John McCall19c1bfd2010-08-25 05:32:35 +000018#include "clang/Sema/TemplateDeduction.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000019#include "clang/Basic/Diagnostic.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000020#include "clang/Lex/Preprocessor.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000021#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000022#include "clang/AST/CXXInheritance.h"
John McCallde6836a2010-08-24 07:21:54 +000023#include "clang/AST/DeclObjC.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000024#include "clang/AST/Expr.h"
Douglas Gregor91cea0a2008-11-19 21:05:33 +000025#include "clang/AST/ExprCXX.h"
John McCalle26a8722010-12-04 08:14:53 +000026#include "clang/AST/ExprObjC.h"
Douglas Gregora11693b2008-11-12 17:17:38 +000027#include "clang/AST/TypeOrdering.h"
Anders Carlssond624e162009-08-26 23:45:07 +000028#include "clang/Basic/PartialDiagnostic.h"
Douglas Gregor2bbc0262010-09-12 04:28:07 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregor58e008d2008-11-13 20:12:29 +000030#include "llvm/ADT/SmallPtrSet.h"
Douglas Gregor55297ac2008-12-23 00:26:44 +000031#include "llvm/ADT/STLExtras.h"
Douglas Gregor5251f1b2008-10-21 16:13:35 +000032#include <algorithm>
33
34namespace clang {
John McCall19c1bfd2010-08-25 05:32:35 +000035using namespace sema;
Douglas Gregor5251f1b2008-10-21 16:13:35 +000036
John McCall7decc9e2010-11-18 06:31:45 +000037/// A convenience routine for creating a decayed reference to a
38/// function.
39static Expr *
40CreateFunctionRefExpr(Sema &S, FunctionDecl *Fn,
41 SourceLocation Loc = SourceLocation()) {
42 Expr *E = new (S.Context) DeclRefExpr(Fn, Fn->getType(), VK_LValue, Loc);
43 S.DefaultFunctionArrayConversion(E);
44 return E;
45}
46
John McCall5c32be02010-08-24 20:38:10 +000047static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
48 bool InOverloadResolution,
49 StandardConversionSequence &SCS);
50static OverloadingResult
51IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
52 UserDefinedConversionSequence& User,
53 OverloadCandidateSet& Conversions,
54 bool AllowExplicit);
55
56
57static ImplicitConversionSequence::CompareKind
58CompareStandardConversionSequences(Sema &S,
59 const StandardConversionSequence& SCS1,
60 const StandardConversionSequence& SCS2);
61
62static ImplicitConversionSequence::CompareKind
63CompareQualificationConversions(Sema &S,
64 const StandardConversionSequence& SCS1,
65 const StandardConversionSequence& SCS2);
66
67static ImplicitConversionSequence::CompareKind
68CompareDerivedToBaseConversions(Sema &S,
69 const StandardConversionSequence& SCS1,
70 const StandardConversionSequence& SCS2);
71
72
73
Douglas Gregor5251f1b2008-10-21 16:13:35 +000074/// GetConversionCategory - Retrieve the implicit conversion
75/// category corresponding to the given implicit conversion kind.
Mike Stump11289f42009-09-09 15:08:12 +000076ImplicitConversionCategory
Douglas Gregor5251f1b2008-10-21 16:13:35 +000077GetConversionCategory(ImplicitConversionKind Kind) {
78 static const ImplicitConversionCategory
79 Category[(int)ICK_Num_Conversion_Kinds] = {
80 ICC_Identity,
81 ICC_Lvalue_Transformation,
82 ICC_Lvalue_Transformation,
83 ICC_Lvalue_Transformation,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +000084 ICC_Identity,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000085 ICC_Qualification_Adjustment,
86 ICC_Promotion,
87 ICC_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +000088 ICC_Promotion,
89 ICC_Conversion,
90 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +000091 ICC_Conversion,
92 ICC_Conversion,
93 ICC_Conversion,
94 ICC_Conversion,
95 ICC_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +000096 ICC_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +000097 ICC_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +000098 ICC_Conversion,
99 ICC_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000100 ICC_Conversion
101 };
102 return Category[(int)Kind];
103}
104
105/// GetConversionRank - Retrieve the implicit conversion rank
106/// corresponding to the given implicit conversion kind.
107ImplicitConversionRank GetConversionRank(ImplicitConversionKind Kind) {
108 static const ImplicitConversionRank
109 Rank[(int)ICK_Num_Conversion_Kinds] = {
110 ICR_Exact_Match,
111 ICR_Exact_Match,
112 ICR_Exact_Match,
113 ICR_Exact_Match,
114 ICR_Exact_Match,
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000115 ICR_Exact_Match,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000116 ICR_Promotion,
117 ICR_Promotion,
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000118 ICR_Promotion,
119 ICR_Conversion,
120 ICR_Conversion,
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000121 ICR_Conversion,
122 ICR_Conversion,
123 ICR_Conversion,
124 ICR_Conversion,
125 ICR_Conversion,
Douglas Gregor786ab212008-10-29 02:00:59 +0000126 ICR_Conversion,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000127 ICR_Conversion,
Douglas Gregor46188682010-05-18 22:42:18 +0000128 ICR_Conversion,
129 ICR_Conversion,
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +0000130 ICR_Complex_Real_Conversion
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000131 };
132 return Rank[(int)Kind];
133}
134
135/// GetImplicitConversionName - Return the name of this kind of
136/// implicit conversion.
137const char* GetImplicitConversionName(ImplicitConversionKind Kind) {
Nuno Lopescfca1f02009-12-23 17:49:57 +0000138 static const char* const Name[(int)ICK_Num_Conversion_Kinds] = {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000139 "No conversion",
140 "Lvalue-to-rvalue",
141 "Array-to-pointer",
142 "Function-to-pointer",
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000143 "Noreturn adjustment",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000144 "Qualification",
145 "Integral promotion",
146 "Floating point promotion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000147 "Complex promotion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000148 "Integral conversion",
149 "Floating conversion",
Douglas Gregor78ca74d2009-02-12 00:15:05 +0000150 "Complex conversion",
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000151 "Floating-integral conversion",
152 "Pointer conversion",
153 "Pointer-to-member conversion",
Douglas Gregor786ab212008-10-29 02:00:59 +0000154 "Boolean conversion",
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000155 "Compatible-types conversion",
Douglas Gregor46188682010-05-18 22:42:18 +0000156 "Derived-to-base conversion",
157 "Vector conversion",
158 "Vector splat",
159 "Complex-real conversion"
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000160 };
161 return Name[Kind];
162}
163
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000164/// StandardConversionSequence - Set the standard conversion
165/// sequence to the identity conversion.
166void StandardConversionSequence::setAsIdentityConversion() {
167 First = ICK_Identity;
168 Second = ICK_Identity;
169 Third = ICK_Identity;
Douglas Gregore489a7d2010-02-28 18:30:25 +0000170 DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000171 ReferenceBinding = false;
172 DirectBinding = false;
Sebastian Redlf69a94a2009-03-29 22:46:24 +0000173 RRefBinding = false;
Douglas Gregor2fe98832008-11-03 19:09:14 +0000174 CopyConstructor = 0;
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000175}
176
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000177/// getRank - Retrieve the rank of this standard conversion sequence
178/// (C++ 13.3.3.1.1p3). The rank is the largest rank of each of the
179/// implicit conversions.
180ImplicitConversionRank StandardConversionSequence::getRank() const {
181 ImplicitConversionRank Rank = ICR_Exact_Match;
182 if (GetConversionRank(First) > Rank)
183 Rank = GetConversionRank(First);
184 if (GetConversionRank(Second) > Rank)
185 Rank = GetConversionRank(Second);
186 if (GetConversionRank(Third) > Rank)
187 Rank = GetConversionRank(Third);
188 return Rank;
189}
190
191/// isPointerConversionToBool - Determines whether this conversion is
192/// a conversion of a pointer or pointer-to-member to bool. This is
Mike Stump11289f42009-09-09 15:08:12 +0000193/// used as part of the ranking of standard conversion sequences
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000194/// (C++ 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000195bool StandardConversionSequence::isPointerConversionToBool() const {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000196 // Note that FromType has not necessarily been transformed by the
197 // array-to-pointer or function-to-pointer implicit conversions, so
198 // check for their presence as well as checking whether FromType is
199 // a pointer.
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000200 if (getToType(1)->isBooleanType() &&
John McCall6d1116a2010-06-11 10:04:22 +0000201 (getFromType()->isPointerType() ||
202 getFromType()->isObjCObjectPointerType() ||
203 getFromType()->isBlockPointerType() ||
Anders Carlsson7da7cc52010-11-05 00:12:09 +0000204 getFromType()->isNullPtrType() ||
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000205 First == ICK_Array_To_Pointer || First == ICK_Function_To_Pointer))
206 return true;
207
208 return false;
209}
210
Douglas Gregor5c407d92008-10-23 00:40:37 +0000211/// isPointerConversionToVoidPointer - Determines whether this
212/// conversion is a conversion of a pointer to a void pointer. This is
213/// used as part of the ranking of standard conversion sequences (C++
214/// 13.3.3.2p4).
Mike Stump11289f42009-09-09 15:08:12 +0000215bool
Douglas Gregor5c407d92008-10-23 00:40:37 +0000216StandardConversionSequence::
Mike Stump11289f42009-09-09 15:08:12 +0000217isPointerConversionToVoidPointer(ASTContext& Context) const {
John McCall0d1da222010-01-12 00:44:57 +0000218 QualType FromType = getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000219 QualType ToType = getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +0000220
221 // Note that FromType has not necessarily been transformed by the
222 // array-to-pointer implicit conversion, so check for its presence
223 // and redo the conversion to get a pointer.
224 if (First == ICK_Array_To_Pointer)
225 FromType = Context.getArrayDecayedType(FromType);
226
John McCall75851b12010-10-26 06:40:27 +0000227 if (Second == ICK_Pointer_Conversion && FromType->isPointerType())
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000228 if (const PointerType* ToPtrType = ToType->getAs<PointerType>())
Douglas Gregor5c407d92008-10-23 00:40:37 +0000229 return ToPtrType->getPointeeType()->isVoidType();
230
231 return false;
232}
233
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000234/// DebugPrint - Print this standard conversion sequence to standard
235/// error. Useful for debugging overloading issues.
236void StandardConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000237 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000238 bool PrintedSomething = false;
239 if (First != ICK_Identity) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000240 OS << GetImplicitConversionName(First);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000241 PrintedSomething = true;
242 }
243
244 if (Second != ICK_Identity) {
245 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000246 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000247 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000248 OS << GetImplicitConversionName(Second);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000249
250 if (CopyConstructor) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000251 OS << " (by copy constructor)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000252 } else if (DirectBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000253 OS << " (direct reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000254 } else if (ReferenceBinding) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000255 OS << " (reference binding)";
Douglas Gregor2fe98832008-11-03 19:09:14 +0000256 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000257 PrintedSomething = true;
258 }
259
260 if (Third != ICK_Identity) {
261 if (PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000262 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000263 }
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000264 OS << GetImplicitConversionName(Third);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000265 PrintedSomething = true;
266 }
267
268 if (!PrintedSomething) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000269 OS << "No conversions required";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000270 }
271}
272
273/// DebugPrint - Print this user-defined conversion sequence to standard
274/// error. Useful for debugging overloading issues.
275void UserDefinedConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000276 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000277 if (Before.First || Before.Second || Before.Third) {
278 Before.DebugPrint();
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000279 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000280 }
Benjamin Kramerb11416d2010-04-17 09:33:03 +0000281 OS << '\'' << ConversionFunction << '\'';
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000282 if (After.First || After.Second || After.Third) {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000283 OS << " -> ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000284 After.DebugPrint();
285 }
286}
287
288/// DebugPrint - Print this implicit conversion sequence to standard
289/// error. Useful for debugging overloading issues.
290void ImplicitConversionSequence::DebugPrint() const {
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000291 llvm::raw_ostream &OS = llvm::errs();
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000292 switch (ConversionKind) {
293 case StandardConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000294 OS << "Standard conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000295 Standard.DebugPrint();
296 break;
297 case UserDefinedConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000298 OS << "User-defined conversion: ";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000299 UserDefined.DebugPrint();
300 break;
301 case EllipsisConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000302 OS << "Ellipsis conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000303 break;
John McCall0d1da222010-01-12 00:44:57 +0000304 case AmbiguousConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000305 OS << "Ambiguous conversion";
John McCall0d1da222010-01-12 00:44:57 +0000306 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000307 case BadConversion:
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000308 OS << "Bad conversion";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000309 break;
310 }
311
Daniel Dunbar42e3df02010-01-22 02:04:41 +0000312 OS << "\n";
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000313}
314
John McCall0d1da222010-01-12 00:44:57 +0000315void AmbiguousConversionSequence::construct() {
316 new (&conversions()) ConversionSet();
317}
318
319void AmbiguousConversionSequence::destruct() {
320 conversions().~ConversionSet();
321}
322
323void
324AmbiguousConversionSequence::copyFrom(const AmbiguousConversionSequence &O) {
325 FromTypePtr = O.FromTypePtr;
326 ToTypePtr = O.ToTypePtr;
327 new (&conversions()) ConversionSet(O.conversions());
328}
329
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000330namespace {
331 // Structure used by OverloadCandidate::DeductionFailureInfo to store
332 // template parameter and template argument information.
333 struct DFIParamWithArguments {
334 TemplateParameter Param;
335 TemplateArgument FirstArg;
336 TemplateArgument SecondArg;
337 };
338}
339
340/// \brief Convert from Sema's representation of template deduction information
341/// to the form used in overload-candidate information.
342OverloadCandidate::DeductionFailureInfo
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000343static MakeDeductionFailureInfo(ASTContext &Context,
344 Sema::TemplateDeductionResult TDK,
John McCall19c1bfd2010-08-25 05:32:35 +0000345 TemplateDeductionInfo &Info) {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000346 OverloadCandidate::DeductionFailureInfo Result;
347 Result.Result = static_cast<unsigned>(TDK);
348 Result.Data = 0;
349 switch (TDK) {
350 case Sema::TDK_Success:
351 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000352 case Sema::TDK_TooManyArguments:
353 case Sema::TDK_TooFewArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000354 break;
355
356 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000357 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000358 Result.Data = Info.Param.getOpaqueValue();
359 break;
360
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000361 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000362 case Sema::TDK_Underqualified: {
Douglas Gregor90cf2c92010-05-08 20:18:54 +0000363 // FIXME: Should allocate from normal heap so that we can free this later.
364 DFIParamWithArguments *Saved = new (Context) DFIParamWithArguments;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000365 Saved->Param = Info.Param;
366 Saved->FirstArg = Info.FirstArg;
367 Saved->SecondArg = Info.SecondArg;
368 Result.Data = Saved;
369 break;
370 }
371
372 case Sema::TDK_SubstitutionFailure:
Douglas Gregord09efd42010-05-08 20:07:26 +0000373 Result.Data = Info.take();
374 break;
375
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000376 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000377 case Sema::TDK_FailedOverloadResolution:
378 break;
379 }
380
381 return Result;
382}
John McCall0d1da222010-01-12 00:44:57 +0000383
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000384void OverloadCandidate::DeductionFailureInfo::Destroy() {
385 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
386 case Sema::TDK_Success:
387 case Sema::TDK_InstantiationDepth:
388 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000389 case Sema::TDK_TooManyArguments:
390 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000391 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000392 break;
393
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000394 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000395 case Sema::TDK_Underqualified:
Douglas Gregorb02d6b32010-05-08 20:20:05 +0000396 // FIXME: Destroy the data?
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000397 Data = 0;
398 break;
Douglas Gregord09efd42010-05-08 20:07:26 +0000399
400 case Sema::TDK_SubstitutionFailure:
401 // FIXME: Destroy the template arugment list?
402 Data = 0;
403 break;
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000404
Douglas Gregor461761d2010-05-08 18:20:53 +0000405 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000406 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000407 case Sema::TDK_FailedOverloadResolution:
408 break;
409 }
410}
411
412TemplateParameter
413OverloadCandidate::DeductionFailureInfo::getTemplateParameter() {
414 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
415 case Sema::TDK_Success:
416 case Sema::TDK_InstantiationDepth:
Douglas Gregor461761d2010-05-08 18:20:53 +0000417 case Sema::TDK_TooManyArguments:
418 case Sema::TDK_TooFewArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000419 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000420 return TemplateParameter();
421
422 case Sema::TDK_Incomplete:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000423 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000424 return TemplateParameter::getFromOpaqueValue(Data);
425
426 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000427 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000428 return static_cast<DFIParamWithArguments*>(Data)->Param;
429
430 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000431 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000432 case Sema::TDK_FailedOverloadResolution:
433 break;
434 }
435
436 return TemplateParameter();
437}
Douglas Gregord09efd42010-05-08 20:07:26 +0000438
439TemplateArgumentList *
440OverloadCandidate::DeductionFailureInfo::getTemplateArgumentList() {
441 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
442 case Sema::TDK_Success:
443 case Sema::TDK_InstantiationDepth:
444 case Sema::TDK_TooManyArguments:
445 case Sema::TDK_TooFewArguments:
446 case Sema::TDK_Incomplete:
447 case Sema::TDK_InvalidExplicitArguments:
448 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000449 case Sema::TDK_Underqualified:
Douglas Gregord09efd42010-05-08 20:07:26 +0000450 return 0;
451
452 case Sema::TDK_SubstitutionFailure:
453 return static_cast<TemplateArgumentList*>(Data);
454
455 // Unhandled
456 case Sema::TDK_NonDeducedMismatch:
457 case Sema::TDK_FailedOverloadResolution:
458 break;
459 }
460
461 return 0;
462}
463
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000464const TemplateArgument *OverloadCandidate::DeductionFailureInfo::getFirstArg() {
465 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
466 case Sema::TDK_Success:
467 case Sema::TDK_InstantiationDepth:
468 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000469 case Sema::TDK_TooManyArguments:
470 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000471 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000472 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000473 return 0;
474
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000475 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000476 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000477 return &static_cast<DFIParamWithArguments*>(Data)->FirstArg;
478
Douglas Gregor461761d2010-05-08 18:20:53 +0000479 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000480 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000481 case Sema::TDK_FailedOverloadResolution:
482 break;
483 }
484
485 return 0;
486}
487
488const TemplateArgument *
489OverloadCandidate::DeductionFailureInfo::getSecondArg() {
490 switch (static_cast<Sema::TemplateDeductionResult>(Result)) {
491 case Sema::TDK_Success:
492 case Sema::TDK_InstantiationDepth:
493 case Sema::TDK_Incomplete:
Douglas Gregor461761d2010-05-08 18:20:53 +0000494 case Sema::TDK_TooManyArguments:
495 case Sema::TDK_TooFewArguments:
Douglas Gregor1d72edd2010-05-08 19:15:54 +0000496 case Sema::TDK_InvalidExplicitArguments:
Douglas Gregord09efd42010-05-08 20:07:26 +0000497 case Sema::TDK_SubstitutionFailure:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000498 return 0;
499
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000500 case Sema::TDK_Inconsistent:
John McCall42d7d192010-08-05 09:05:08 +0000501 case Sema::TDK_Underqualified:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000502 return &static_cast<DFIParamWithArguments*>(Data)->SecondArg;
503
Douglas Gregor461761d2010-05-08 18:20:53 +0000504 // Unhandled
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000505 case Sema::TDK_NonDeducedMismatch:
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000506 case Sema::TDK_FailedOverloadResolution:
507 break;
508 }
509
510 return 0;
511}
512
513void OverloadCandidateSet::clear() {
Douglas Gregor3626a5c2010-05-08 17:41:32 +0000514 inherited::clear();
515 Functions.clear();
516}
517
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000518// IsOverload - Determine whether the given New declaration is an
John McCall3d988d92009-12-02 08:47:38 +0000519// overload of the declarations in Old. This routine returns false if
520// New and Old cannot be overloaded, e.g., if New has the same
521// signature as some function in Old (C++ 1.3.10) or if the Old
522// declarations aren't functions (or function templates) at all. When
John McCalldaa3d6b2009-12-09 03:35:25 +0000523// it does return false, MatchedDecl will point to the decl that New
524// cannot be overloaded with. This decl may be a UsingShadowDecl on
525// top of the underlying declaration.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000526//
527// Example: Given the following input:
528//
529// void f(int, float); // #1
530// void f(int, int); // #2
531// int f(int, int); // #3
532//
533// When we process #1, there is no previous declaration of "f",
Mike Stump11289f42009-09-09 15:08:12 +0000534// so IsOverload will not be used.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000535//
John McCall3d988d92009-12-02 08:47:38 +0000536// When we process #2, Old contains only the FunctionDecl for #1. By
537// comparing the parameter types, we see that #1 and #2 are overloaded
538// (since they have different signatures), so this routine returns
539// false; MatchedDecl is unchanged.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000540//
John McCall3d988d92009-12-02 08:47:38 +0000541// When we process #3, Old is an overload set containing #1 and #2. We
542// compare the signatures of #3 to #1 (they're overloaded, so we do
543// nothing) and then #3 to #2. Since the signatures of #3 and #2 are
544// identical (return types of functions are not part of the
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000545// signature), IsOverload returns false and MatchedDecl will be set to
546// point to the FunctionDecl for #2.
John McCalle9cccd82010-06-16 08:42:20 +0000547//
548// 'NewIsUsingShadowDecl' indicates that 'New' is being introduced
549// into a class by a using declaration. The rules for whether to hide
550// shadow declarations ignore some properties which otherwise figure
551// into a function template's signature.
John McCalldaa3d6b2009-12-09 03:35:25 +0000552Sema::OverloadKind
John McCalle9cccd82010-06-16 08:42:20 +0000553Sema::CheckOverload(Scope *S, FunctionDecl *New, const LookupResult &Old,
554 NamedDecl *&Match, bool NewIsUsingDecl) {
John McCall3d988d92009-12-02 08:47:38 +0000555 for (LookupResult::iterator I = Old.begin(), E = Old.end();
John McCall1f82f242009-11-18 22:49:29 +0000556 I != E; ++I) {
John McCalle9cccd82010-06-16 08:42:20 +0000557 NamedDecl *OldD = *I;
558
559 bool OldIsUsingDecl = false;
560 if (isa<UsingShadowDecl>(OldD)) {
561 OldIsUsingDecl = true;
562
563 // We can always introduce two using declarations into the same
564 // context, even if they have identical signatures.
565 if (NewIsUsingDecl) continue;
566
567 OldD = cast<UsingShadowDecl>(OldD)->getTargetDecl();
568 }
569
570 // If either declaration was introduced by a using declaration,
571 // we'll need to use slightly different rules for matching.
572 // Essentially, these rules are the normal rules, except that
573 // function templates hide function templates with different
574 // return types or template parameter lists.
575 bool UseMemberUsingDeclRules =
576 (OldIsUsingDecl || NewIsUsingDecl) && CurContext->isRecord();
577
John McCall3d988d92009-12-02 08:47:38 +0000578 if (FunctionTemplateDecl *OldT = dyn_cast<FunctionTemplateDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000579 if (!IsOverload(New, OldT->getTemplatedDecl(), UseMemberUsingDeclRules)) {
580 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
581 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
582 continue;
583 }
584
John McCalldaa3d6b2009-12-09 03:35:25 +0000585 Match = *I;
586 return Ovl_Match;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000587 }
John McCall3d988d92009-12-02 08:47:38 +0000588 } else if (FunctionDecl *OldF = dyn_cast<FunctionDecl>(OldD)) {
John McCalle9cccd82010-06-16 08:42:20 +0000589 if (!IsOverload(New, OldF, UseMemberUsingDeclRules)) {
590 if (UseMemberUsingDeclRules && OldIsUsingDecl) {
591 HideUsingShadowDecl(S, cast<UsingShadowDecl>(*I));
592 continue;
593 }
594
John McCalldaa3d6b2009-12-09 03:35:25 +0000595 Match = *I;
596 return Ovl_Match;
John McCall1f82f242009-11-18 22:49:29 +0000597 }
John McCalla8987a2942010-11-10 03:01:53 +0000598 } else if (isa<UsingDecl>(OldD)) {
John McCall84d87672009-12-10 09:41:52 +0000599 // We can overload with these, which can show up when doing
600 // redeclaration checks for UsingDecls.
601 assert(Old.getLookupKind() == LookupUsingDeclName);
John McCalla8987a2942010-11-10 03:01:53 +0000602 } else if (isa<TagDecl>(OldD)) {
603 // We can always overload with tags by hiding them.
John McCall84d87672009-12-10 09:41:52 +0000604 } else if (isa<UnresolvedUsingValueDecl>(OldD)) {
605 // Optimistically assume that an unresolved using decl will
606 // overload; if it doesn't, we'll have to diagnose during
607 // template instantiation.
608 } else {
John McCall1f82f242009-11-18 22:49:29 +0000609 // (C++ 13p1):
610 // Only function declarations can be overloaded; object and type
611 // declarations cannot be overloaded.
John McCalldaa3d6b2009-12-09 03:35:25 +0000612 Match = *I;
613 return Ovl_NonFunction;
John McCall1f82f242009-11-18 22:49:29 +0000614 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000615 }
John McCall1f82f242009-11-18 22:49:29 +0000616
John McCalldaa3d6b2009-12-09 03:35:25 +0000617 return Ovl_Overload;
John McCall1f82f242009-11-18 22:49:29 +0000618}
619
John McCalle9cccd82010-06-16 08:42:20 +0000620bool Sema::IsOverload(FunctionDecl *New, FunctionDecl *Old,
621 bool UseUsingDeclRules) {
John McCall8246e352010-08-12 07:09:11 +0000622 // If both of the functions are extern "C", then they are not
623 // overloads.
624 if (Old->isExternC() && New->isExternC())
625 return false;
626
John McCall1f82f242009-11-18 22:49:29 +0000627 FunctionTemplateDecl *OldTemplate = Old->getDescribedFunctionTemplate();
628 FunctionTemplateDecl *NewTemplate = New->getDescribedFunctionTemplate();
629
630 // C++ [temp.fct]p2:
631 // A function template can be overloaded with other function templates
632 // and with normal (non-template) functions.
633 if ((OldTemplate == 0) != (NewTemplate == 0))
634 return true;
635
636 // Is the function New an overload of the function Old?
637 QualType OldQType = Context.getCanonicalType(Old->getType());
638 QualType NewQType = Context.getCanonicalType(New->getType());
639
640 // Compare the signatures (C++ 1.3.10) of the two functions to
641 // determine whether they are overloads. If we find any mismatch
642 // in the signature, they are overloads.
643
644 // If either of these functions is a K&R-style function (no
645 // prototype), then we consider them to have matching signatures.
646 if (isa<FunctionNoProtoType>(OldQType.getTypePtr()) ||
647 isa<FunctionNoProtoType>(NewQType.getTypePtr()))
648 return false;
649
John McCall424cec92011-01-19 06:33:43 +0000650 const FunctionProtoType* OldType = cast<FunctionProtoType>(OldQType);
651 const FunctionProtoType* NewType = cast<FunctionProtoType>(NewQType);
John McCall1f82f242009-11-18 22:49:29 +0000652
653 // The signature of a function includes the types of its
654 // parameters (C++ 1.3.10), which includes the presence or absence
655 // of the ellipsis; see C++ DR 357).
656 if (OldQType != NewQType &&
657 (OldType->getNumArgs() != NewType->getNumArgs() ||
658 OldType->isVariadic() != NewType->isVariadic() ||
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +0000659 !FunctionArgTypesAreEqual(OldType, NewType)))
John McCall1f82f242009-11-18 22:49:29 +0000660 return true;
661
662 // C++ [temp.over.link]p4:
663 // The signature of a function template consists of its function
664 // signature, its return type and its template parameter list. The names
665 // of the template parameters are significant only for establishing the
666 // relationship between the template parameters and the rest of the
667 // signature.
668 //
669 // We check the return type and template parameter lists for function
670 // templates first; the remaining checks follow.
John McCalle9cccd82010-06-16 08:42:20 +0000671 //
672 // However, we don't consider either of these when deciding whether
673 // a member introduced by a shadow declaration is hidden.
674 if (!UseUsingDeclRules && NewTemplate &&
John McCall1f82f242009-11-18 22:49:29 +0000675 (!TemplateParameterListsAreEqual(NewTemplate->getTemplateParameters(),
676 OldTemplate->getTemplateParameters(),
677 false, TPL_TemplateMatch) ||
678 OldType->getResultType() != NewType->getResultType()))
679 return true;
680
681 // If the function is a class member, its signature includes the
682 // cv-qualifiers (if any) on the function itself.
683 //
684 // As part of this, also check whether one of the member functions
685 // is static, in which case they are not overloads (C++
686 // 13.1p2). While not part of the definition of the signature,
687 // this check is important to determine whether these functions
688 // can be overloaded.
689 CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
690 CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
691 if (OldMethod && NewMethod &&
692 !OldMethod->isStatic() && !NewMethod->isStatic() &&
693 OldMethod->getTypeQualifiers() != NewMethod->getTypeQualifiers())
694 return true;
695
696 // The signatures match; this is not an overload.
697 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000698}
699
Douglas Gregor8e1cf602008-10-29 00:13:59 +0000700/// TryImplicitConversion - Attempt to perform an implicit conversion
701/// from the given expression (Expr) to the given type (ToType). This
702/// function returns an implicit conversion sequence that can be used
703/// to perform the initialization. Given
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000704///
705/// void f(float f);
706/// void g(int i) { f(i); }
707///
708/// this routine would produce an implicit conversion sequence to
709/// describe the initialization of f from i, which will be a standard
710/// conversion sequence containing an lvalue-to-rvalue conversion (C++
711/// 4.1) followed by a floating-integral conversion (C++ 4.9).
712//
713/// Note that this routine only determines how the conversion can be
714/// performed; it does not actually perform the conversion. As such,
715/// it will not produce any diagnostics if no conversion is available,
716/// but will instead return an implicit conversion sequence of kind
717/// "BadConversion".
Douglas Gregor2fe98832008-11-03 19:09:14 +0000718///
719/// If @p SuppressUserConversions, then user-defined conversions are
720/// not permitted.
Douglas Gregor5fb53972009-01-14 15:45:31 +0000721/// If @p AllowExplicit, then explicit user-defined conversions are
722/// permitted.
John McCall5c32be02010-08-24 20:38:10 +0000723static ImplicitConversionSequence
724TryImplicitConversion(Sema &S, Expr *From, QualType ToType,
725 bool SuppressUserConversions,
726 bool AllowExplicit,
727 bool InOverloadResolution) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000728 ImplicitConversionSequence ICS;
John McCall5c32be02010-08-24 20:38:10 +0000729 if (IsStandardConversion(S, From, ToType, InOverloadResolution,
730 ICS.Standard)) {
John McCall0d1da222010-01-12 00:44:57 +0000731 ICS.setStandard();
John McCallbc077cf2010-02-08 23:07:23 +0000732 return ICS;
733 }
734
John McCall5c32be02010-08-24 20:38:10 +0000735 if (!S.getLangOptions().CPlusPlus) {
John McCall65eb8792010-02-25 01:37:24 +0000736 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
John McCallbc077cf2010-02-08 23:07:23 +0000737 return ICS;
738 }
739
Douglas Gregor836a7e82010-08-11 02:15:33 +0000740 // C++ [over.ics.user]p4:
741 // A conversion of an expression of class type to the same class
742 // type is given Exact Match rank, and a conversion of an
743 // expression of class type to a base class of that type is
744 // given Conversion rank, in spite of the fact that a copy/move
745 // constructor (i.e., a user-defined conversion function) is
746 // called for those cases.
747 QualType FromType = From->getType();
748 if (ToType->getAs<RecordType>() && FromType->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +0000749 (S.Context.hasSameUnqualifiedType(FromType, ToType) ||
750 S.IsDerivedFrom(FromType, ToType))) {
Douglas Gregor5ab11652010-04-17 22:01:05 +0000751 ICS.setStandard();
752 ICS.Standard.setAsIdentityConversion();
753 ICS.Standard.setFromType(FromType);
754 ICS.Standard.setAllToTypes(ToType);
755
756 // We don't actually check at this point whether there is a valid
757 // copy/move constructor, since overloading just assumes that it
758 // exists. When we actually perform initialization, we'll find the
759 // appropriate constructor to copy the returned object, if needed.
760 ICS.Standard.CopyConstructor = 0;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000761
Douglas Gregor5ab11652010-04-17 22:01:05 +0000762 // Determine whether this is considered a derived-to-base conversion.
John McCall5c32be02010-08-24 20:38:10 +0000763 if (!S.Context.hasSameUnqualifiedType(FromType, ToType))
Douglas Gregor5ab11652010-04-17 22:01:05 +0000764 ICS.Standard.Second = ICK_Derived_To_Base;
Douglas Gregor836a7e82010-08-11 02:15:33 +0000765
766 return ICS;
767 }
768
769 if (SuppressUserConversions) {
770 // We're not in the case above, so there is no conversion that
771 // we can perform.
772 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Douglas Gregor5ab11652010-04-17 22:01:05 +0000773 return ICS;
774 }
775
776 // Attempt user-defined conversion.
John McCallbc077cf2010-02-08 23:07:23 +0000777 OverloadCandidateSet Conversions(From->getExprLoc());
778 OverloadingResult UserDefResult
John McCall5c32be02010-08-24 20:38:10 +0000779 = IsUserDefinedConversion(S, From, ToType, ICS.UserDefined, Conversions,
Douglas Gregor5ab11652010-04-17 22:01:05 +0000780 AllowExplicit);
John McCallbc077cf2010-02-08 23:07:23 +0000781
782 if (UserDefResult == OR_Success) {
John McCall0d1da222010-01-12 00:44:57 +0000783 ICS.setUserDefined();
Douglas Gregor05379422008-11-03 17:51:48 +0000784 // C++ [over.ics.user]p4:
785 // A conversion of an expression of class type to the same class
786 // type is given Exact Match rank, and a conversion of an
787 // expression of class type to a base class of that type is
788 // given Conversion rank, in spite of the fact that a copy
789 // constructor (i.e., a user-defined conversion function) is
790 // called for those cases.
Mike Stump11289f42009-09-09 15:08:12 +0000791 if (CXXConstructorDecl *Constructor
Douglas Gregor05379422008-11-03 17:51:48 +0000792 = dyn_cast<CXXConstructorDecl>(ICS.UserDefined.ConversionFunction)) {
Mike Stump11289f42009-09-09 15:08:12 +0000793 QualType FromCanon
John McCall5c32be02010-08-24 20:38:10 +0000794 = S.Context.getCanonicalType(From->getType().getUnqualifiedType());
795 QualType ToCanon
796 = S.Context.getCanonicalType(ToType).getUnqualifiedType();
Douglas Gregor507eb872009-12-22 00:34:07 +0000797 if (Constructor->isCopyConstructor() &&
John McCall5c32be02010-08-24 20:38:10 +0000798 (FromCanon == ToCanon || S.IsDerivedFrom(FromCanon, ToCanon))) {
Douglas Gregor2fe98832008-11-03 19:09:14 +0000799 // Turn this into a "standard" conversion sequence, so that it
800 // gets ranked with standard conversion sequences.
John McCall0d1da222010-01-12 00:44:57 +0000801 ICS.setStandard();
Douglas Gregor05379422008-11-03 17:51:48 +0000802 ICS.Standard.setAsIdentityConversion();
John McCall0d1da222010-01-12 00:44:57 +0000803 ICS.Standard.setFromType(From->getType());
Douglas Gregor3edc4d52010-01-27 03:51:04 +0000804 ICS.Standard.setAllToTypes(ToType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000805 ICS.Standard.CopyConstructor = Constructor;
Douglas Gregorbb2e68832009-02-02 22:11:10 +0000806 if (ToCanon != FromCanon)
Douglas Gregor05379422008-11-03 17:51:48 +0000807 ICS.Standard.Second = ICK_Derived_To_Base;
808 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000809 }
Douglas Gregor576e98c2009-01-30 23:27:23 +0000810
811 // C++ [over.best.ics]p4:
812 // However, when considering the argument of a user-defined
813 // conversion function that is a candidate by 13.3.1.3 when
814 // invoked for the copying of the temporary in the second step
815 // of a class copy-initialization, or by 13.3.1.4, 13.3.1.5, or
816 // 13.3.1.6 in all cases, only standard conversion sequences and
817 // ellipsis conversion sequences are allowed.
John McCall6a61b522010-01-13 09:16:55 +0000818 if (SuppressUserConversions && ICS.isUserDefined()) {
John McCall65eb8792010-02-25 01:37:24 +0000819 ICS.setBad(BadConversionSequence::suppressed_user, From, ToType);
John McCall6a61b522010-01-13 09:16:55 +0000820 }
John McCalle8c8cd22010-01-13 22:30:33 +0000821 } else if (UserDefResult == OR_Ambiguous && !SuppressUserConversions) {
John McCall0d1da222010-01-12 00:44:57 +0000822 ICS.setAmbiguous();
823 ICS.Ambiguous.setFromType(From->getType());
824 ICS.Ambiguous.setToType(ToType);
825 for (OverloadCandidateSet::iterator Cand = Conversions.begin();
826 Cand != Conversions.end(); ++Cand)
827 if (Cand->Viable)
828 ICS.Ambiguous.addConversion(Cand->Function);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000829 } else {
John McCall65eb8792010-02-25 01:37:24 +0000830 ICS.setBad(BadConversionSequence::no_conversion, From, ToType);
Fariborz Jahanian21ccf062009-09-23 00:58:07 +0000831 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000832
833 return ICS;
834}
835
John McCall5c32be02010-08-24 20:38:10 +0000836bool Sema::TryImplicitConversion(InitializationSequence &Sequence,
837 const InitializedEntity &Entity,
838 Expr *Initializer,
839 bool SuppressUserConversions,
840 bool AllowExplicitConversions,
841 bool InOverloadResolution) {
842 ImplicitConversionSequence ICS
843 = clang::TryImplicitConversion(*this, Initializer, Entity.getType(),
844 SuppressUserConversions,
845 AllowExplicitConversions,
846 InOverloadResolution);
847 if (ICS.isBad()) return true;
848
849 // Perform the actual conversion.
850 Sequence.AddConversionSequenceStep(ICS, Entity.getType());
851 return false;
852}
853
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000854/// PerformImplicitConversion - Perform an implicit conversion of the
855/// expression From to the type ToType. Returns true if there was an
856/// error, false otherwise. The expression From is replaced with the
857/// converted expression. Flavor is the kind of conversion we're
858/// performing, used in the error message. If @p AllowExplicit,
859/// explicit user-defined conversions are permitted.
860bool
861Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
862 AssignmentAction Action, bool AllowExplicit) {
863 ImplicitConversionSequence ICS;
864 return PerformImplicitConversion(From, ToType, Action, AllowExplicit, ICS);
865}
866
867bool
868Sema::PerformImplicitConversion(Expr *&From, QualType ToType,
869 AssignmentAction Action, bool AllowExplicit,
870 ImplicitConversionSequence& ICS) {
John McCall5c32be02010-08-24 20:38:10 +0000871 ICS = clang::TryImplicitConversion(*this, From, ToType,
872 /*SuppressUserConversions=*/false,
873 AllowExplicit,
874 /*InOverloadResolution=*/false);
Douglas Gregorae4b5df2010-04-16 22:27:05 +0000875 return PerformImplicitConversion(From, ToType, ICS, Action);
876}
877
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000878/// \brief Determine whether the conversion from FromType to ToType is a valid
879/// conversion that strips "noreturn" off the nested function type.
880static bool IsNoReturnConversion(ASTContext &Context, QualType FromType,
881 QualType ToType, QualType &ResultTy) {
882 if (Context.hasSameUnqualifiedType(FromType, ToType))
883 return false;
884
John McCall991eb4b2010-12-21 00:44:39 +0000885 // Permit the conversion F(t __attribute__((noreturn))) -> F(t)
886 // where F adds one of the following at most once:
887 // - a pointer
888 // - a member pointer
889 // - a block pointer
890 CanQualType CanTo = Context.getCanonicalType(ToType);
891 CanQualType CanFrom = Context.getCanonicalType(FromType);
892 Type::TypeClass TyClass = CanTo->getTypeClass();
893 if (TyClass != CanFrom->getTypeClass()) return false;
894 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto) {
895 if (TyClass == Type::Pointer) {
896 CanTo = CanTo.getAs<PointerType>()->getPointeeType();
897 CanFrom = CanFrom.getAs<PointerType>()->getPointeeType();
898 } else if (TyClass == Type::BlockPointer) {
899 CanTo = CanTo.getAs<BlockPointerType>()->getPointeeType();
900 CanFrom = CanFrom.getAs<BlockPointerType>()->getPointeeType();
901 } else if (TyClass == Type::MemberPointer) {
902 CanTo = CanTo.getAs<MemberPointerType>()->getPointeeType();
903 CanFrom = CanFrom.getAs<MemberPointerType>()->getPointeeType();
904 } else {
905 return false;
906 }
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000907
John McCall991eb4b2010-12-21 00:44:39 +0000908 TyClass = CanTo->getTypeClass();
909 if (TyClass != CanFrom->getTypeClass()) return false;
910 if (TyClass != Type::FunctionProto && TyClass != Type::FunctionNoProto)
911 return false;
912 }
913
914 const FunctionType *FromFn = cast<FunctionType>(CanFrom);
915 FunctionType::ExtInfo EInfo = FromFn->getExtInfo();
916 if (!EInfo.getNoReturn()) return false;
917
918 FromFn = Context.adjustFunctionType(FromFn, EInfo.withNoReturn(false));
919 assert(QualType(FromFn, 0).isCanonical());
920 if (QualType(FromFn, 0) != CanTo) return false;
921
922 ResultTy = ToType;
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000923 return true;
924}
Douglas Gregor46188682010-05-18 22:42:18 +0000925
926/// \brief Determine whether the conversion from FromType to ToType is a valid
927/// vector conversion.
928///
929/// \param ICK Will be set to the vector conversion kind, if this is a vector
930/// conversion.
931static bool IsVectorConversion(ASTContext &Context, QualType FromType,
932 QualType ToType, ImplicitConversionKind &ICK) {
933 // We need at least one of these types to be a vector type to have a vector
934 // conversion.
935 if (!ToType->isVectorType() && !FromType->isVectorType())
936 return false;
937
938 // Identical types require no conversions.
939 if (Context.hasSameUnqualifiedType(FromType, ToType))
940 return false;
941
942 // There are no conversions between extended vector types, only identity.
943 if (ToType->isExtVectorType()) {
944 // There are no conversions between extended vector types other than the
945 // identity conversion.
946 if (FromType->isExtVectorType())
947 return false;
948
949 // Vector splat from any arithmetic type to a vector.
Douglas Gregora3208f92010-06-22 23:41:02 +0000950 if (FromType->isArithmeticType()) {
Douglas Gregor46188682010-05-18 22:42:18 +0000951 ICK = ICK_Vector_Splat;
952 return true;
953 }
954 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000955
956 // We can perform the conversion between vector types in the following cases:
957 // 1)vector types are equivalent AltiVec and GCC vector types
958 // 2)lax vector conversions are permitted and the vector types are of the
959 // same size
960 if (ToType->isVectorType() && FromType->isVectorType()) {
961 if (Context.areCompatibleVectorTypes(FromType, ToType) ||
Chandler Carruth9c524c12010-08-08 05:02:51 +0000962 (Context.getLangOptions().LaxVectorConversions &&
963 (Context.getTypeSize(FromType) == Context.getTypeSize(ToType)))) {
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000964 ICK = ICK_Vector_Conversion;
965 return true;
966 }
Douglas Gregor46188682010-05-18 22:42:18 +0000967 }
Douglas Gregor59e8b3b2010-08-06 10:14:59 +0000968
Douglas Gregor46188682010-05-18 22:42:18 +0000969 return false;
970}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +0000971
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000972/// IsStandardConversion - Determines whether there is a standard
973/// conversion sequence (C++ [conv], C++ [over.ics.scs]) from the
974/// expression From to the type ToType. Standard conversion sequences
975/// only consider non-class types; for conversions that involve class
976/// types, use TryImplicitConversion. If a conversion exists, SCS will
977/// contain the standard conversion sequence required to perform this
978/// conversion and this routine will return true. Otherwise, this
979/// routine will return false and the value of SCS is unspecified.
John McCall5c32be02010-08-24 20:38:10 +0000980static bool IsStandardConversion(Sema &S, Expr* From, QualType ToType,
981 bool InOverloadResolution,
982 StandardConversionSequence &SCS) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000983 QualType FromType = From->getType();
John McCall5c32be02010-08-24 20:38:10 +0000984
Douglas Gregor26bee0b2008-10-31 16:23:19 +0000985 // Standard conversions (C++ [conv])
Douglas Gregora11693b2008-11-12 17:17:38 +0000986 SCS.setAsIdentityConversion();
Douglas Gregore489a7d2010-02-28 18:30:25 +0000987 SCS.DeprecatedStringLiteralToCharPtr = false;
Douglas Gregor47d3f272008-12-19 17:40:08 +0000988 SCS.IncompatibleObjC = false;
John McCall0d1da222010-01-12 00:44:57 +0000989 SCS.setFromType(FromType);
Douglas Gregor2fe98832008-11-03 19:09:14 +0000990 SCS.CopyConstructor = 0;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000991
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000992 // There are no standard conversions for class types in C++, so
Mike Stump11289f42009-09-09 15:08:12 +0000993 // abort early. When overloading in C, however, we do permit
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000994 if (FromType->isRecordType() || ToType->isRecordType()) {
John McCall5c32be02010-08-24 20:38:10 +0000995 if (S.getLangOptions().CPlusPlus)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000996 return false;
997
Mike Stump11289f42009-09-09 15:08:12 +0000998 // When we're overloading in C, we allow, as standard conversions,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000999 }
1000
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001001 // The first conversion can be an lvalue-to-rvalue conversion,
1002 // array-to-pointer conversion, or function-to-pointer conversion
1003 // (C++ 4p1).
1004
John McCall5c32be02010-08-24 20:38:10 +00001005 if (FromType == S.Context.OverloadTy) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001006 DeclAccessPair AccessPair;
1007 if (FunctionDecl *Fn
John McCall5c32be02010-08-24 20:38:10 +00001008 = S.ResolveAddressOfOverloadedFunction(From, ToType, false,
1009 AccessPair)) {
Douglas Gregor980fb162010-04-29 18:24:40 +00001010 // We were able to resolve the address of the overloaded function,
1011 // so we can convert to the type of that function.
1012 FromType = Fn->getType();
1013 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
1014 if (!Method->isStatic()) {
John McCall424cec92011-01-19 06:33:43 +00001015 const Type *ClassType
John McCall5c32be02010-08-24 20:38:10 +00001016 = S.Context.getTypeDeclType(Method->getParent()).getTypePtr();
1017 FromType = S.Context.getMemberPointerType(FromType, ClassType);
Douglas Gregor980fb162010-04-29 18:24:40 +00001018 }
1019 }
1020
1021 // If the "from" expression takes the address of the overloaded
1022 // function, update the type of the resulting expression accordingly.
1023 if (FromType->getAs<FunctionType>())
1024 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(From->IgnoreParens()))
John McCalle3027922010-08-25 11:45:40 +00001025 if (UnOp->getOpcode() == UO_AddrOf)
John McCall5c32be02010-08-24 20:38:10 +00001026 FromType = S.Context.getPointerType(FromType);
Douglas Gregor980fb162010-04-29 18:24:40 +00001027
1028 // Check that we've computed the proper type after overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00001029 assert(S.Context.hasSameType(FromType,
1030 S.FixOverloadedFunctionReference(From, AccessPair, Fn)->getType()));
Douglas Gregor980fb162010-04-29 18:24:40 +00001031 } else {
1032 return false;
1033 }
Anders Carlssonba37e1e2010-11-04 05:28:09 +00001034 }
Mike Stump11289f42009-09-09 15:08:12 +00001035 // Lvalue-to-rvalue conversion (C++ 4.1):
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001036 // An lvalue (3.10) of a non-function, non-array type T can be
1037 // converted to an rvalue.
John McCall086a4642010-11-24 05:12:34 +00001038 bool argIsLValue = From->isLValue();
1039 if (argIsLValue &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00001040 !FromType->isFunctionType() && !FromType->isArrayType() &&
John McCall5c32be02010-08-24 20:38:10 +00001041 S.Context.getCanonicalType(FromType) != S.Context.OverloadTy) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001042 SCS.First = ICK_Lvalue_To_Rvalue;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001043
1044 // If T is a non-class type, the type of the rvalue is the
1045 // cv-unqualified version of T. Otherwise, the type of the rvalue
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001046 // is T (C++ 4.1p1). C++ can't get here with class types; in C, we
1047 // just strip the qualifiers because they don't matter.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001048 FromType = FromType.getUnqualifiedType();
Mike Stump12b8ce12009-08-04 21:02:39 +00001049 } else if (FromType->isArrayType()) {
1050 // Array-to-pointer conversion (C++ 4.2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001051 SCS.First = ICK_Array_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001052
1053 // An lvalue or rvalue of type "array of N T" or "array of unknown
1054 // bound of T" can be converted to an rvalue of type "pointer to
1055 // T" (C++ 4.2p1).
John McCall5c32be02010-08-24 20:38:10 +00001056 FromType = S.Context.getArrayDecayedType(FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001057
John McCall5c32be02010-08-24 20:38:10 +00001058 if (S.IsStringLiteralToNonConstPointerConversion(From, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001059 // This conversion is deprecated. (C++ D.4).
Douglas Gregore489a7d2010-02-28 18:30:25 +00001060 SCS.DeprecatedStringLiteralToCharPtr = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001061
1062 // For the purpose of ranking in overload resolution
1063 // (13.3.3.1.1), this conversion is considered an
1064 // array-to-pointer conversion followed by a qualification
1065 // conversion (4.4). (C++ 4.2p2)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001066 SCS.Second = ICK_Identity;
1067 SCS.Third = ICK_Qualification;
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001068 SCS.setAllToTypes(FromType);
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001069 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001070 }
John McCall086a4642010-11-24 05:12:34 +00001071 } else if (FromType->isFunctionType() && argIsLValue) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001072 // Function-to-pointer conversion (C++ 4.3).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001073 SCS.First = ICK_Function_To_Pointer;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001074
1075 // An lvalue of function type T can be converted to an rvalue of
1076 // type "pointer to T." The result is a pointer to the
1077 // function. (C++ 4.3p1).
John McCall5c32be02010-08-24 20:38:10 +00001078 FromType = S.Context.getPointerType(FromType);
Mike Stump12b8ce12009-08-04 21:02:39 +00001079 } else {
1080 // We don't require any conversions for the first step.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001081 SCS.First = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001082 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001083 SCS.setToType(0, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001084
1085 // The second conversion can be an integral promotion, floating
1086 // point promotion, integral conversion, floating point conversion,
1087 // floating-integral conversion, pointer conversion,
1088 // pointer-to-member conversion, or boolean conversion (C++ 4p1).
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001089 // For overloading in C, this can also be a "compatible-type"
1090 // conversion.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001091 bool IncompatibleObjC = false;
Douglas Gregor46188682010-05-18 22:42:18 +00001092 ImplicitConversionKind SecondICK = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001093 if (S.Context.hasSameUnqualifiedType(FromType, ToType)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001094 // The unqualified versions of the types are the same: there's no
1095 // conversion to do.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001096 SCS.Second = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00001097 } else if (S.IsIntegralPromotion(From, FromType, ToType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001098 // Integral promotion (C++ 4.5).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001099 SCS.Second = ICK_Integral_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001100 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001101 } else if (S.IsFloatingPointPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001102 // Floating point promotion (C++ 4.6).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001103 SCS.Second = ICK_Floating_Promotion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001104 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001105 } else if (S.IsComplexPromotion(FromType, ToType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001106 // Complex promotion (Clang extension)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001107 SCS.Second = ICK_Complex_Promotion;
1108 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001109 } else if (ToType->isBooleanType() &&
1110 (FromType->isArithmeticType() ||
1111 FromType->isAnyPointerType() ||
1112 FromType->isBlockPointerType() ||
1113 FromType->isMemberPointerType() ||
1114 FromType->isNullPtrType())) {
1115 // Boolean conversions (C++ 4.12).
1116 SCS.Second = ICK_Boolean_Conversion;
1117 FromType = S.Context.BoolTy;
Douglas Gregor0bf31402010-10-08 23:50:27 +00001118 } else if (FromType->isIntegralOrUnscopedEnumerationType() &&
John McCall5c32be02010-08-24 20:38:10 +00001119 ToType->isIntegralType(S.Context)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001120 // Integral conversions (C++ 4.7).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001121 SCS.Second = ICK_Integral_Conversion;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001122 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001123 } else if (FromType->isAnyComplexType() && ToType->isComplexType()) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001124 // Complex conversions (C99 6.3.1.6)
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001125 SCS.Second = ICK_Complex_Conversion;
1126 FromType = ToType.getUnqualifiedType();
John McCall8cb679e2010-11-15 09:13:47 +00001127 } else if ((FromType->isAnyComplexType() && ToType->isArithmeticType()) ||
1128 (ToType->isAnyComplexType() && FromType->isArithmeticType())) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001129 // Complex-real conversions (C99 6.3.1.7)
1130 SCS.Second = ICK_Complex_Real;
1131 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001132 } else if (FromType->isRealFloatingType() && ToType->isRealFloatingType()) {
Chandler Carruth8fa1e7e2010-02-25 07:20:54 +00001133 // Floating point conversions (C++ 4.8).
1134 SCS.Second = ICK_Floating_Conversion;
1135 FromType = ToType.getUnqualifiedType();
Douglas Gregor49b4d732010-06-22 23:07:26 +00001136 } else if ((FromType->isRealFloatingType() &&
John McCall8cb679e2010-11-15 09:13:47 +00001137 ToType->isIntegralType(S.Context)) ||
Douglas Gregor0bf31402010-10-08 23:50:27 +00001138 (FromType->isIntegralOrUnscopedEnumerationType() &&
Douglas Gregor49b4d732010-06-22 23:07:26 +00001139 ToType->isRealFloatingType())) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001140 // Floating-integral conversions (C++ 4.9).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001141 SCS.Second = ICK_Floating_Integral;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001142 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001143 } else if (S.IsPointerConversion(From, FromType, ToType, InOverloadResolution,
1144 FromType, IncompatibleObjC)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001145 // Pointer conversions (C++ 4.10).
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001146 SCS.Second = ICK_Pointer_Conversion;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001147 SCS.IncompatibleObjC = IncompatibleObjC;
John McCall5c32be02010-08-24 20:38:10 +00001148 } else if (S.IsMemberPointerConversion(From, FromType, ToType,
1149 InOverloadResolution, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001150 // Pointer to member conversions (4.11).
Sebastian Redl72b597d2009-01-25 19:43:20 +00001151 SCS.Second = ICK_Pointer_Member;
John McCall5c32be02010-08-24 20:38:10 +00001152 } else if (IsVectorConversion(S.Context, FromType, ToType, SecondICK)) {
Douglas Gregor46188682010-05-18 22:42:18 +00001153 SCS.Second = SecondICK;
1154 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001155 } else if (!S.getLangOptions().CPlusPlus &&
1156 S.Context.typesAreCompatible(ToType, FromType)) {
Mike Stump12b8ce12009-08-04 21:02:39 +00001157 // Compatible conversions (Clang extension for C function overloading)
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001158 SCS.Second = ICK_Compatible_Conversion;
Douglas Gregor46188682010-05-18 22:42:18 +00001159 FromType = ToType.getUnqualifiedType();
John McCall5c32be02010-08-24 20:38:10 +00001160 } else if (IsNoReturnConversion(S.Context, FromType, ToType, FromType)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001161 // Treat a conversion that strips "noreturn" as an identity conversion.
1162 SCS.Second = ICK_NoReturn_Adjustment;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001163 } else {
1164 // No second conversion required.
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001165 SCS.Second = ICK_Identity;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001166 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001167 SCS.setToType(1, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001168
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001169 QualType CanonFrom;
1170 QualType CanonTo;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001171 // The third conversion can be a qualification conversion (C++ 4p1).
John McCall5c32be02010-08-24 20:38:10 +00001172 if (S.IsQualificationConversion(FromType, ToType)) {
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001173 SCS.Third = ICK_Qualification;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001174 FromType = ToType;
John McCall5c32be02010-08-24 20:38:10 +00001175 CanonFrom = S.Context.getCanonicalType(FromType);
1176 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001177 } else {
1178 // No conversion required
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001179 SCS.Third = ICK_Identity;
1180
Mike Stump11289f42009-09-09 15:08:12 +00001181 // C++ [over.best.ics]p6:
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001182 // [...] Any difference in top-level cv-qualification is
1183 // subsumed by the initialization itself and does not constitute
1184 // a conversion. [...]
John McCall5c32be02010-08-24 20:38:10 +00001185 CanonFrom = S.Context.getCanonicalType(FromType);
1186 CanonTo = S.Context.getCanonicalType(ToType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001187 if (CanonFrom.getLocalUnqualifiedType()
1188 == CanonTo.getLocalUnqualifiedType() &&
Fariborz Jahanian9f963c22010-05-18 23:04:17 +00001189 (CanonFrom.getLocalCVRQualifiers() != CanonTo.getLocalCVRQualifiers()
1190 || CanonFrom.getObjCGCAttr() != CanonTo.getObjCGCAttr())) {
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001191 FromType = ToType;
1192 CanonFrom = CanonTo;
1193 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001194 }
Douglas Gregor3edc4d52010-01-27 03:51:04 +00001195 SCS.setToType(2, FromType);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001196
1197 // If we have not converted the argument type to the parameter type,
1198 // this is a bad conversion sequence.
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001199 if (CanonFrom != CanonTo)
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001200 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001201
Douglas Gregor26bee0b2008-10-31 16:23:19 +00001202 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001203}
1204
1205/// IsIntegralPromotion - Determines whether the conversion from the
1206/// expression From (whose potentially-adjusted type is FromType) to
1207/// ToType is an integral promotion (C++ 4.5). If so, returns true and
1208/// sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001209bool Sema::IsIntegralPromotion(Expr *From, QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001210 const BuiltinType *To = ToType->getAs<BuiltinType>();
Sebastian Redlee547972008-11-04 15:59:10 +00001211 // All integers are built-in.
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001212 if (!To) {
1213 return false;
1214 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001215
1216 // An rvalue of type char, signed char, unsigned char, short int, or
1217 // unsigned short int can be converted to an rvalue of type int if
1218 // int can represent all the values of the source type; otherwise,
1219 // the source rvalue can be converted to an rvalue of type unsigned
1220 // int (C++ 4.5p1).
Douglas Gregora71cc152010-02-02 20:10:50 +00001221 if (FromType->isPromotableIntegerType() && !FromType->isBooleanType() &&
1222 !FromType->isEnumeralType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001223 if (// We can promote any signed, promotable integer type to an int
1224 (FromType->isSignedIntegerType() ||
1225 // We can promote any unsigned integer type whose size is
1226 // less than int to an int.
Mike Stump11289f42009-09-09 15:08:12 +00001227 (!FromType->isSignedIntegerType() &&
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001228 Context.getTypeSize(FromType) < Context.getTypeSize(ToType)))) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001229 return To->getKind() == BuiltinType::Int;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001230 }
1231
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001232 return To->getKind() == BuiltinType::UInt;
1233 }
1234
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001235 // C++0x [conv.prom]p3:
1236 // A prvalue of an unscoped enumeration type whose underlying type is not
1237 // fixed (7.2) can be converted to an rvalue a prvalue of the first of the
1238 // following types that can represent all the values of the enumeration
1239 // (i.e., the values in the range bmin to bmax as described in 7.2): int,
1240 // unsigned int, long int, unsigned long int, long long int, or unsigned
1241 // long long int. If none of the types in that list can represent all the
1242 // values of the enumeration, an rvalue a prvalue of an unscoped enumeration
1243 // type can be converted to an rvalue a prvalue of the extended integer type
1244 // with lowest integer conversion rank (4.13) greater than the rank of long
1245 // long in which all the values of the enumeration can be represented. If
1246 // there are two such extended types, the signed one is chosen.
Douglas Gregor0bf31402010-10-08 23:50:27 +00001247 if (const EnumType *FromEnumType = FromType->getAs<EnumType>()) {
1248 // C++0x 7.2p9: Note that this implicit enum to int conversion is not
1249 // provided for a scoped enumeration.
1250 if (FromEnumType->getDecl()->isScoped())
1251 return false;
1252
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001253 // We have already pre-calculated the promotion type, so this is trivial.
Douglas Gregorc87f4d42010-09-12 03:38:25 +00001254 if (ToType->isIntegerType() &&
1255 !RequireCompleteType(From->getLocStart(), FromType, PDiag()))
John McCall56774992009-12-09 09:09:27 +00001256 return Context.hasSameUnqualifiedType(ToType,
1257 FromEnumType->getDecl()->getPromotionType());
Douglas Gregor0bf31402010-10-08 23:50:27 +00001258 }
John McCall56774992009-12-09 09:09:27 +00001259
Douglas Gregorcd1d0b42010-10-21 18:04:08 +00001260 // C++0x [conv.prom]p2:
1261 // A prvalue of type char16_t, char32_t, or wchar_t (3.9.1) can be converted
1262 // to an rvalue a prvalue of the first of the following types that can
1263 // represent all the values of its underlying type: int, unsigned int,
1264 // long int, unsigned long int, long long int, or unsigned long long int.
1265 // If none of the types in that list can represent all the values of its
1266 // underlying type, an rvalue a prvalue of type char16_t, char32_t,
1267 // or wchar_t can be converted to an rvalue a prvalue of its underlying
1268 // type.
1269 if (FromType->isAnyCharacterType() && !FromType->isCharType() &&
1270 ToType->isIntegerType()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001271 // Determine whether the type we're converting from is signed or
1272 // unsigned.
1273 bool FromIsSigned;
1274 uint64_t FromSize = Context.getTypeSize(FromType);
John McCall56774992009-12-09 09:09:27 +00001275
1276 // FIXME: Is wchar_t signed or unsigned? We assume it's signed for now.
1277 FromIsSigned = true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001278
1279 // The types we'll try to promote to, in the appropriate
1280 // order. Try each of these types.
Mike Stump11289f42009-09-09 15:08:12 +00001281 QualType PromoteTypes[6] = {
1282 Context.IntTy, Context.UnsignedIntTy,
Douglas Gregor1d248c52008-12-12 02:00:36 +00001283 Context.LongTy, Context.UnsignedLongTy ,
1284 Context.LongLongTy, Context.UnsignedLongLongTy
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001285 };
Douglas Gregor1d248c52008-12-12 02:00:36 +00001286 for (int Idx = 0; Idx < 6; ++Idx) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001287 uint64_t ToSize = Context.getTypeSize(PromoteTypes[Idx]);
1288 if (FromSize < ToSize ||
Mike Stump11289f42009-09-09 15:08:12 +00001289 (FromSize == ToSize &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001290 FromIsSigned == PromoteTypes[Idx]->isSignedIntegerType())) {
1291 // We found the type that we can promote to. If this is the
1292 // type we wanted, we have a promotion. Otherwise, no
1293 // promotion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001294 return Context.hasSameUnqualifiedType(ToType, PromoteTypes[Idx]);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001295 }
1296 }
1297 }
1298
1299 // An rvalue for an integral bit-field (9.6) can be converted to an
1300 // rvalue of type int if int can represent all the values of the
1301 // bit-field; otherwise, it can be converted to unsigned int if
1302 // unsigned int can represent all the values of the bit-field. If
1303 // the bit-field is larger yet, no integral promotion applies to
1304 // it. If the bit-field has an enumerated type, it is treated as any
1305 // other value of that type for promotion purposes (C++ 4.5p3).
Mike Stump87c57ac2009-05-16 07:39:55 +00001306 // FIXME: We should delay checking of bit-fields until we actually perform the
1307 // conversion.
Douglas Gregor71235ec2009-05-02 02:18:30 +00001308 using llvm::APSInt;
1309 if (From)
1310 if (FieldDecl *MemberDecl = From->getBitField()) {
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001311 APSInt BitWidth;
Douglas Gregor6972a622010-06-16 00:35:25 +00001312 if (FromType->isIntegralType(Context) &&
Douglas Gregor71235ec2009-05-02 02:18:30 +00001313 MemberDecl->getBitWidth()->isIntegerConstantExpr(BitWidth, Context)) {
1314 APSInt ToSize(BitWidth.getBitWidth(), BitWidth.isUnsigned());
1315 ToSize = Context.getTypeSize(ToType);
Mike Stump11289f42009-09-09 15:08:12 +00001316
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001317 // Are we promoting to an int from a bitfield that fits in an int?
1318 if (BitWidth < ToSize ||
1319 (FromType->isSignedIntegerType() && BitWidth <= ToSize)) {
1320 return To->getKind() == BuiltinType::Int;
1321 }
Mike Stump11289f42009-09-09 15:08:12 +00001322
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001323 // Are we promoting to an unsigned int from an unsigned bitfield
1324 // that fits into an unsigned int?
1325 if (FromType->isUnsignedIntegerType() && BitWidth <= ToSize) {
1326 return To->getKind() == BuiltinType::UInt;
1327 }
Mike Stump11289f42009-09-09 15:08:12 +00001328
Douglas Gregor2eedc3a2008-12-20 23:49:58 +00001329 return false;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001330 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001331 }
Mike Stump11289f42009-09-09 15:08:12 +00001332
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001333 // An rvalue of type bool can be converted to an rvalue of type int,
1334 // with false becoming zero and true becoming one (C++ 4.5p4).
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001335 if (FromType->isBooleanType() && To->getKind() == BuiltinType::Int) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001336 return true;
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001337 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001338
1339 return false;
1340}
1341
1342/// IsFloatingPointPromotion - Determines whether the conversion from
1343/// FromType to ToType is a floating point promotion (C++ 4.6). If so,
1344/// returns true and sets PromotedType to the promoted type.
Mike Stump11289f42009-09-09 15:08:12 +00001345bool Sema::IsFloatingPointPromotion(QualType FromType, QualType ToType) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001346 /// An rvalue of type float can be converted to an rvalue of type
1347 /// double. (C++ 4.6p1).
John McCall9dd450b2009-09-21 23:43:11 +00001348 if (const BuiltinType *FromBuiltin = FromType->getAs<BuiltinType>())
1349 if (const BuiltinType *ToBuiltin = ToType->getAs<BuiltinType>()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001350 if (FromBuiltin->getKind() == BuiltinType::Float &&
1351 ToBuiltin->getKind() == BuiltinType::Double)
1352 return true;
1353
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001354 // C99 6.3.1.5p1:
1355 // When a float is promoted to double or long double, or a
1356 // double is promoted to long double [...].
1357 if (!getLangOptions().CPlusPlus &&
1358 (FromBuiltin->getKind() == BuiltinType::Float ||
1359 FromBuiltin->getKind() == BuiltinType::Double) &&
1360 (ToBuiltin->getKind() == BuiltinType::LongDouble))
1361 return true;
1362 }
1363
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001364 return false;
1365}
1366
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001367/// \brief Determine if a conversion is a complex promotion.
1368///
1369/// A complex promotion is defined as a complex -> complex conversion
1370/// where the conversion between the underlying real types is a
Douglas Gregor67525022009-02-12 00:26:06 +00001371/// floating-point or integral promotion.
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001372bool Sema::IsComplexPromotion(QualType FromType, QualType ToType) {
John McCall9dd450b2009-09-21 23:43:11 +00001373 const ComplexType *FromComplex = FromType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001374 if (!FromComplex)
1375 return false;
1376
John McCall9dd450b2009-09-21 23:43:11 +00001377 const ComplexType *ToComplex = ToType->getAs<ComplexType>();
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001378 if (!ToComplex)
1379 return false;
1380
1381 return IsFloatingPointPromotion(FromComplex->getElementType(),
Douglas Gregor67525022009-02-12 00:26:06 +00001382 ToComplex->getElementType()) ||
1383 IsIntegralPromotion(0, FromComplex->getElementType(),
1384 ToComplex->getElementType());
Douglas Gregor78ca74d2009-02-12 00:15:05 +00001385}
1386
Douglas Gregor237f96c2008-11-26 23:31:11 +00001387/// BuildSimilarlyQualifiedPointerType - In a pointer conversion from
1388/// the pointer type FromPtr to a pointer to type ToPointee, with the
1389/// same type qualifiers as FromPtr has on its pointee type. ToType,
1390/// if non-empty, will be a pointer to ToType that may or may not have
1391/// the right set of qualifiers on its pointee.
Mike Stump11289f42009-09-09 15:08:12 +00001392static QualType
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001393BuildSimilarlyQualifiedPointerType(const Type *FromPtr,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001394 QualType ToPointee, QualType ToType,
1395 ASTContext &Context) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001396 assert((FromPtr->getTypeClass() == Type::Pointer ||
1397 FromPtr->getTypeClass() == Type::ObjCObjectPointer) &&
1398 "Invalid similarly-qualified pointer type");
Douglas Gregorc6bd1d32010-12-06 22:09:19 +00001399
1400 /// \brief Conversions to 'id' subsume cv-qualifier conversions.
1401 if (ToType->isObjCIdType() || ToType->isObjCQualifiedIdType())
1402 return ToType.getUnqualifiedType();
1403
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001404 QualType CanonFromPointee
1405 = Context.getCanonicalType(FromPtr->getPointeeType());
Douglas Gregor237f96c2008-11-26 23:31:11 +00001406 QualType CanonToPointee = Context.getCanonicalType(ToPointee);
John McCall8ccfcb52009-09-24 19:53:00 +00001407 Qualifiers Quals = CanonFromPointee.getQualifiers();
Mike Stump11289f42009-09-09 15:08:12 +00001408
1409 // Exact qualifier match -> return the pointer type we're converting to.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00001410 if (CanonToPointee.getLocalQualifiers() == Quals) {
Douglas Gregor237f96c2008-11-26 23:31:11 +00001411 // ToType is exactly what we need. Return it.
John McCall8ccfcb52009-09-24 19:53:00 +00001412 if (!ToType.isNull())
Douglas Gregorb9f907b2010-05-25 15:31:05 +00001413 return ToType.getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001414
1415 // Build a pointer to ToPointee. It has the right qualifiers
1416 // already.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001417 if (isa<ObjCObjectPointerType>(ToType))
1418 return Context.getObjCObjectPointerType(ToPointee);
Douglas Gregor237f96c2008-11-26 23:31:11 +00001419 return Context.getPointerType(ToPointee);
1420 }
1421
1422 // Just build a canonical type that has the right qualifiers.
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001423 QualType QualifiedCanonToPointee
1424 = Context.getQualifiedType(CanonToPointee.getLocalUnqualifiedType(), Quals);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001425
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001426 if (isa<ObjCObjectPointerType>(ToType))
1427 return Context.getObjCObjectPointerType(QualifiedCanonToPointee);
1428 return Context.getPointerType(QualifiedCanonToPointee);
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001429}
1430
Mike Stump11289f42009-09-09 15:08:12 +00001431static bool isNullPointerConstantForConversion(Expr *Expr,
Anders Carlsson759b7892009-08-28 15:55:56 +00001432 bool InOverloadResolution,
1433 ASTContext &Context) {
1434 // Handle value-dependent integral null pointer constants correctly.
1435 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
1436 if (Expr->isValueDependent() && !Expr->isTypeDependent() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00001437 Expr->getType()->isIntegerType() && !Expr->getType()->isEnumeralType())
Anders Carlsson759b7892009-08-28 15:55:56 +00001438 return !InOverloadResolution;
1439
Douglas Gregor56751b52009-09-25 04:25:58 +00001440 return Expr->isNullPointerConstant(Context,
1441 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1442 : Expr::NPC_ValueDependentIsNull);
Anders Carlsson759b7892009-08-28 15:55:56 +00001443}
Mike Stump11289f42009-09-09 15:08:12 +00001444
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001445/// IsPointerConversion - Determines whether the conversion of the
1446/// expression From, which has the (possibly adjusted) type FromType,
1447/// can be converted to the type ToType via a pointer conversion (C++
1448/// 4.10). If so, returns true and places the converted type (that
1449/// might differ from ToType in its cv-qualifiers at some level) into
1450/// ConvertedType.
Douglas Gregor231d1c62008-11-27 00:15:41 +00001451///
Douglas Gregora29dc052008-11-27 01:19:21 +00001452/// This routine also supports conversions to and from block pointers
1453/// and conversions with Objective-C's 'id', 'id<protocols...>', and
1454/// pointers to interfaces. FIXME: Once we've determined the
1455/// appropriate overloading rules for Objective-C, we may want to
1456/// split the Objective-C checks into a different routine; however,
1457/// GCC seems to consider all of these conversions to be pointer
Douglas Gregor47d3f272008-12-19 17:40:08 +00001458/// conversions, so for now they live here. IncompatibleObjC will be
1459/// set if the conversion is an allowed Objective-C conversion that
1460/// should result in a warning.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001461bool Sema::IsPointerConversion(Expr *From, QualType FromType, QualType ToType,
Anders Carlsson228eea32009-08-28 15:33:32 +00001462 bool InOverloadResolution,
Douglas Gregor47d3f272008-12-19 17:40:08 +00001463 QualType& ConvertedType,
Mike Stump11289f42009-09-09 15:08:12 +00001464 bool &IncompatibleObjC) {
Douglas Gregor47d3f272008-12-19 17:40:08 +00001465 IncompatibleObjC = false;
Chandler Carruth8e543b32010-12-12 08:17:55 +00001466 if (isObjCPointerConversion(FromType, ToType, ConvertedType,
1467 IncompatibleObjC))
Douglas Gregora119f102008-12-19 19:13:09 +00001468 return true;
Douglas Gregor47d3f272008-12-19 17:40:08 +00001469
Mike Stump11289f42009-09-09 15:08:12 +00001470 // Conversion from a null pointer constant to any Objective-C pointer type.
1471 if (ToType->isObjCObjectPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001472 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor79a6b012008-12-22 20:51:52 +00001473 ConvertedType = ToType;
1474 return true;
1475 }
1476
Douglas Gregor231d1c62008-11-27 00:15:41 +00001477 // Blocks: Block pointers can be converted to void*.
1478 if (FromType->isBlockPointerType() && ToType->isPointerType() &&
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001479 ToType->getAs<PointerType>()->getPointeeType()->isVoidType()) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001480 ConvertedType = ToType;
1481 return true;
1482 }
1483 // Blocks: A null pointer constant can be converted to a block
1484 // pointer type.
Mike Stump11289f42009-09-09 15:08:12 +00001485 if (ToType->isBlockPointerType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001486 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor231d1c62008-11-27 00:15:41 +00001487 ConvertedType = ToType;
1488 return true;
1489 }
1490
Sebastian Redl576fd422009-05-10 18:38:11 +00001491 // If the left-hand-side is nullptr_t, the right side can be a null
1492 // pointer constant.
Mike Stump11289f42009-09-09 15:08:12 +00001493 if (ToType->isNullPtrType() &&
Anders Carlsson759b7892009-08-28 15:55:56 +00001494 isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Sebastian Redl576fd422009-05-10 18:38:11 +00001495 ConvertedType = ToType;
1496 return true;
1497 }
1498
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001499 const PointerType* ToTypePtr = ToType->getAs<PointerType>();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001500 if (!ToTypePtr)
1501 return false;
1502
1503 // A null pointer constant can be converted to a pointer type (C++ 4.10p1).
Anders Carlsson759b7892009-08-28 15:55:56 +00001504 if (isNullPointerConstantForConversion(From, InOverloadResolution, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001505 ConvertedType = ToType;
1506 return true;
1507 }
Sebastian Redl72b8aef2008-10-31 14:43:28 +00001508
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001509 // Beyond this point, both types need to be pointers
1510 // , including objective-c pointers.
1511 QualType ToPointeeType = ToTypePtr->getPointeeType();
1512 if (FromType->isObjCObjectPointerType() && ToPointeeType->isVoidType()) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001513 ConvertedType = BuildSimilarlyQualifiedPointerType(
1514 FromType->getAs<ObjCObjectPointerType>(),
1515 ToPointeeType,
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001516 ToType, Context);
1517 return true;
Fariborz Jahanian01cbe442009-12-16 23:13:33 +00001518 }
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001519 const PointerType *FromTypePtr = FromType->getAs<PointerType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001520 if (!FromTypePtr)
1521 return false;
1522
1523 QualType FromPointeeType = FromTypePtr->getPointeeType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00001524
Douglas Gregorfb640862010-08-18 21:25:30 +00001525 // If the unqualified pointee types are the same, this can't be a
1526 // pointer conversion, so don't do all of the work below.
1527 if (Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType))
1528 return false;
1529
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001530 // An rvalue of type "pointer to cv T," where T is an object type,
1531 // can be converted to an rvalue of type "pointer to cv void" (C++
1532 // 4.10p2).
Eli Friedmana170cd62010-08-05 02:49:48 +00001533 if (FromPointeeType->isIncompleteOrObjectType() &&
1534 ToPointeeType->isVoidType()) {
Mike Stump11289f42009-09-09 15:08:12 +00001535 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001536 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001537 ToType, Context);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001538 return true;
1539 }
1540
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001541 // When we're overloading in C, we allow a special kind of pointer
1542 // conversion for compatible-but-not-identical pointee types.
Mike Stump11289f42009-09-09 15:08:12 +00001543 if (!getLangOptions().CPlusPlus &&
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001544 Context.typesAreCompatible(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001545 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001546 ToPointeeType,
Mike Stump11289f42009-09-09 15:08:12 +00001547 ToType, Context);
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001548 return true;
1549 }
1550
Douglas Gregor5c407d92008-10-23 00:40:37 +00001551 // C++ [conv.ptr]p3:
Mike Stump11289f42009-09-09 15:08:12 +00001552 //
Douglas Gregor5c407d92008-10-23 00:40:37 +00001553 // An rvalue of type "pointer to cv D," where D is a class type,
1554 // can be converted to an rvalue of type "pointer to cv B," where
1555 // B is a base class (clause 10) of D. If B is an inaccessible
1556 // (clause 11) or ambiguous (10.2) base class of D, a program that
1557 // necessitates this conversion is ill-formed. The result of the
1558 // conversion is a pointer to the base class sub-object of the
1559 // derived class object. The null pointer value is converted to
1560 // the null pointer value of the destination type.
1561 //
Douglas Gregor39c16d42008-10-24 04:54:22 +00001562 // Note that we do not check for ambiguity or inaccessibility
1563 // here. That is handled by CheckPointerConversion.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001564 if (getLangOptions().CPlusPlus &&
1565 FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
Douglas Gregord28f0412010-02-22 17:06:41 +00001566 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType) &&
Douglas Gregore6fb91f2009-10-29 23:08:22 +00001567 !RequireCompleteType(From->getLocStart(), FromPointeeType, PDiag()) &&
Douglas Gregor237f96c2008-11-26 23:31:11 +00001568 IsDerivedFrom(FromPointeeType, ToPointeeType)) {
Mike Stump11289f42009-09-09 15:08:12 +00001569 ConvertedType = BuildSimilarlyQualifiedPointerType(FromTypePtr,
Douglas Gregorbb9bf882008-11-27 00:52:49 +00001570 ToPointeeType,
Douglas Gregor237f96c2008-11-26 23:31:11 +00001571 ToType, Context);
1572 return true;
1573 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00001574
Douglas Gregora119f102008-12-19 19:13:09 +00001575 return false;
1576}
1577
1578/// isObjCPointerConversion - Determines whether this is an
1579/// Objective-C pointer conversion. Subroutine of IsPointerConversion,
1580/// with the same arguments and return values.
Mike Stump11289f42009-09-09 15:08:12 +00001581bool Sema::isObjCPointerConversion(QualType FromType, QualType ToType,
Douglas Gregora119f102008-12-19 19:13:09 +00001582 QualType& ConvertedType,
1583 bool &IncompatibleObjC) {
1584 if (!getLangOptions().ObjC1)
1585 return false;
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001586
Steve Naroff7cae42b2009-07-10 23:34:53 +00001587 // First, we handle all conversions on ObjC object pointer types.
Chandler Carruth8e543b32010-12-12 08:17:55 +00001588 const ObjCObjectPointerType* ToObjCPtr =
1589 ToType->getAs<ObjCObjectPointerType>();
Mike Stump11289f42009-09-09 15:08:12 +00001590 const ObjCObjectPointerType *FromObjCPtr =
John McCall9dd450b2009-09-21 23:43:11 +00001591 FromType->getAs<ObjCObjectPointerType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001592
Steve Naroff7cae42b2009-07-10 23:34:53 +00001593 if (ToObjCPtr && FromObjCPtr) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001594 // If the pointee types are the same (ignoring qualifications),
1595 // then this is not a pointer conversion.
1596 if (Context.hasSameUnqualifiedType(ToObjCPtr->getPointeeType(),
1597 FromObjCPtr->getPointeeType()))
1598 return false;
1599
Steve Naroff1329fa02009-07-15 18:40:39 +00001600 // Objective C++: We're able to convert between "id" or "Class" and a
Steve Naroff7cae42b2009-07-10 23:34:53 +00001601 // pointer to any interface (in both directions).
Steve Naroff1329fa02009-07-15 18:40:39 +00001602 if (ToObjCPtr->isObjCBuiltinType() && FromObjCPtr->isObjCBuiltinType()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001603 ConvertedType = ToType;
1604 return true;
1605 }
1606 // Conversions with Objective-C's id<...>.
Mike Stump11289f42009-09-09 15:08:12 +00001607 if ((FromObjCPtr->isObjCQualifiedIdType() ||
Steve Naroff7cae42b2009-07-10 23:34:53 +00001608 ToObjCPtr->isObjCQualifiedIdType()) &&
Mike Stump11289f42009-09-09 15:08:12 +00001609 Context.ObjCQualifiedIdTypesAreCompatible(ToType, FromType,
Steve Naroff8e6aee52009-07-23 01:01:38 +00001610 /*compare=*/false)) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001611 ConvertedType = ToType;
1612 return true;
1613 }
1614 // Objective C++: We're able to convert from a pointer to an
1615 // interface to a pointer to a different interface.
1616 if (Context.canAssignObjCInterfaces(ToObjCPtr, FromObjCPtr)) {
Fariborz Jahanianb397e432010-03-15 18:36:00 +00001617 const ObjCInterfaceType* LHS = ToObjCPtr->getInterfaceType();
1618 const ObjCInterfaceType* RHS = FromObjCPtr->getInterfaceType();
1619 if (getLangOptions().CPlusPlus && LHS && RHS &&
1620 !ToObjCPtr->getPointeeType().isAtLeastAsQualifiedAs(
1621 FromObjCPtr->getPointeeType()))
1622 return false;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001623 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1624 ToObjCPtr->getPointeeType(),
1625 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001626 return true;
1627 }
1628
1629 if (Context.canAssignObjCInterfaces(FromObjCPtr, ToObjCPtr)) {
1630 // Okay: this is some kind of implicit downcast of Objective-C
1631 // interfaces, which is permitted. However, we're going to
1632 // complain about it.
1633 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001634 ConvertedType = BuildSimilarlyQualifiedPointerType(FromObjCPtr,
1635 ToObjCPtr->getPointeeType(),
1636 ToType, Context);
Steve Naroff7cae42b2009-07-10 23:34:53 +00001637 return true;
1638 }
Mike Stump11289f42009-09-09 15:08:12 +00001639 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001640 // Beyond this point, both types need to be C pointers or block pointers.
Douglas Gregor033f56d2008-12-23 00:53:59 +00001641 QualType ToPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001642 if (const PointerType *ToCPtr = ToType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001643 ToPointeeType = ToCPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001644 else if (const BlockPointerType *ToBlockPtr =
1645 ToType->getAs<BlockPointerType>()) {
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001646 // Objective C++: We're able to convert from a pointer to any object
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001647 // to a block pointer type.
1648 if (FromObjCPtr && FromObjCPtr->isObjCBuiltinType()) {
1649 ConvertedType = ToType;
1650 return true;
1651 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001652 ToPointeeType = ToBlockPtr->getPointeeType();
Fariborz Jahanian4efdec02010-01-20 22:54:38 +00001653 }
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001654 else if (FromType->getAs<BlockPointerType>() &&
1655 ToObjCPtr && ToObjCPtr->isObjCBuiltinType()) {
1656 // Objective C++: We're able to convert from a block pointer type to a
Fariborz Jahanian879cc732010-01-21 00:08:17 +00001657 // pointer to any object.
Fariborz Jahaniane4951fd2010-01-21 00:05:09 +00001658 ConvertedType = ToType;
1659 return true;
1660 }
Douglas Gregor033f56d2008-12-23 00:53:59 +00001661 else
Douglas Gregora119f102008-12-19 19:13:09 +00001662 return false;
1663
Douglas Gregor033f56d2008-12-23 00:53:59 +00001664 QualType FromPointeeType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001665 if (const PointerType *FromCPtr = FromType->getAs<PointerType>())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001666 FromPointeeType = FromCPtr->getPointeeType();
Chandler Carruth8e543b32010-12-12 08:17:55 +00001667 else if (const BlockPointerType *FromBlockPtr =
1668 FromType->getAs<BlockPointerType>())
Douglas Gregor033f56d2008-12-23 00:53:59 +00001669 FromPointeeType = FromBlockPtr->getPointeeType();
1670 else
Douglas Gregora119f102008-12-19 19:13:09 +00001671 return false;
1672
Douglas Gregora119f102008-12-19 19:13:09 +00001673 // If we have pointers to pointers, recursively check whether this
1674 // is an Objective-C conversion.
1675 if (FromPointeeType->isPointerType() && ToPointeeType->isPointerType() &&
1676 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1677 IncompatibleObjC)) {
1678 // We always complain about this conversion.
1679 IncompatibleObjC = true;
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001680 ConvertedType = Context.getPointerType(ConvertedType);
Douglas Gregora119f102008-12-19 19:13:09 +00001681 return true;
1682 }
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001683 // Allow conversion of pointee being objective-c pointer to another one;
1684 // as in I* to id.
1685 if (FromPointeeType->getAs<ObjCObjectPointerType>() &&
1686 ToPointeeType->getAs<ObjCObjectPointerType>() &&
1687 isObjCPointerConversion(FromPointeeType, ToPointeeType, ConvertedType,
1688 IncompatibleObjC)) {
Douglas Gregor8d6d0672010-12-01 21:43:58 +00001689 ConvertedType = Context.getPointerType(ConvertedType);
Fariborz Jahanian42ffdb32010-01-18 22:59:22 +00001690 return true;
1691 }
1692
Douglas Gregor033f56d2008-12-23 00:53:59 +00001693 // If we have pointers to functions or blocks, check whether the only
Douglas Gregora119f102008-12-19 19:13:09 +00001694 // differences in the argument and result types are in Objective-C
1695 // pointer conversions. If so, we permit the conversion (but
1696 // complain about it).
Mike Stump11289f42009-09-09 15:08:12 +00001697 const FunctionProtoType *FromFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001698 = FromPointeeType->getAs<FunctionProtoType>();
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001699 const FunctionProtoType *ToFunctionType
John McCall9dd450b2009-09-21 23:43:11 +00001700 = ToPointeeType->getAs<FunctionProtoType>();
Douglas Gregora119f102008-12-19 19:13:09 +00001701 if (FromFunctionType && ToFunctionType) {
1702 // If the function types are exactly the same, this isn't an
1703 // Objective-C pointer conversion.
1704 if (Context.getCanonicalType(FromPointeeType)
1705 == Context.getCanonicalType(ToPointeeType))
1706 return false;
1707
1708 // Perform the quick checks that will tell us whether these
1709 // function types are obviously different.
1710 if (FromFunctionType->getNumArgs() != ToFunctionType->getNumArgs() ||
1711 FromFunctionType->isVariadic() != ToFunctionType->isVariadic() ||
1712 FromFunctionType->getTypeQuals() != ToFunctionType->getTypeQuals())
1713 return false;
1714
1715 bool HasObjCConversion = false;
1716 if (Context.getCanonicalType(FromFunctionType->getResultType())
1717 == Context.getCanonicalType(ToFunctionType->getResultType())) {
1718 // Okay, the types match exactly. Nothing to do.
1719 } else if (isObjCPointerConversion(FromFunctionType->getResultType(),
1720 ToFunctionType->getResultType(),
1721 ConvertedType, IncompatibleObjC)) {
1722 // Okay, we have an Objective-C pointer conversion.
1723 HasObjCConversion = true;
1724 } else {
1725 // Function types are too different. Abort.
1726 return false;
1727 }
Mike Stump11289f42009-09-09 15:08:12 +00001728
Douglas Gregora119f102008-12-19 19:13:09 +00001729 // Check argument types.
1730 for (unsigned ArgIdx = 0, NumArgs = FromFunctionType->getNumArgs();
1731 ArgIdx != NumArgs; ++ArgIdx) {
1732 QualType FromArgType = FromFunctionType->getArgType(ArgIdx);
1733 QualType ToArgType = ToFunctionType->getArgType(ArgIdx);
1734 if (Context.getCanonicalType(FromArgType)
1735 == Context.getCanonicalType(ToArgType)) {
1736 // Okay, the types match exactly. Nothing to do.
1737 } else if (isObjCPointerConversion(FromArgType, ToArgType,
1738 ConvertedType, IncompatibleObjC)) {
1739 // Okay, we have an Objective-C pointer conversion.
1740 HasObjCConversion = true;
1741 } else {
1742 // Argument types are too different. Abort.
1743 return false;
1744 }
1745 }
1746
1747 if (HasObjCConversion) {
1748 // We had an Objective-C conversion. Allow this pointer
1749 // conversion, but complain about it.
1750 ConvertedType = ToType;
1751 IncompatibleObjC = true;
1752 return true;
1753 }
1754 }
1755
Sebastian Redl72b597d2009-01-25 19:43:20 +00001756 return false;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001757}
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001758
1759/// FunctionArgTypesAreEqual - This routine checks two function proto types
1760/// for equlity of their argument types. Caller has already checked that
1761/// they have same number of arguments. This routine assumes that Objective-C
1762/// pointer types which only differ in their protocol qualifiers are equal.
John McCall424cec92011-01-19 06:33:43 +00001763bool Sema::FunctionArgTypesAreEqual(const FunctionProtoType *OldType,
1764 const FunctionProtoType *NewType) {
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001765 if (!getLangOptions().ObjC1)
1766 return std::equal(OldType->arg_type_begin(), OldType->arg_type_end(),
1767 NewType->arg_type_begin());
1768
1769 for (FunctionProtoType::arg_type_iterator O = OldType->arg_type_begin(),
1770 N = NewType->arg_type_begin(),
1771 E = OldType->arg_type_end(); O && (O != E); ++O, ++N) {
1772 QualType ToType = (*O);
1773 QualType FromType = (*N);
1774 if (ToType != FromType) {
1775 if (const PointerType *PTTo = ToType->getAs<PointerType>()) {
1776 if (const PointerType *PTFr = FromType->getAs<PointerType>())
Chandler Carruth27c9fe92010-05-06 00:15:06 +00001777 if ((PTTo->getPointeeType()->isObjCQualifiedIdType() &&
1778 PTFr->getPointeeType()->isObjCQualifiedIdType()) ||
1779 (PTTo->getPointeeType()->isObjCQualifiedClassType() &&
1780 PTFr->getPointeeType()->isObjCQualifiedClassType()))
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001781 continue;
1782 }
John McCall8b07ec22010-05-15 11:32:37 +00001783 else if (const ObjCObjectPointerType *PTTo =
1784 ToType->getAs<ObjCObjectPointerType>()) {
1785 if (const ObjCObjectPointerType *PTFr =
1786 FromType->getAs<ObjCObjectPointerType>())
1787 if (PTTo->getInterfaceDecl() == PTFr->getInterfaceDecl())
1788 continue;
Fariborz Jahanian5e5998f2010-05-03 21:06:18 +00001789 }
1790 return false;
1791 }
1792 }
1793 return true;
1794}
Douglas Gregor5251f1b2008-10-21 16:13:35 +00001795
Douglas Gregor39c16d42008-10-24 04:54:22 +00001796/// CheckPointerConversion - Check the pointer conversion from the
1797/// expression From to the type ToType. This routine checks for
Sebastian Redl9f831db2009-07-25 15:41:38 +00001798/// ambiguous or inaccessible derived-to-base pointer
Douglas Gregor39c16d42008-10-24 04:54:22 +00001799/// conversions for which IsPointerConversion has already returned
1800/// true. It returns true and produces a diagnostic if there was an
1801/// error, or returns false otherwise.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001802bool Sema::CheckPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001803 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001804 CXXCastPath& BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001805 bool IgnoreBaseAccess) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001806 QualType FromType = From->getType();
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001807 bool IsCStyleOrFunctionalCast = IgnoreBaseAccess;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001808
John McCall8cb679e2010-11-15 09:13:47 +00001809 Kind = CK_BitCast;
1810
Douglas Gregor4038cf42010-06-08 17:35:15 +00001811 if (CXXBoolLiteralExpr* LitBool
1812 = dyn_cast<CXXBoolLiteralExpr>(From->IgnoreParens()))
Argyrios Kyrtzidisd6ea6bd2010-09-28 14:54:11 +00001813 if (!IsCStyleOrFunctionalCast && LitBool->getValue() == false)
Douglas Gregor4038cf42010-06-08 17:35:15 +00001814 Diag(LitBool->getExprLoc(), diag::warn_init_pointer_from_false)
1815 << ToType;
1816
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001817 if (const PointerType *FromPtrType = FromType->getAs<PointerType>())
1818 if (const PointerType *ToPtrType = ToType->getAs<PointerType>()) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001819 QualType FromPointeeType = FromPtrType->getPointeeType(),
1820 ToPointeeType = ToPtrType->getPointeeType();
Douglas Gregor1e57a3f2008-12-18 23:43:31 +00001821
Douglas Gregorcc3f3252010-03-03 23:55:11 +00001822 if (FromPointeeType->isRecordType() && ToPointeeType->isRecordType() &&
1823 !Context.hasSameUnqualifiedType(FromPointeeType, ToPointeeType)) {
Douglas Gregor39c16d42008-10-24 04:54:22 +00001824 // We must have a derived-to-base conversion. Check an
1825 // ambiguous or inaccessible conversion.
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001826 if (CheckDerivedToBaseConversion(FromPointeeType, ToPointeeType,
1827 From->getExprLoc(),
Anders Carlssona70cff62010-04-24 19:06:50 +00001828 From->getSourceRange(), &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001829 IgnoreBaseAccess))
Anders Carlsson7ec8ccd2009-09-12 04:46:44 +00001830 return true;
1831
1832 // The conversion was successful.
John McCalle3027922010-08-25 11:45:40 +00001833 Kind = CK_DerivedToBase;
Douglas Gregor39c16d42008-10-24 04:54:22 +00001834 }
1835 }
Mike Stump11289f42009-09-09 15:08:12 +00001836 if (const ObjCObjectPointerType *FromPtrType =
John McCall8cb679e2010-11-15 09:13:47 +00001837 FromType->getAs<ObjCObjectPointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00001838 if (const ObjCObjectPointerType *ToPtrType =
John McCall9dd450b2009-09-21 23:43:11 +00001839 ToType->getAs<ObjCObjectPointerType>()) {
Steve Naroff7cae42b2009-07-10 23:34:53 +00001840 // Objective-C++ conversions are always okay.
1841 // FIXME: We should have a different class of conversions for the
1842 // Objective-C++ implicit conversions.
Steve Naroff1329fa02009-07-15 18:40:39 +00001843 if (FromPtrType->isObjCBuiltinType() || ToPtrType->isObjCBuiltinType())
Steve Naroff7cae42b2009-07-10 23:34:53 +00001844 return false;
John McCall8cb679e2010-11-15 09:13:47 +00001845 }
Steve Naroff7cae42b2009-07-10 23:34:53 +00001846 }
John McCall8cb679e2010-11-15 09:13:47 +00001847
1848 // We shouldn't fall into this case unless it's valid for other
1849 // reasons.
1850 if (From->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
1851 Kind = CK_NullToPointer;
1852
Douglas Gregor39c16d42008-10-24 04:54:22 +00001853 return false;
1854}
1855
Sebastian Redl72b597d2009-01-25 19:43:20 +00001856/// IsMemberPointerConversion - Determines whether the conversion of the
1857/// expression From, which has the (possibly adjusted) type FromType, can be
1858/// converted to the type ToType via a member pointer conversion (C++ 4.11).
1859/// If so, returns true and places the converted type (that might differ from
1860/// ToType in its cv-qualifiers at some level) into ConvertedType.
1861bool Sema::IsMemberPointerConversion(Expr *From, QualType FromType,
Douglas Gregor56751b52009-09-25 04:25:58 +00001862 QualType ToType,
1863 bool InOverloadResolution,
1864 QualType &ConvertedType) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001865 const MemberPointerType *ToTypePtr = ToType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001866 if (!ToTypePtr)
1867 return false;
1868
1869 // A null pointer constant can be converted to a member pointer (C++ 4.11p1)
Douglas Gregor56751b52009-09-25 04:25:58 +00001870 if (From->isNullPointerConstant(Context,
1871 InOverloadResolution? Expr::NPC_ValueDependentIsNotNull
1872 : Expr::NPC_ValueDependentIsNull)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001873 ConvertedType = ToType;
1874 return true;
1875 }
1876
1877 // Otherwise, both types have to be member pointers.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001878 const MemberPointerType *FromTypePtr = FromType->getAs<MemberPointerType>();
Sebastian Redl72b597d2009-01-25 19:43:20 +00001879 if (!FromTypePtr)
1880 return false;
1881
1882 // A pointer to member of B can be converted to a pointer to member of D,
1883 // where D is derived from B (C++ 4.11p2).
1884 QualType FromClass(FromTypePtr->getClass(), 0);
1885 QualType ToClass(ToTypePtr->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001886
Douglas Gregor7f6ae692010-12-21 21:40:41 +00001887 if (!Context.hasSameUnqualifiedType(FromClass, ToClass) &&
1888 !RequireCompleteType(From->getLocStart(), ToClass, PDiag()) &&
1889 IsDerivedFrom(ToClass, FromClass)) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001890 ConvertedType = Context.getMemberPointerType(FromTypePtr->getPointeeType(),
1891 ToClass.getTypePtr());
1892 return true;
1893 }
1894
1895 return false;
1896}
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00001897
Sebastian Redl72b597d2009-01-25 19:43:20 +00001898/// CheckMemberPointerConversion - Check the member pointer conversion from the
1899/// expression From to the type ToType. This routine checks for ambiguous or
John McCall5b0829a2010-02-10 09:31:12 +00001900/// virtual or inaccessible base-to-derived member pointer conversions
Sebastian Redl72b597d2009-01-25 19:43:20 +00001901/// for which IsMemberPointerConversion has already returned true. It returns
1902/// true and produces a diagnostic if there was an error, or returns false
1903/// otherwise.
Mike Stump11289f42009-09-09 15:08:12 +00001904bool Sema::CheckMemberPointerConversion(Expr *From, QualType ToType,
John McCalle3027922010-08-25 11:45:40 +00001905 CastKind &Kind,
John McCallcf142162010-08-07 06:22:56 +00001906 CXXCastPath &BasePath,
Sebastian Redl7c353682009-11-14 21:15:49 +00001907 bool IgnoreBaseAccess) {
Sebastian Redl72b597d2009-01-25 19:43:20 +00001908 QualType FromType = From->getType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001909 const MemberPointerType *FromPtrType = FromType->getAs<MemberPointerType>();
Anders Carlssond7923c62009-08-22 23:33:40 +00001910 if (!FromPtrType) {
1911 // This must be a null pointer to member pointer conversion
Douglas Gregor56751b52009-09-25 04:25:58 +00001912 assert(From->isNullPointerConstant(Context,
1913 Expr::NPC_ValueDependentIsNull) &&
Anders Carlssond7923c62009-08-22 23:33:40 +00001914 "Expr must be null pointer constant!");
John McCalle3027922010-08-25 11:45:40 +00001915 Kind = CK_NullToMemberPointer;
Sebastian Redled8f2002009-01-28 18:33:18 +00001916 return false;
Anders Carlssond7923c62009-08-22 23:33:40 +00001917 }
Sebastian Redl72b597d2009-01-25 19:43:20 +00001918
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001919 const MemberPointerType *ToPtrType = ToType->getAs<MemberPointerType>();
Sebastian Redled8f2002009-01-28 18:33:18 +00001920 assert(ToPtrType && "No member pointer cast has a target type "
1921 "that is not a member pointer.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001922
Sebastian Redled8f2002009-01-28 18:33:18 +00001923 QualType FromClass = QualType(FromPtrType->getClass(), 0);
1924 QualType ToClass = QualType(ToPtrType->getClass(), 0);
Sebastian Redl72b597d2009-01-25 19:43:20 +00001925
Sebastian Redled8f2002009-01-28 18:33:18 +00001926 // FIXME: What about dependent types?
1927 assert(FromClass->isRecordType() && "Pointer into non-class.");
1928 assert(ToClass->isRecordType() && "Pointer into non-class.");
Sebastian Redl72b597d2009-01-25 19:43:20 +00001929
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001930 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
Douglas Gregor36d1b142009-10-06 17:59:45 +00001931 /*DetectVirtual=*/true);
Sebastian Redled8f2002009-01-28 18:33:18 +00001932 bool DerivationOkay = IsDerivedFrom(ToClass, FromClass, Paths);
1933 assert(DerivationOkay &&
1934 "Should not have been called if derivation isn't OK.");
1935 (void)DerivationOkay;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001936
Sebastian Redled8f2002009-01-28 18:33:18 +00001937 if (Paths.isAmbiguous(Context.getCanonicalType(FromClass).
1938 getUnqualifiedType())) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001939 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
1940 Diag(From->getExprLoc(), diag::err_ambiguous_memptr_conv)
1941 << 0 << FromClass << ToClass << PathDisplayStr << From->getSourceRange();
1942 return true;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001943 }
Sebastian Redled8f2002009-01-28 18:33:18 +00001944
Douglas Gregor89ee6822009-02-28 01:32:25 +00001945 if (const RecordType *VBase = Paths.getDetectedVirtual()) {
Sebastian Redled8f2002009-01-28 18:33:18 +00001946 Diag(From->getExprLoc(), diag::err_memptr_conv_via_virtual)
1947 << FromClass << ToClass << QualType(VBase, 0)
1948 << From->getSourceRange();
1949 return true;
1950 }
1951
John McCall5b0829a2010-02-10 09:31:12 +00001952 if (!IgnoreBaseAccess)
John McCall1064d7e2010-03-16 05:22:47 +00001953 CheckBaseClassAccess(From->getExprLoc(), FromClass, ToClass,
1954 Paths.front(),
1955 diag::err_downcast_from_inaccessible_base);
John McCall5b0829a2010-02-10 09:31:12 +00001956
Anders Carlssond7923c62009-08-22 23:33:40 +00001957 // Must be a base to derived member conversion.
Anders Carlsson7d3360f2010-04-24 19:36:51 +00001958 BuildBasePathArray(Paths, BasePath);
John McCalle3027922010-08-25 11:45:40 +00001959 Kind = CK_BaseToDerivedMemberPointer;
Sebastian Redl72b597d2009-01-25 19:43:20 +00001960 return false;
1961}
1962
Douglas Gregor9a657932008-10-21 23:43:52 +00001963/// IsQualificationConversion - Determines whether the conversion from
1964/// an rvalue of type FromType to ToType is a qualification conversion
1965/// (C++ 4.4).
Mike Stump11289f42009-09-09 15:08:12 +00001966bool
1967Sema::IsQualificationConversion(QualType FromType, QualType ToType) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001968 FromType = Context.getCanonicalType(FromType);
1969 ToType = Context.getCanonicalType(ToType);
1970
1971 // If FromType and ToType are the same type, this is not a
1972 // qualification conversion.
Sebastian Redlcbdffb12010-02-03 19:36:07 +00001973 if (FromType.getUnqualifiedType() == ToType.getUnqualifiedType())
Douglas Gregor9a657932008-10-21 23:43:52 +00001974 return false;
Sebastian Redled8f2002009-01-28 18:33:18 +00001975
Douglas Gregor9a657932008-10-21 23:43:52 +00001976 // (C++ 4.4p4):
1977 // A conversion can add cv-qualifiers at levels other than the first
1978 // in multi-level pointers, subject to the following rules: [...]
1979 bool PreviousToQualsIncludeConst = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001980 bool UnwrappedAnyPointer = false;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00001981 while (Context.UnwrapSimilarPointerTypes(FromType, ToType)) {
Douglas Gregor9a657932008-10-21 23:43:52 +00001982 // Within each iteration of the loop, we check the qualifiers to
1983 // determine if this still looks like a qualification
1984 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00001985 // pointers or pointers-to-members and do it all again
Douglas Gregor9a657932008-10-21 23:43:52 +00001986 // until there are no more pointers or pointers-to-members left to
1987 // unwrap.
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001988 UnwrappedAnyPointer = true;
Douglas Gregor9a657932008-10-21 23:43:52 +00001989
1990 // -- for every j > 0, if const is in cv 1,j then const is in cv
1991 // 2,j, and similarly for volatile.
Douglas Gregorea2d4212008-10-22 00:38:21 +00001992 if (!ToType.isAtLeastAsQualifiedAs(FromType))
Douglas Gregor9a657932008-10-21 23:43:52 +00001993 return false;
Mike Stump11289f42009-09-09 15:08:12 +00001994
Douglas Gregor9a657932008-10-21 23:43:52 +00001995 // -- if the cv 1,j and cv 2,j are different, then const is in
1996 // every cv for 0 < k < j.
1997 if (FromType.getCVRQualifiers() != ToType.getCVRQualifiers()
Douglas Gregore1eb9d82008-10-22 14:17:15 +00001998 && !PreviousToQualsIncludeConst)
Douglas Gregor9a657932008-10-21 23:43:52 +00001999 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002000
Douglas Gregor9a657932008-10-21 23:43:52 +00002001 // Keep track of whether all prior cv-qualifiers in the "to" type
2002 // include const.
Mike Stump11289f42009-09-09 15:08:12 +00002003 PreviousToQualsIncludeConst
Douglas Gregor9a657932008-10-21 23:43:52 +00002004 = PreviousToQualsIncludeConst && ToType.isConstQualified();
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002005 }
Douglas Gregor9a657932008-10-21 23:43:52 +00002006
2007 // We are left with FromType and ToType being the pointee types
2008 // after unwrapping the original FromType and ToType the same number
2009 // of types. If we unwrapped any pointers, and if FromType and
2010 // ToType have the same unqualified type (since we checked
2011 // qualifiers above), then this is a qualification conversion.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00002012 return UnwrappedAnyPointer && Context.hasSameUnqualifiedType(FromType,ToType);
Douglas Gregor9a657932008-10-21 23:43:52 +00002013}
2014
Douglas Gregor576e98c2009-01-30 23:27:23 +00002015/// Determines whether there is a user-defined conversion sequence
2016/// (C++ [over.ics.user]) that converts expression From to the type
2017/// ToType. If such a conversion exists, User will contain the
2018/// user-defined conversion sequence that performs such a conversion
2019/// and this routine will return true. Otherwise, this routine returns
2020/// false and User is unspecified.
2021///
Douglas Gregor576e98c2009-01-30 23:27:23 +00002022/// \param AllowExplicit true if the conversion should consider C++0x
2023/// "explicit" conversion functions as well as non-explicit conversion
2024/// functions (C++0x [class.conv.fct]p2).
John McCall5c32be02010-08-24 20:38:10 +00002025static OverloadingResult
2026IsUserDefinedConversion(Sema &S, Expr *From, QualType ToType,
2027 UserDefinedConversionSequence& User,
2028 OverloadCandidateSet& CandidateSet,
2029 bool AllowExplicit) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002030 // Whether we will only visit constructors.
2031 bool ConstructorsOnly = false;
2032
2033 // If the type we are conversion to is a class type, enumerate its
2034 // constructors.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002035 if (const RecordType *ToRecordType = ToType->getAs<RecordType>()) {
Douglas Gregor5ab11652010-04-17 22:01:05 +00002036 // C++ [over.match.ctor]p1:
2037 // When objects of class type are direct-initialized (8.5), or
2038 // copy-initialized from an expression of the same or a
2039 // derived class type (8.5), overload resolution selects the
2040 // constructor. [...] For copy-initialization, the candidate
2041 // functions are all the converting constructors (12.3.1) of
2042 // that class. The argument list is the expression-list within
2043 // the parentheses of the initializer.
John McCall5c32be02010-08-24 20:38:10 +00002044 if (S.Context.hasSameUnqualifiedType(ToType, From->getType()) ||
Douglas Gregor5ab11652010-04-17 22:01:05 +00002045 (From->getType()->getAs<RecordType>() &&
John McCall5c32be02010-08-24 20:38:10 +00002046 S.IsDerivedFrom(From->getType(), ToType)))
Douglas Gregor5ab11652010-04-17 22:01:05 +00002047 ConstructorsOnly = true;
2048
John McCall5c32be02010-08-24 20:38:10 +00002049 if (S.RequireCompleteType(From->getLocStart(), ToType, S.PDiag())) {
Douglas Gregor3ec1bf22009-11-05 13:06:35 +00002050 // We're not going to find any constructors.
2051 } else if (CXXRecordDecl *ToRecordDecl
2052 = dyn_cast<CXXRecordDecl>(ToRecordType->getDecl())) {
Douglas Gregor89ee6822009-02-28 01:32:25 +00002053 DeclContext::lookup_iterator Con, ConEnd;
John McCall5c32be02010-08-24 20:38:10 +00002054 for (llvm::tie(Con, ConEnd) = S.LookupConstructors(ToRecordDecl);
Douglas Gregor89ee6822009-02-28 01:32:25 +00002055 Con != ConEnd; ++Con) {
John McCalla0296f72010-03-19 07:35:19 +00002056 NamedDecl *D = *Con;
2057 DeclAccessPair FoundDecl = DeclAccessPair::make(D, D->getAccess());
2058
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002059 // Find the constructor (which may be a template).
2060 CXXConstructorDecl *Constructor = 0;
2061 FunctionTemplateDecl *ConstructorTmpl
John McCalla0296f72010-03-19 07:35:19 +00002062 = dyn_cast<FunctionTemplateDecl>(D);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002063 if (ConstructorTmpl)
Mike Stump11289f42009-09-09 15:08:12 +00002064 Constructor
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002065 = cast<CXXConstructorDecl>(ConstructorTmpl->getTemplatedDecl());
2066 else
John McCalla0296f72010-03-19 07:35:19 +00002067 Constructor = cast<CXXConstructorDecl>(D);
Douglas Gregorffe14e32009-11-14 01:20:54 +00002068
Fariborz Jahanian11a8e952009-08-06 17:22:51 +00002069 if (!Constructor->isInvalidDecl() &&
Anders Carlssond20e7952009-08-28 16:57:08 +00002070 Constructor->isConvertingConstructor(AllowExplicit)) {
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002071 if (ConstructorTmpl)
John McCall5c32be02010-08-24 20:38:10 +00002072 S.AddTemplateOverloadCandidate(ConstructorTmpl, FoundDecl,
2073 /*ExplicitArgs*/ 0,
2074 &From, 1, CandidateSet,
2075 /*SuppressUserConversions=*/
2076 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002077 else
Fariborz Jahanianb3c44f92009-10-01 20:39:51 +00002078 // Allow one user-defined conversion when user specifies a
2079 // From->ToType conversion via an static cast (c-style, etc).
John McCall5c32be02010-08-24 20:38:10 +00002080 S.AddOverloadCandidate(Constructor, FoundDecl,
2081 &From, 1, CandidateSet,
2082 /*SuppressUserConversions=*/
2083 !ConstructorsOnly);
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00002084 }
Douglas Gregor89ee6822009-02-28 01:32:25 +00002085 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002086 }
2087 }
2088
Douglas Gregor5ab11652010-04-17 22:01:05 +00002089 // Enumerate conversion functions, if we're allowed to.
2090 if (ConstructorsOnly) {
John McCall5c32be02010-08-24 20:38:10 +00002091 } else if (S.RequireCompleteType(From->getLocStart(), From->getType(),
2092 S.PDiag(0) << From->getSourceRange())) {
Douglas Gregor8a2e6012009-08-24 15:23:48 +00002093 // No conversion functions from incomplete types.
Mike Stump11289f42009-09-09 15:08:12 +00002094 } else if (const RecordType *FromRecordType
Douglas Gregor5ab11652010-04-17 22:01:05 +00002095 = From->getType()->getAs<RecordType>()) {
Mike Stump11289f42009-09-09 15:08:12 +00002096 if (CXXRecordDecl *FromRecordDecl
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002097 = dyn_cast<CXXRecordDecl>(FromRecordType->getDecl())) {
2098 // Add all of the conversion functions as candidates.
John McCallad371252010-01-20 00:46:10 +00002099 const UnresolvedSetImpl *Conversions
Fariborz Jahanianf4061e32009-09-14 20:41:01 +00002100 = FromRecordDecl->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00002101 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00002102 E = Conversions->end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00002103 DeclAccessPair FoundDecl = I.getPair();
2104 NamedDecl *D = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00002105 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
2106 if (isa<UsingShadowDecl>(D))
2107 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2108
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002109 CXXConversionDecl *Conv;
2110 FunctionTemplateDecl *ConvTemplate;
John McCallda4458e2010-03-31 01:36:47 +00002111 if ((ConvTemplate = dyn_cast<FunctionTemplateDecl>(D)))
2112 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002113 else
John McCallda4458e2010-03-31 01:36:47 +00002114 Conv = cast<CXXConversionDecl>(D);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002115
2116 if (AllowExplicit || !Conv->isExplicit()) {
2117 if (ConvTemplate)
John McCall5c32be02010-08-24 20:38:10 +00002118 S.AddTemplateConversionCandidate(ConvTemplate, FoundDecl,
2119 ActingContext, From, ToType,
2120 CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002121 else
John McCall5c32be02010-08-24 20:38:10 +00002122 S.AddConversionCandidate(Conv, FoundDecl, ActingContext,
2123 From, ToType, CandidateSet);
Fariborz Jahanianf9012a32009-09-11 18:46:22 +00002124 }
2125 }
2126 }
Douglas Gregora1f013e2008-11-07 22:36:19 +00002127 }
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002128
2129 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002130 switch (CandidateSet.BestViableFunction(S, From->getLocStart(), Best, true)) {
John McCall5c32be02010-08-24 20:38:10 +00002131 case OR_Success:
2132 // Record the standard conversion we used and the conversion function.
2133 if (CXXConstructorDecl *Constructor
2134 = dyn_cast<CXXConstructorDecl>(Best->Function)) {
2135 // C++ [over.ics.user]p1:
2136 // If the user-defined conversion is specified by a
2137 // constructor (12.3.1), the initial standard conversion
2138 // sequence converts the source type to the type required by
2139 // the argument of the constructor.
2140 //
2141 QualType ThisType = Constructor->getThisType(S.Context);
2142 if (Best->Conversions[0].isEllipsis())
2143 User.EllipsisConversion = true;
2144 else {
Douglas Gregora1f013e2008-11-07 22:36:19 +00002145 User.Before = Best->Conversions[0].Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00002146 User.EllipsisConversion = false;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002147 }
John McCall5c32be02010-08-24 20:38:10 +00002148 User.ConversionFunction = Constructor;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002149 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002150 User.After.setAsIdentityConversion();
2151 User.After.setFromType(ThisType->getAs<PointerType>()->getPointeeType());
2152 User.After.setAllToTypes(ToType);
2153 return OR_Success;
2154 } else if (CXXConversionDecl *Conversion
2155 = dyn_cast<CXXConversionDecl>(Best->Function)) {
2156 // C++ [over.ics.user]p1:
2157 //
2158 // [...] If the user-defined conversion is specified by a
2159 // conversion function (12.3.2), the initial standard
2160 // conversion sequence converts the source type to the
2161 // implicit object parameter of the conversion function.
2162 User.Before = Best->Conversions[0].Standard;
2163 User.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002164 User.FoundConversionFunction = Best->FoundDecl.getDecl();
John McCall5c32be02010-08-24 20:38:10 +00002165 User.EllipsisConversion = false;
Mike Stump11289f42009-09-09 15:08:12 +00002166
John McCall5c32be02010-08-24 20:38:10 +00002167 // C++ [over.ics.user]p2:
2168 // The second standard conversion sequence converts the
2169 // result of the user-defined conversion to the target type
2170 // for the sequence. Since an implicit conversion sequence
2171 // is an initialization, the special rules for
2172 // initialization by user-defined conversion apply when
2173 // selecting the best user-defined conversion for a
2174 // user-defined conversion sequence (see 13.3.3 and
2175 // 13.3.3.1).
2176 User.After = Best->FinalConversion;
2177 return OR_Success;
2178 } else {
2179 llvm_unreachable("Not a constructor or conversion function?");
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002180 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002181 }
2182
John McCall5c32be02010-08-24 20:38:10 +00002183 case OR_No_Viable_Function:
2184 return OR_No_Viable_Function;
2185 case OR_Deleted:
2186 // No conversion here! We're done.
2187 return OR_Deleted;
2188
2189 case OR_Ambiguous:
2190 return OR_Ambiguous;
2191 }
2192
Fariborz Jahanian3e6b57e2009-09-15 19:12:21 +00002193 return OR_No_Viable_Function;
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002194}
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002195
2196bool
Fariborz Jahanian76197412009-11-18 18:26:29 +00002197Sema::DiagnoseMultipleUserDefinedConversion(Expr *From, QualType ToType) {
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002198 ImplicitConversionSequence ICS;
John McCallbc077cf2010-02-08 23:07:23 +00002199 OverloadCandidateSet CandidateSet(From->getExprLoc());
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002200 OverloadingResult OvResult =
John McCall5c32be02010-08-24 20:38:10 +00002201 IsUserDefinedConversion(*this, From, ToType, ICS.UserDefined,
Douglas Gregor5ab11652010-04-17 22:01:05 +00002202 CandidateSet, false);
Fariborz Jahanian76197412009-11-18 18:26:29 +00002203 if (OvResult == OR_Ambiguous)
2204 Diag(From->getSourceRange().getBegin(),
2205 diag::err_typecheck_ambiguous_condition)
2206 << From->getType() << ToType << From->getSourceRange();
2207 else if (OvResult == OR_No_Viable_Function && !CandidateSet.empty())
2208 Diag(From->getSourceRange().getBegin(),
2209 diag::err_typecheck_nonviable_condition)
2210 << From->getType() << ToType << From->getSourceRange();
2211 else
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002212 return false;
John McCall5c32be02010-08-24 20:38:10 +00002213 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &From, 1);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00002214 return true;
2215}
Douglas Gregor26bee0b2008-10-31 16:23:19 +00002216
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002217/// CompareImplicitConversionSequences - Compare two implicit
2218/// conversion sequences to determine whether one is better than the
2219/// other or if they are indistinguishable (C++ 13.3.3.2).
John McCall5c32be02010-08-24 20:38:10 +00002220static ImplicitConversionSequence::CompareKind
2221CompareImplicitConversionSequences(Sema &S,
2222 const ImplicitConversionSequence& ICS1,
2223 const ImplicitConversionSequence& ICS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002224{
2225 // (C++ 13.3.3.2p2): When comparing the basic forms of implicit
2226 // conversion sequences (as defined in 13.3.3.1)
2227 // -- a standard conversion sequence (13.3.3.1.1) is a better
2228 // conversion sequence than a user-defined conversion sequence or
2229 // an ellipsis conversion sequence, and
2230 // -- a user-defined conversion sequence (13.3.3.1.2) is a better
2231 // conversion sequence than an ellipsis conversion sequence
2232 // (13.3.3.1.3).
Mike Stump11289f42009-09-09 15:08:12 +00002233 //
John McCall0d1da222010-01-12 00:44:57 +00002234 // C++0x [over.best.ics]p10:
2235 // For the purpose of ranking implicit conversion sequences as
2236 // described in 13.3.3.2, the ambiguous conversion sequence is
2237 // treated as a user-defined sequence that is indistinguishable
2238 // from any other user-defined conversion sequence.
Douglas Gregor5ab11652010-04-17 22:01:05 +00002239 if (ICS1.getKindRank() < ICS2.getKindRank())
2240 return ImplicitConversionSequence::Better;
2241 else if (ICS2.getKindRank() < ICS1.getKindRank())
2242 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002243
Benjamin Kramer98ff7f82010-04-18 12:05:54 +00002244 // The following checks require both conversion sequences to be of
2245 // the same kind.
2246 if (ICS1.getKind() != ICS2.getKind())
2247 return ImplicitConversionSequence::Indistinguishable;
2248
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002249 // Two implicit conversion sequences of the same form are
2250 // indistinguishable conversion sequences unless one of the
2251 // following rules apply: (C++ 13.3.3.2p3):
John McCall0d1da222010-01-12 00:44:57 +00002252 if (ICS1.isStandard())
John McCall5c32be02010-08-24 20:38:10 +00002253 return CompareStandardConversionSequences(S, ICS1.Standard, ICS2.Standard);
John McCall0d1da222010-01-12 00:44:57 +00002254 else if (ICS1.isUserDefined()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002255 // User-defined conversion sequence U1 is a better conversion
2256 // sequence than another user-defined conversion sequence U2 if
2257 // they contain the same user-defined conversion function or
2258 // constructor and if the second standard conversion sequence of
2259 // U1 is better than the second standard conversion sequence of
2260 // U2 (C++ 13.3.3.2p3).
Mike Stump11289f42009-09-09 15:08:12 +00002261 if (ICS1.UserDefined.ConversionFunction ==
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002262 ICS2.UserDefined.ConversionFunction)
John McCall5c32be02010-08-24 20:38:10 +00002263 return CompareStandardConversionSequences(S,
2264 ICS1.UserDefined.After,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002265 ICS2.UserDefined.After);
2266 }
2267
2268 return ImplicitConversionSequence::Indistinguishable;
2269}
2270
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002271static bool hasSimilarType(ASTContext &Context, QualType T1, QualType T2) {
2272 while (Context.UnwrapSimilarPointerTypes(T1, T2)) {
2273 Qualifiers Quals;
2274 T1 = Context.getUnqualifiedArrayType(T1, Quals);
2275 T2 = Context.getUnqualifiedArrayType(T2, Quals);
2276 }
2277
2278 return Context.hasSameUnqualifiedType(T1, T2);
2279}
2280
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002281// Per 13.3.3.2p3, compare the given standard conversion sequences to
2282// determine if one is a proper subset of the other.
2283static ImplicitConversionSequence::CompareKind
2284compareStandardConversionSubsets(ASTContext &Context,
2285 const StandardConversionSequence& SCS1,
2286 const StandardConversionSequence& SCS2) {
2287 ImplicitConversionSequence::CompareKind Result
2288 = ImplicitConversionSequence::Indistinguishable;
2289
Douglas Gregore87561a2010-05-23 22:10:15 +00002290 // the identity conversion sequence is considered to be a subsequence of
2291 // any non-identity conversion sequence
2292 if (SCS1.ReferenceBinding == SCS2.ReferenceBinding) {
2293 if (SCS1.isIdentityConversion() && !SCS2.isIdentityConversion())
2294 return ImplicitConversionSequence::Better;
2295 else if (!SCS1.isIdentityConversion() && SCS2.isIdentityConversion())
2296 return ImplicitConversionSequence::Worse;
2297 }
2298
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002299 if (SCS1.Second != SCS2.Second) {
2300 if (SCS1.Second == ICK_Identity)
2301 Result = ImplicitConversionSequence::Better;
2302 else if (SCS2.Second == ICK_Identity)
2303 Result = ImplicitConversionSequence::Worse;
2304 else
2305 return ImplicitConversionSequence::Indistinguishable;
Douglas Gregor1fc3d662010-06-09 03:53:18 +00002306 } else if (!hasSimilarType(Context, SCS1.getToType(1), SCS2.getToType(1)))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002307 return ImplicitConversionSequence::Indistinguishable;
2308
2309 if (SCS1.Third == SCS2.Third) {
2310 return Context.hasSameType(SCS1.getToType(2), SCS2.getToType(2))? Result
2311 : ImplicitConversionSequence::Indistinguishable;
2312 }
2313
2314 if (SCS1.Third == ICK_Identity)
2315 return Result == ImplicitConversionSequence::Worse
2316 ? ImplicitConversionSequence::Indistinguishable
2317 : ImplicitConversionSequence::Better;
2318
2319 if (SCS2.Third == ICK_Identity)
2320 return Result == ImplicitConversionSequence::Better
2321 ? ImplicitConversionSequence::Indistinguishable
2322 : ImplicitConversionSequence::Worse;
2323
2324 return ImplicitConversionSequence::Indistinguishable;
2325}
2326
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002327/// CompareStandardConversionSequences - Compare two standard
2328/// conversion sequences to determine whether one is better than the
2329/// other or if they are indistinguishable (C++ 13.3.3.2p3).
John McCall5c32be02010-08-24 20:38:10 +00002330static ImplicitConversionSequence::CompareKind
2331CompareStandardConversionSequences(Sema &S,
2332 const StandardConversionSequence& SCS1,
2333 const StandardConversionSequence& SCS2)
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002334{
2335 // Standard conversion sequence S1 is a better conversion sequence
2336 // than standard conversion sequence S2 if (C++ 13.3.3.2p3):
2337
2338 // -- S1 is a proper subsequence of S2 (comparing the conversion
2339 // sequences in the canonical form defined by 13.3.3.1.1,
2340 // excluding any Lvalue Transformation; the identity conversion
2341 // sequence is considered to be a subsequence of any
2342 // non-identity conversion sequence) or, if not that,
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002343 if (ImplicitConversionSequence::CompareKind CK
John McCall5c32be02010-08-24 20:38:10 +00002344 = compareStandardConversionSubsets(S.Context, SCS1, SCS2))
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002345 return CK;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002346
2347 // -- the rank of S1 is better than the rank of S2 (by the rules
2348 // defined below), or, if not that,
2349 ImplicitConversionRank Rank1 = SCS1.getRank();
2350 ImplicitConversionRank Rank2 = SCS2.getRank();
2351 if (Rank1 < Rank2)
2352 return ImplicitConversionSequence::Better;
2353 else if (Rank2 < Rank1)
2354 return ImplicitConversionSequence::Worse;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002355
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002356 // (C++ 13.3.3.2p4): Two conversion sequences with the same rank
2357 // are indistinguishable unless one of the following rules
2358 // applies:
Mike Stump11289f42009-09-09 15:08:12 +00002359
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002360 // A conversion that is not a conversion of a pointer, or
2361 // pointer to member, to bool is better than another conversion
2362 // that is such a conversion.
2363 if (SCS1.isPointerConversionToBool() != SCS2.isPointerConversionToBool())
2364 return SCS2.isPointerConversionToBool()
2365 ? ImplicitConversionSequence::Better
2366 : ImplicitConversionSequence::Worse;
2367
Douglas Gregor5c407d92008-10-23 00:40:37 +00002368 // C++ [over.ics.rank]p4b2:
2369 //
2370 // If class B is derived directly or indirectly from class A,
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002371 // conversion of B* to A* is better than conversion of B* to
2372 // void*, and conversion of A* to void* is better than conversion
2373 // of B* to void*.
Mike Stump11289f42009-09-09 15:08:12 +00002374 bool SCS1ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002375 = SCS1.isPointerConversionToVoidPointer(S.Context);
Mike Stump11289f42009-09-09 15:08:12 +00002376 bool SCS2ConvertsToVoid
John McCall5c32be02010-08-24 20:38:10 +00002377 = SCS2.isPointerConversionToVoidPointer(S.Context);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002378 if (SCS1ConvertsToVoid != SCS2ConvertsToVoid) {
2379 // Exactly one of the conversion sequences is a conversion to
2380 // a void pointer; it's the worse conversion.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002381 return SCS2ConvertsToVoid ? ImplicitConversionSequence::Better
2382 : ImplicitConversionSequence::Worse;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002383 } else if (!SCS1ConvertsToVoid && !SCS2ConvertsToVoid) {
2384 // Neither conversion sequence converts to a void pointer; compare
2385 // their derived-to-base conversions.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002386 if (ImplicitConversionSequence::CompareKind DerivedCK
John McCall5c32be02010-08-24 20:38:10 +00002387 = CompareDerivedToBaseConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002388 return DerivedCK;
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002389 } else if (SCS1ConvertsToVoid && SCS2ConvertsToVoid) {
2390 // Both conversion sequences are conversions to void
2391 // pointers. Compare the source types to determine if there's an
2392 // inheritance relationship in their sources.
John McCall0d1da222010-01-12 00:44:57 +00002393 QualType FromType1 = SCS1.getFromType();
2394 QualType FromType2 = SCS2.getFromType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002395
2396 // Adjust the types we're converting from via the array-to-pointer
2397 // conversion, if we need to.
2398 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002399 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002400 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002401 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002402
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002403 QualType FromPointee1
2404 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
2405 QualType FromPointee2
2406 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002407
John McCall5c32be02010-08-24 20:38:10 +00002408 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002409 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002410 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002411 return ImplicitConversionSequence::Worse;
2412
2413 // Objective-C++: If one interface is more specific than the
2414 // other, it is the better one.
John McCall8b07ec22010-05-15 11:32:37 +00002415 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2416 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002417 if (FromIface1 && FromIface1) {
John McCall5c32be02010-08-24 20:38:10 +00002418 if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002419 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002420 else if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor1aa450a2009-12-13 21:37:05 +00002421 return ImplicitConversionSequence::Worse;
2422 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002423 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002424
2425 // Compare based on qualification conversions (C++ 13.3.3.2p3,
2426 // bullet 3).
Mike Stump11289f42009-09-09 15:08:12 +00002427 if (ImplicitConversionSequence::CompareKind QualCK
John McCall5c32be02010-08-24 20:38:10 +00002428 = CompareQualificationConversions(S, SCS1, SCS2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002429 return QualCK;
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002430
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002431 if (SCS1.ReferenceBinding && SCS2.ReferenceBinding) {
Sebastian Redlb28b4072009-03-22 23:49:27 +00002432 // C++0x [over.ics.rank]p3b4:
2433 // -- S1 and S2 are reference bindings (8.5.3) and neither refers to an
2434 // implicit object parameter of a non-static member function declared
2435 // without a ref-qualifier, and S1 binds an rvalue reference to an
2436 // rvalue and S2 binds an lvalue reference.
Sebastian Redl4c0cd852009-03-29 15:27:50 +00002437 // FIXME: We don't know if we're dealing with the implicit object parameter,
2438 // or if the member function in this case has a ref qualifier.
2439 // (Of course, we don't have ref qualifiers yet.)
2440 if (SCS1.RRefBinding != SCS2.RRefBinding)
2441 return SCS1.RRefBinding ? ImplicitConversionSequence::Better
2442 : ImplicitConversionSequence::Worse;
Sebastian Redlb28b4072009-03-22 23:49:27 +00002443
2444 // C++ [over.ics.rank]p3b4:
2445 // -- S1 and S2 are reference bindings (8.5.3), and the types to
2446 // which the references refer are the same type except for
2447 // top-level cv-qualifiers, and the type to which the reference
2448 // initialized by S2 refers is more cv-qualified than the type
2449 // to which the reference initialized by S1 refers.
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002450 QualType T1 = SCS1.getToType(2);
2451 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002452 T1 = S.Context.getCanonicalType(T1);
2453 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002454 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002455 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2456 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002457 if (UnqualT1 == UnqualT2) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00002458 // If the type is an array type, promote the element qualifiers to the
2459 // type for comparison.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002460 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002461 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002462 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002463 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002464 if (T2.isMoreQualifiedThan(T1))
2465 return ImplicitConversionSequence::Better;
2466 else if (T1.isMoreQualifiedThan(T2))
2467 return ImplicitConversionSequence::Worse;
2468 }
2469 }
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002470
2471 return ImplicitConversionSequence::Indistinguishable;
2472}
2473
2474/// CompareQualificationConversions - Compares two standard conversion
2475/// sequences to determine whether they can be ranked based on their
Mike Stump11289f42009-09-09 15:08:12 +00002476/// qualification conversions (C++ 13.3.3.2p3 bullet 3).
2477ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002478CompareQualificationConversions(Sema &S,
2479 const StandardConversionSequence& SCS1,
2480 const StandardConversionSequence& SCS2) {
Douglas Gregor4b62ec62008-10-22 15:04:37 +00002481 // C++ 13.3.3.2p3:
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002482 // -- S1 and S2 differ only in their qualification conversion and
2483 // yield similar types T1 and T2 (C++ 4.4), respectively, and the
2484 // cv-qualification signature of type T1 is a proper subset of
2485 // the cv-qualification signature of type T2, and S1 is not the
2486 // deprecated string literal array-to-pointer conversion (4.2).
2487 if (SCS1.First != SCS2.First || SCS1.Second != SCS2.Second ||
2488 SCS1.Third != SCS2.Third || SCS1.Third != ICK_Qualification)
2489 return ImplicitConversionSequence::Indistinguishable;
2490
2491 // FIXME: the example in the standard doesn't use a qualification
2492 // conversion (!)
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002493 QualType T1 = SCS1.getToType(2);
2494 QualType T2 = SCS2.getToType(2);
John McCall5c32be02010-08-24 20:38:10 +00002495 T1 = S.Context.getCanonicalType(T1);
2496 T2 = S.Context.getCanonicalType(T2);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002497 Qualifiers T1Quals, T2Quals;
John McCall5c32be02010-08-24 20:38:10 +00002498 QualType UnqualT1 = S.Context.getUnqualifiedArrayType(T1, T1Quals);
2499 QualType UnqualT2 = S.Context.getUnqualifiedArrayType(T2, T2Quals);
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002500
2501 // If the types are the same, we won't learn anything by unwrapped
2502 // them.
Chandler Carruth607f38e2009-12-29 07:16:59 +00002503 if (UnqualT1 == UnqualT2)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002504 return ImplicitConversionSequence::Indistinguishable;
2505
Chandler Carruth607f38e2009-12-29 07:16:59 +00002506 // If the type is an array type, promote the element qualifiers to the type
2507 // for comparison.
2508 if (isa<ArrayType>(T1) && T1Quals)
John McCall5c32be02010-08-24 20:38:10 +00002509 T1 = S.Context.getQualifiedType(UnqualT1, T1Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002510 if (isa<ArrayType>(T2) && T2Quals)
John McCall5c32be02010-08-24 20:38:10 +00002511 T2 = S.Context.getQualifiedType(UnqualT2, T2Quals);
Chandler Carruth607f38e2009-12-29 07:16:59 +00002512
Mike Stump11289f42009-09-09 15:08:12 +00002513 ImplicitConversionSequence::CompareKind Result
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002514 = ImplicitConversionSequence::Indistinguishable;
John McCall5c32be02010-08-24 20:38:10 +00002515 while (S.Context.UnwrapSimilarPointerTypes(T1, T2)) {
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002516 // Within each iteration of the loop, we check the qualifiers to
2517 // determine if this still looks like a qualification
2518 // conversion. Then, if all is well, we unwrap one more level of
Douglas Gregor29a92472008-10-22 17:49:05 +00002519 // pointers or pointers-to-members and do it all again
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002520 // until there are no more pointers or pointers-to-members left
2521 // to unwrap. This essentially mimics what
2522 // IsQualificationConversion does, but here we're checking for a
2523 // strict subset of qualifiers.
2524 if (T1.getCVRQualifiers() == T2.getCVRQualifiers())
2525 // The qualifiers are the same, so this doesn't tell us anything
2526 // about how the sequences rank.
2527 ;
2528 else if (T2.isMoreQualifiedThan(T1)) {
2529 // T1 has fewer qualifiers, so it could be the better sequence.
2530 if (Result == ImplicitConversionSequence::Worse)
2531 // Neither has qualifiers that are a subset of the other's
2532 // qualifiers.
2533 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002534
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002535 Result = ImplicitConversionSequence::Better;
2536 } else if (T1.isMoreQualifiedThan(T2)) {
2537 // T2 has fewer qualifiers, so it could be the better sequence.
2538 if (Result == ImplicitConversionSequence::Better)
2539 // Neither has qualifiers that are a subset of the other's
2540 // qualifiers.
2541 return ImplicitConversionSequence::Indistinguishable;
Mike Stump11289f42009-09-09 15:08:12 +00002542
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002543 Result = ImplicitConversionSequence::Worse;
2544 } else {
2545 // Qualifiers are disjoint.
2546 return ImplicitConversionSequence::Indistinguishable;
2547 }
2548
2549 // If the types after this point are equivalent, we're done.
John McCall5c32be02010-08-24 20:38:10 +00002550 if (S.Context.hasSameUnqualifiedType(T1, T2))
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002551 break;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002552 }
2553
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002554 // Check that the winning standard conversion sequence isn't using
2555 // the deprecated string literal array to pointer conversion.
2556 switch (Result) {
2557 case ImplicitConversionSequence::Better:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002558 if (SCS1.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002559 Result = ImplicitConversionSequence::Indistinguishable;
2560 break;
2561
2562 case ImplicitConversionSequence::Indistinguishable:
2563 break;
2564
2565 case ImplicitConversionSequence::Worse:
Douglas Gregore489a7d2010-02-28 18:30:25 +00002566 if (SCS2.DeprecatedStringLiteralToCharPtr)
Douglas Gregore1eb9d82008-10-22 14:17:15 +00002567 Result = ImplicitConversionSequence::Indistinguishable;
2568 break;
2569 }
2570
2571 return Result;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00002572}
2573
Douglas Gregor5c407d92008-10-23 00:40:37 +00002574/// CompareDerivedToBaseConversions - Compares two standard conversion
2575/// sequences to determine whether they can be ranked based on their
Douglas Gregor237f96c2008-11-26 23:31:11 +00002576/// various kinds of derived-to-base conversions (C++
2577/// [over.ics.rank]p4b3). As part of these checks, we also look at
2578/// conversions between Objective-C interface types.
Douglas Gregor5c407d92008-10-23 00:40:37 +00002579ImplicitConversionSequence::CompareKind
John McCall5c32be02010-08-24 20:38:10 +00002580CompareDerivedToBaseConversions(Sema &S,
2581 const StandardConversionSequence& SCS1,
2582 const StandardConversionSequence& SCS2) {
John McCall0d1da222010-01-12 00:44:57 +00002583 QualType FromType1 = SCS1.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002584 QualType ToType1 = SCS1.getToType(1);
John McCall0d1da222010-01-12 00:44:57 +00002585 QualType FromType2 = SCS2.getFromType();
Douglas Gregor3edc4d52010-01-27 03:51:04 +00002586 QualType ToType2 = SCS2.getToType(1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002587
2588 // Adjust the types we're converting from via the array-to-pointer
2589 // conversion, if we need to.
2590 if (SCS1.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002591 FromType1 = S.Context.getArrayDecayedType(FromType1);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002592 if (SCS2.First == ICK_Array_To_Pointer)
John McCall5c32be02010-08-24 20:38:10 +00002593 FromType2 = S.Context.getArrayDecayedType(FromType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002594
2595 // Canonicalize all of the types.
John McCall5c32be02010-08-24 20:38:10 +00002596 FromType1 = S.Context.getCanonicalType(FromType1);
2597 ToType1 = S.Context.getCanonicalType(ToType1);
2598 FromType2 = S.Context.getCanonicalType(FromType2);
2599 ToType2 = S.Context.getCanonicalType(ToType2);
Douglas Gregor5c407d92008-10-23 00:40:37 +00002600
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002601 // C++ [over.ics.rank]p4b3:
Douglas Gregor5c407d92008-10-23 00:40:37 +00002602 //
2603 // If class B is derived directly or indirectly from class A and
2604 // class C is derived directly or indirectly from B,
Douglas Gregor237f96c2008-11-26 23:31:11 +00002605 //
2606 // For Objective-C, we let A, B, and C also be Objective-C
2607 // interfaces.
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002608
2609 // Compare based on pointer conversions.
Mike Stump11289f42009-09-09 15:08:12 +00002610 if (SCS1.Second == ICK_Pointer_Conversion &&
Douglas Gregora29dc052008-11-27 01:19:21 +00002611 SCS2.Second == ICK_Pointer_Conversion &&
2612 /*FIXME: Remove if Objective-C id conversions get their own rank*/
2613 FromType1->isPointerType() && FromType2->isPointerType() &&
2614 ToType1->isPointerType() && ToType2->isPointerType()) {
Mike Stump11289f42009-09-09 15:08:12 +00002615 QualType FromPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002616 = FromType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +00002617 QualType ToPointee1
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002618 = ToType1->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002619 QualType FromPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002620 = FromType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor5c407d92008-10-23 00:40:37 +00002621 QualType ToPointee2
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002622 = ToType2->getAs<PointerType>()->getPointeeType().getUnqualifiedType();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002623
John McCall8b07ec22010-05-15 11:32:37 +00002624 const ObjCObjectType* FromIface1 = FromPointee1->getAs<ObjCObjectType>();
2625 const ObjCObjectType* FromIface2 = FromPointee2->getAs<ObjCObjectType>();
2626 const ObjCObjectType* ToIface1 = ToPointee1->getAs<ObjCObjectType>();
2627 const ObjCObjectType* ToIface2 = ToPointee2->getAs<ObjCObjectType>();
Douglas Gregor237f96c2008-11-26 23:31:11 +00002628
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002629 // -- conversion of C* to B* is better than conversion of C* to A*,
Douglas Gregor5c407d92008-10-23 00:40:37 +00002630 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002631 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002632 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002633 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Douglas Gregor5c407d92008-10-23 00:40:37 +00002634 return ImplicitConversionSequence::Worse;
Douglas Gregor237f96c2008-11-26 23:31:11 +00002635
2636 if (ToIface1 && ToIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002637 if (S.Context.canAssignObjCInterfaces(ToIface2, ToIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002638 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002639 else if (S.Context.canAssignObjCInterfaces(ToIface1, ToIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002640 return ImplicitConversionSequence::Worse;
2641 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002642 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002643
2644 // -- conversion of B* to A* is better than conversion of C* to A*,
2645 if (FromPointee1 != FromPointee2 && ToPointee1 == ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002646 if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002647 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002648 else if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002649 return ImplicitConversionSequence::Worse;
Mike Stump11289f42009-09-09 15:08:12 +00002650
Douglas Gregor237f96c2008-11-26 23:31:11 +00002651 if (FromIface1 && FromIface2) {
John McCall5c32be02010-08-24 20:38:10 +00002652 if (S.Context.canAssignObjCInterfaces(FromIface1, FromIface2))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002653 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002654 else if (S.Context.canAssignObjCInterfaces(FromIface2, FromIface1))
Douglas Gregor237f96c2008-11-26 23:31:11 +00002655 return ImplicitConversionSequence::Worse;
2656 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002657 }
Douglas Gregor5c407d92008-10-23 00:40:37 +00002658 }
2659
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002660 // Ranking of member-pointer types.
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002661 if (SCS1.Second == ICK_Pointer_Member && SCS2.Second == ICK_Pointer_Member &&
2662 FromType1->isMemberPointerType() && FromType2->isMemberPointerType() &&
2663 ToType1->isMemberPointerType() && ToType2->isMemberPointerType()) {
2664 const MemberPointerType * FromMemPointer1 =
2665 FromType1->getAs<MemberPointerType>();
2666 const MemberPointerType * ToMemPointer1 =
2667 ToType1->getAs<MemberPointerType>();
2668 const MemberPointerType * FromMemPointer2 =
2669 FromType2->getAs<MemberPointerType>();
2670 const MemberPointerType * ToMemPointer2 =
2671 ToType2->getAs<MemberPointerType>();
2672 const Type *FromPointeeType1 = FromMemPointer1->getClass();
2673 const Type *ToPointeeType1 = ToMemPointer1->getClass();
2674 const Type *FromPointeeType2 = FromMemPointer2->getClass();
2675 const Type *ToPointeeType2 = ToMemPointer2->getClass();
2676 QualType FromPointee1 = QualType(FromPointeeType1, 0).getUnqualifiedType();
2677 QualType ToPointee1 = QualType(ToPointeeType1, 0).getUnqualifiedType();
2678 QualType FromPointee2 = QualType(FromPointeeType2, 0).getUnqualifiedType();
2679 QualType ToPointee2 = QualType(ToPointeeType2, 0).getUnqualifiedType();
Fariborz Jahanianac741ff2009-10-20 20:07:35 +00002680 // conversion of A::* to B::* is better than conversion of A::* to C::*,
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002681 if (FromPointee1 == FromPointee2 && ToPointee1 != ToPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002682 if (S.IsDerivedFrom(ToPointee1, ToPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002683 return ImplicitConversionSequence::Worse;
John McCall5c32be02010-08-24 20:38:10 +00002684 else if (S.IsDerivedFrom(ToPointee2, ToPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002685 return ImplicitConversionSequence::Better;
2686 }
2687 // conversion of B::* to C::* is better than conversion of A::* to C::*
2688 if (ToPointee1 == ToPointee2 && FromPointee1 != FromPointee2) {
John McCall5c32be02010-08-24 20:38:10 +00002689 if (S.IsDerivedFrom(FromPointee1, FromPointee2))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002690 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002691 else if (S.IsDerivedFrom(FromPointee2, FromPointee1))
Fariborz Jahanian9a587b02009-10-20 20:04:46 +00002692 return ImplicitConversionSequence::Worse;
2693 }
2694 }
2695
Douglas Gregor5ab11652010-04-17 22:01:05 +00002696 if (SCS1.Second == ICK_Derived_To_Base) {
Douglas Gregor2fe98832008-11-03 19:09:14 +00002697 // -- conversion of C to B is better than conversion of C to A,
Douglas Gregor83af86a2010-02-25 19:01:05 +00002698 // -- binding of an expression of type C to a reference of type
2699 // B& is better than binding an expression of type C to a
2700 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002701 if (S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2702 !S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2703 if (S.IsDerivedFrom(ToType1, ToType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002704 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002705 else if (S.IsDerivedFrom(ToType2, ToType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002706 return ImplicitConversionSequence::Worse;
2707 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002708
Douglas Gregor2fe98832008-11-03 19:09:14 +00002709 // -- conversion of B to A is better than conversion of C to A.
Douglas Gregor83af86a2010-02-25 19:01:05 +00002710 // -- binding of an expression of type B to a reference of type
2711 // A& is better than binding an expression of type C to a
2712 // reference of type A&,
John McCall5c32be02010-08-24 20:38:10 +00002713 if (!S.Context.hasSameUnqualifiedType(FromType1, FromType2) &&
2714 S.Context.hasSameUnqualifiedType(ToType1, ToType2)) {
2715 if (S.IsDerivedFrom(FromType2, FromType1))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002716 return ImplicitConversionSequence::Better;
John McCall5c32be02010-08-24 20:38:10 +00002717 else if (S.IsDerivedFrom(FromType1, FromType2))
Douglas Gregor2fe98832008-11-03 19:09:14 +00002718 return ImplicitConversionSequence::Worse;
2719 }
2720 }
Douglas Gregoref30a5f2008-10-29 14:50:44 +00002721
Douglas Gregor5c407d92008-10-23 00:40:37 +00002722 return ImplicitConversionSequence::Indistinguishable;
2723}
2724
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002725/// CompareReferenceRelationship - Compare the two types T1 and T2 to
2726/// determine whether they are reference-related,
2727/// reference-compatible, reference-compatible with added
2728/// qualification, or incompatible, for use in C++ initialization by
2729/// reference (C++ [dcl.ref.init]p4). Neither type can be a reference
2730/// type, and the first type (T1) is the pointee type of the reference
2731/// type being initialized.
2732Sema::ReferenceCompareResult
2733Sema::CompareReferenceRelationship(SourceLocation Loc,
2734 QualType OrigT1, QualType OrigT2,
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002735 bool &DerivedToBase,
2736 bool &ObjCConversion) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002737 assert(!OrigT1->isReferenceType() &&
2738 "T1 must be the pointee type of the reference type");
2739 assert(!OrigT2->isReferenceType() && "T2 cannot be a reference type");
2740
2741 QualType T1 = Context.getCanonicalType(OrigT1);
2742 QualType T2 = Context.getCanonicalType(OrigT2);
2743 Qualifiers T1Quals, T2Quals;
2744 QualType UnqualT1 = Context.getUnqualifiedArrayType(T1, T1Quals);
2745 QualType UnqualT2 = Context.getUnqualifiedArrayType(T2, T2Quals);
2746
2747 // C++ [dcl.init.ref]p4:
2748 // Given types "cv1 T1" and "cv2 T2," "cv1 T1" is
2749 // reference-related to "cv2 T2" if T1 is the same type as T2, or
2750 // T1 is a base class of T2.
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002751 DerivedToBase = false;
2752 ObjCConversion = false;
2753 if (UnqualT1 == UnqualT2) {
2754 // Nothing to do.
2755 } else if (!RequireCompleteType(Loc, OrigT2, PDiag()) &&
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002756 IsDerivedFrom(UnqualT2, UnqualT1))
2757 DerivedToBase = true;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002758 else if (UnqualT1->isObjCObjectOrInterfaceType() &&
2759 UnqualT2->isObjCObjectOrInterfaceType() &&
2760 Context.canBindObjCObjectType(UnqualT1, UnqualT2))
2761 ObjCConversion = true;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002762 else
2763 return Ref_Incompatible;
2764
2765 // At this point, we know that T1 and T2 are reference-related (at
2766 // least).
2767
2768 // If the type is an array type, promote the element qualifiers to the type
2769 // for comparison.
2770 if (isa<ArrayType>(T1) && T1Quals)
2771 T1 = Context.getQualifiedType(UnqualT1, T1Quals);
2772 if (isa<ArrayType>(T2) && T2Quals)
2773 T2 = Context.getQualifiedType(UnqualT2, T2Quals);
2774
2775 // C++ [dcl.init.ref]p4:
2776 // "cv1 T1" is reference-compatible with "cv2 T2" if T1 is
2777 // reference-related to T2 and cv1 is the same cv-qualification
2778 // as, or greater cv-qualification than, cv2. For purposes of
2779 // overload resolution, cases for which cv1 is greater
2780 // cv-qualification than cv2 are identified as
2781 // reference-compatible with added qualification (see 13.3.3.2).
2782 if (T1Quals.getCVRQualifiers() == T2Quals.getCVRQualifiers())
2783 return Ref_Compatible;
2784 else if (T1.isMoreQualifiedThan(T2))
2785 return Ref_Compatible_With_Added_Qualification;
2786 else
2787 return Ref_Related;
2788}
2789
Douglas Gregor836a7e82010-08-11 02:15:33 +00002790/// \brief Look for a user-defined conversion to an value reference-compatible
Sebastian Redld92badf2010-06-30 18:13:39 +00002791/// with DeclType. Return true if something definite is found.
2792static bool
Douglas Gregor836a7e82010-08-11 02:15:33 +00002793FindConversionForRefInit(Sema &S, ImplicitConversionSequence &ICS,
2794 QualType DeclType, SourceLocation DeclLoc,
2795 Expr *Init, QualType T2, bool AllowRvalues,
2796 bool AllowExplicit) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002797 assert(T2->isRecordType() && "Can only find conversions of record types.");
2798 CXXRecordDecl *T2RecordDecl
2799 = dyn_cast<CXXRecordDecl>(T2->getAs<RecordType>()->getDecl());
2800
Douglas Gregor836a7e82010-08-11 02:15:33 +00002801 QualType ToType
2802 = AllowRvalues? DeclType->getAs<ReferenceType>()->getPointeeType()
2803 : DeclType;
2804
Sebastian Redld92badf2010-06-30 18:13:39 +00002805 OverloadCandidateSet CandidateSet(DeclLoc);
2806 const UnresolvedSetImpl *Conversions
2807 = T2RecordDecl->getVisibleConversionFunctions();
2808 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
2809 E = Conversions->end(); I != E; ++I) {
2810 NamedDecl *D = *I;
2811 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(D->getDeclContext());
2812 if (isa<UsingShadowDecl>(D))
2813 D = cast<UsingShadowDecl>(D)->getTargetDecl();
2814
2815 FunctionTemplateDecl *ConvTemplate
2816 = dyn_cast<FunctionTemplateDecl>(D);
2817 CXXConversionDecl *Conv;
2818 if (ConvTemplate)
2819 Conv = cast<CXXConversionDecl>(ConvTemplate->getTemplatedDecl());
2820 else
2821 Conv = cast<CXXConversionDecl>(D);
2822
Douglas Gregor836a7e82010-08-11 02:15:33 +00002823 // If this is an explicit conversion, and we're not allowed to consider
2824 // explicit conversions, skip it.
2825 if (!AllowExplicit && Conv->isExplicit())
2826 continue;
2827
2828 if (AllowRvalues) {
2829 bool DerivedToBase = false;
2830 bool ObjCConversion = false;
2831 if (!ConvTemplate &&
Chandler Carruth8e543b32010-12-12 08:17:55 +00002832 S.CompareReferenceRelationship(
2833 DeclLoc,
2834 Conv->getConversionType().getNonReferenceType()
2835 .getUnqualifiedType(),
2836 DeclType.getNonReferenceType().getUnqualifiedType(),
2837 DerivedToBase, ObjCConversion) ==
2838 Sema::Ref_Incompatible)
Douglas Gregor836a7e82010-08-11 02:15:33 +00002839 continue;
2840 } else {
2841 // If the conversion function doesn't return a reference type,
2842 // it can't be considered for this conversion. An rvalue reference
2843 // is only acceptable if its referencee is a function type.
2844
2845 const ReferenceType *RefType =
2846 Conv->getConversionType()->getAs<ReferenceType>();
2847 if (!RefType ||
2848 (!RefType->isLValueReferenceType() &&
2849 !RefType->getPointeeType()->isFunctionType()))
2850 continue;
Sebastian Redld92badf2010-06-30 18:13:39 +00002851 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00002852
2853 if (ConvTemplate)
2854 S.AddTemplateConversionCandidate(ConvTemplate, I.getPair(), ActingDC,
2855 Init, ToType, CandidateSet);
2856 else
2857 S.AddConversionCandidate(Conv, I.getPair(), ActingDC, Init,
2858 ToType, CandidateSet);
Sebastian Redld92badf2010-06-30 18:13:39 +00002859 }
2860
2861 OverloadCandidateSet::iterator Best;
Douglas Gregord5b730c92010-09-12 08:07:23 +00002862 switch (CandidateSet.BestViableFunction(S, DeclLoc, Best, true)) {
Sebastian Redld92badf2010-06-30 18:13:39 +00002863 case OR_Success:
2864 // C++ [over.ics.ref]p1:
2865 //
2866 // [...] If the parameter binds directly to the result of
2867 // applying a conversion function to the argument
2868 // expression, the implicit conversion sequence is a
2869 // user-defined conversion sequence (13.3.3.1.2), with the
2870 // second standard conversion sequence either an identity
2871 // conversion or, if the conversion function returns an
2872 // entity of a type that is a derived class of the parameter
2873 // type, a derived-to-base Conversion.
2874 if (!Best->FinalConversion.DirectBinding)
2875 return false;
2876
2877 ICS.setUserDefined();
2878 ICS.UserDefined.Before = Best->Conversions[0].Standard;
2879 ICS.UserDefined.After = Best->FinalConversion;
2880 ICS.UserDefined.ConversionFunction = Best->Function;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00002881 ICS.UserDefined.FoundConversionFunction = Best->FoundDecl.getDecl();
Sebastian Redld92badf2010-06-30 18:13:39 +00002882 ICS.UserDefined.EllipsisConversion = false;
2883 assert(ICS.UserDefined.After.ReferenceBinding &&
2884 ICS.UserDefined.After.DirectBinding &&
2885 "Expected a direct reference binding!");
2886 return true;
2887
2888 case OR_Ambiguous:
2889 ICS.setAmbiguous();
2890 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin();
2891 Cand != CandidateSet.end(); ++Cand)
2892 if (Cand->Viable)
2893 ICS.Ambiguous.addConversion(Cand->Function);
2894 return true;
2895
2896 case OR_No_Viable_Function:
2897 case OR_Deleted:
2898 // There was no suitable conversion, or we found a deleted
2899 // conversion; continue with other checks.
2900 return false;
2901 }
Eric Christopheraba9fb22010-06-30 18:36:32 +00002902
2903 return false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002904}
2905
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002906/// \brief Compute an implicit conversion sequence for reference
2907/// initialization.
2908static ImplicitConversionSequence
2909TryReferenceInit(Sema &S, Expr *&Init, QualType DeclType,
2910 SourceLocation DeclLoc,
2911 bool SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00002912 bool AllowExplicit) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002913 assert(DeclType->isReferenceType() && "Reference init needs a reference");
2914
2915 // Most paths end in a failed conversion.
2916 ImplicitConversionSequence ICS;
2917 ICS.setBad(BadConversionSequence::no_conversion, Init, DeclType);
2918
2919 QualType T1 = DeclType->getAs<ReferenceType>()->getPointeeType();
2920 QualType T2 = Init->getType();
2921
2922 // If the initializer is the address of an overloaded function, try
2923 // to resolve the overloaded function. If all goes well, T2 is the
2924 // type of the resulting function.
2925 if (S.Context.getCanonicalType(T2) == S.Context.OverloadTy) {
2926 DeclAccessPair Found;
2927 if (FunctionDecl *Fn = S.ResolveAddressOfOverloadedFunction(Init, DeclType,
2928 false, Found))
2929 T2 = Fn->getType();
2930 }
2931
2932 // Compute some basic properties of the types and the initializer.
2933 bool isRValRef = DeclType->isRValueReferenceType();
2934 bool DerivedToBase = false;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002935 bool ObjCConversion = false;
Sebastian Redld92badf2010-06-30 18:13:39 +00002936 Expr::Classification InitCategory = Init->Classify(S.Context);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002937 Sema::ReferenceCompareResult RefRelationship
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002938 = S.CompareReferenceRelationship(DeclLoc, T1, T2, DerivedToBase,
2939 ObjCConversion);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002940
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002941
Sebastian Redld92badf2010-06-30 18:13:39 +00002942 // C++0x [dcl.init.ref]p5:
Douglas Gregor870f3742010-04-18 09:22:00 +00002943 // A reference to type "cv1 T1" is initialized by an expression
2944 // of type "cv2 T2" as follows:
2945
Sebastian Redld92badf2010-06-30 18:13:39 +00002946 // -- If reference is an lvalue reference and the initializer expression
2947 // The next bullet point (T1 is a function) is pretty much equivalent to this
2948 // one, so it's handled here.
2949 if (!isRValRef || T1->isFunctionType()) {
2950 // -- is an lvalue (but is not a bit-field), and "cv1 T1" is
2951 // reference-compatible with "cv2 T2," or
2952 //
2953 // Per C++ [over.ics.ref]p4, we don't check the bit-field property here.
2954 if (InitCategory.isLValue() &&
2955 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002956 // C++ [over.ics.ref]p1:
Sebastian Redld92badf2010-06-30 18:13:39 +00002957 // When a parameter of reference type binds directly (8.5.3)
2958 // to an argument expression, the implicit conversion sequence
2959 // is the identity conversion, unless the argument expression
2960 // has a type that is a derived class of the parameter type,
2961 // in which case the implicit conversion sequence is a
2962 // derived-to-base Conversion (13.3.3.1).
2963 ICS.setStandard();
2964 ICS.Standard.First = ICK_Identity;
Douglas Gregor8b2d2fe2010-08-07 11:51:51 +00002965 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
2966 : ObjCConversion? ICK_Compatible_Conversion
2967 : ICK_Identity;
Sebastian Redld92badf2010-06-30 18:13:39 +00002968 ICS.Standard.Third = ICK_Identity;
2969 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
2970 ICS.Standard.setToType(0, T2);
2971 ICS.Standard.setToType(1, T1);
2972 ICS.Standard.setToType(2, T1);
2973 ICS.Standard.ReferenceBinding = true;
2974 ICS.Standard.DirectBinding = true;
2975 ICS.Standard.RRefBinding = isRValRef;
2976 ICS.Standard.CopyConstructor = 0;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002977
Sebastian Redld92badf2010-06-30 18:13:39 +00002978 // Nothing more to do: the inaccessibility/ambiguity check for
2979 // derived-to-base conversions is suppressed when we're
2980 // computing the implicit conversion sequence (C++
2981 // [over.best.ics]p2).
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002982 return ICS;
Sebastian Redld92badf2010-06-30 18:13:39 +00002983 }
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002984
Sebastian Redld92badf2010-06-30 18:13:39 +00002985 // -- has a class type (i.e., T2 is a class type), where T1 is
2986 // not reference-related to T2, and can be implicitly
2987 // converted to an lvalue of type "cv3 T3," where "cv1 T1"
2988 // is reference-compatible with "cv3 T3" 92) (this
2989 // conversion is selected by enumerating the applicable
2990 // conversion functions (13.3.1.6) and choosing the best
2991 // one through overload resolution (13.3)),
2992 if (!SuppressUserConversions && T2->isRecordType() &&
2993 !S.RequireCompleteType(DeclLoc, T2, 0) &&
2994 RefRelationship == Sema::Ref_Incompatible) {
Douglas Gregor836a7e82010-08-11 02:15:33 +00002995 if (FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
2996 Init, T2, /*AllowRvalues=*/false,
2997 AllowExplicit))
Sebastian Redld92badf2010-06-30 18:13:39 +00002998 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00002999 }
3000 }
3001
Sebastian Redld92badf2010-06-30 18:13:39 +00003002 // -- Otherwise, the reference shall be an lvalue reference to a
3003 // non-volatile const type (i.e., cv1 shall be const), or the reference
3004 // shall be an rvalue reference and the initializer expression shall be
3005 // an rvalue or have a function type.
Douglas Gregor870f3742010-04-18 09:22:00 +00003006 //
3007 // We actually handle one oddity of C++ [over.ics.ref] at this
3008 // point, which is that, due to p2 (which short-circuits reference
3009 // binding by only attempting a simple conversion for non-direct
3010 // bindings) and p3's strange wording, we allow a const volatile
3011 // reference to bind to an rvalue. Hence the check for the presence
3012 // of "const" rather than checking for "const" being the only
3013 // qualifier.
Sebastian Redld92badf2010-06-30 18:13:39 +00003014 // This is also the point where rvalue references and lvalue inits no longer
3015 // go together.
3016 if ((!isRValRef && !T1.isConstQualified()) ||
3017 (isRValRef && InitCategory.isLValue()))
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003018 return ICS;
3019
Sebastian Redld92badf2010-06-30 18:13:39 +00003020 // -- If T1 is a function type, then
3021 // -- if T2 is the same type as T1, the reference is bound to the
3022 // initializer expression lvalue;
3023 // -- if T2 is a class type and the initializer expression can be
3024 // implicitly converted to an lvalue of type T1 [...], the
3025 // reference is bound to the function lvalue that is the result
3026 // of the conversion;
3027 // This is the same as for the lvalue case above, so it was handled there.
3028 // -- otherwise, the program is ill-formed.
3029 // This is the one difference to the lvalue case.
3030 if (T1->isFunctionType())
3031 return ICS;
3032
3033 // -- Otherwise, if T2 is a class type and
Douglas Gregorf93df192010-04-18 08:46:23 +00003034 // -- the initializer expression is an rvalue and "cv1 T1"
3035 // is reference-compatible with "cv2 T2," or
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003036 //
Douglas Gregorf93df192010-04-18 08:46:23 +00003037 // -- T1 is not reference-related to T2 and the initializer
3038 // expression can be implicitly converted to an rvalue
3039 // of type "cv3 T3" (this conversion is selected by
3040 // enumerating the applicable conversion functions
3041 // (13.3.1.6) and choosing the best one through overload
3042 // resolution (13.3)),
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003043 //
Douglas Gregorf93df192010-04-18 08:46:23 +00003044 // then the reference is bound to the initializer
3045 // expression rvalue in the first case and to the object
3046 // that is the result of the conversion in the second case
3047 // (or, in either case, to the appropriate base class
3048 // subobject of the object).
Douglas Gregor836a7e82010-08-11 02:15:33 +00003049 if (T2->isRecordType()) {
3050 // First case: "cv1 T1" is reference-compatible with "cv2 T2". This is a
3051 // direct binding in C++0x but not in C++03.
3052 if (InitCategory.isRValue() &&
3053 RefRelationship >= Sema::Ref_Compatible_With_Added_Qualification) {
3054 ICS.setStandard();
3055 ICS.Standard.First = ICK_Identity;
3056 ICS.Standard.Second = DerivedToBase? ICK_Derived_To_Base
3057 : ObjCConversion? ICK_Compatible_Conversion
3058 : ICK_Identity;
3059 ICS.Standard.Third = ICK_Identity;
3060 ICS.Standard.FromTypePtr = T2.getAsOpaquePtr();
3061 ICS.Standard.setToType(0, T2);
3062 ICS.Standard.setToType(1, T1);
3063 ICS.Standard.setToType(2, T1);
3064 ICS.Standard.ReferenceBinding = true;
3065 ICS.Standard.DirectBinding = S.getLangOptions().CPlusPlus0x;
3066 ICS.Standard.RRefBinding = isRValRef;
3067 ICS.Standard.CopyConstructor = 0;
3068 return ICS;
3069 }
3070
3071 // Second case: not reference-related.
3072 if (RefRelationship == Sema::Ref_Incompatible &&
3073 !S.RequireCompleteType(DeclLoc, T2, 0) &&
3074 FindConversionForRefInit(S, ICS, DeclType, DeclLoc,
3075 Init, T2, /*AllowRvalues=*/true,
3076 AllowExplicit))
3077 return ICS;
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003078 }
Douglas Gregor836a7e82010-08-11 02:15:33 +00003079
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003080 // -- Otherwise, a temporary of type "cv1 T1" is created and
3081 // initialized from the initializer expression using the
3082 // rules for a non-reference copy initialization (8.5). The
3083 // reference is then bound to the temporary. If T1 is
3084 // reference-related to T2, cv1 must be the same
3085 // cv-qualification as, or greater cv-qualification than,
3086 // cv2; otherwise, the program is ill-formed.
3087 if (RefRelationship == Sema::Ref_Related) {
3088 // If cv1 == cv2 or cv1 is a greater cv-qualified than cv2, then
3089 // we would be reference-compatible or reference-compatible with
3090 // added qualification. But that wasn't the case, so the reference
3091 // initialization fails.
3092 return ICS;
3093 }
3094
3095 // If at least one of the types is a class type, the types are not
3096 // related, and we aren't allowed any user conversions, the
3097 // reference binding fails. This case is important for breaking
3098 // recursion, since TryImplicitConversion below will attempt to
3099 // create a temporary through the use of a copy constructor.
3100 if (SuppressUserConversions && RefRelationship == Sema::Ref_Incompatible &&
3101 (T1->isRecordType() || T2->isRecordType()))
3102 return ICS;
3103
3104 // C++ [over.ics.ref]p2:
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003105 // When a parameter of reference type is not bound directly to
3106 // an argument expression, the conversion sequence is the one
3107 // required to convert the argument expression to the
3108 // underlying type of the reference according to
3109 // 13.3.3.1. Conceptually, this conversion sequence corresponds
3110 // to copy-initializing a temporary of the underlying type with
3111 // the argument expression. Any difference in top-level
3112 // cv-qualification is subsumed by the initialization itself
3113 // and does not constitute a conversion.
John McCall5c32be02010-08-24 20:38:10 +00003114 ICS = TryImplicitConversion(S, Init, T1, SuppressUserConversions,
3115 /*AllowExplicit=*/false,
3116 /*InOverloadResolution=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003117
3118 // Of course, that's still a reference binding.
3119 if (ICS.isStandard()) {
3120 ICS.Standard.ReferenceBinding = true;
3121 ICS.Standard.RRefBinding = isRValRef;
3122 } else if (ICS.isUserDefined()) {
3123 ICS.UserDefined.After.ReferenceBinding = true;
3124 ICS.UserDefined.After.RRefBinding = isRValRef;
3125 }
3126 return ICS;
3127}
3128
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003129/// TryCopyInitialization - Try to copy-initialize a value of type
3130/// ToType from the expression From. Return the implicit conversion
3131/// sequence required to pass this argument, which may be a bad
3132/// conversion sequence (meaning that the argument cannot be passed to
Douglas Gregor2fe98832008-11-03 19:09:14 +00003133/// a parameter of this type). If @p SuppressUserConversions, then we
Douglas Gregore81335c2010-04-16 18:00:29 +00003134/// do not permit any user-defined conversion sequences.
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003135static ImplicitConversionSequence
3136TryCopyInitialization(Sema &S, Expr *From, QualType ToType,
Douglas Gregordcd27ff2010-04-16 17:53:55 +00003137 bool SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003138 bool InOverloadResolution) {
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003139 if (ToType->isReferenceType())
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003140 return TryReferenceInit(S, From, ToType,
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003141 /*FIXME:*/From->getLocStart(),
3142 SuppressUserConversions,
Douglas Gregoradc7a702010-04-16 17:45:54 +00003143 /*AllowExplicit=*/false);
Douglas Gregor38ae6ab2010-04-13 16:31:36 +00003144
John McCall5c32be02010-08-24 20:38:10 +00003145 return TryImplicitConversion(S, From, ToType,
3146 SuppressUserConversions,
3147 /*AllowExplicit=*/false,
3148 InOverloadResolution);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00003149}
3150
Douglas Gregor436424c2008-11-18 23:14:02 +00003151/// TryObjectArgumentInitialization - Try to initialize the object
3152/// parameter of the given member function (@c Method) from the
3153/// expression @p From.
John McCall5c32be02010-08-24 20:38:10 +00003154static ImplicitConversionSequence
3155TryObjectArgumentInitialization(Sema &S, QualType OrigFromType,
3156 CXXMethodDecl *Method,
3157 CXXRecordDecl *ActingContext) {
3158 QualType ClassType = S.Context.getTypeDeclType(ActingContext);
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003159 // [class.dtor]p2: A destructor can be invoked for a const, volatile or
3160 // const volatile object.
3161 unsigned Quals = isa<CXXDestructorDecl>(Method) ?
3162 Qualifiers::Const | Qualifiers::Volatile : Method->getTypeQualifiers();
John McCall5c32be02010-08-24 20:38:10 +00003163 QualType ImplicitParamType = S.Context.getCVRQualifiedType(ClassType, Quals);
Douglas Gregor436424c2008-11-18 23:14:02 +00003164
3165 // Set up the conversion sequence as a "bad" conversion, to allow us
3166 // to exit early.
3167 ImplicitConversionSequence ICS;
Douglas Gregor436424c2008-11-18 23:14:02 +00003168
3169 // We need to have an object of class type.
John McCall47000992010-01-14 03:28:57 +00003170 QualType FromType = OrigFromType;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003171 if (const PointerType *PT = FromType->getAs<PointerType>())
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003172 FromType = PT->getPointeeType();
3173
3174 assert(FromType->isRecordType());
Douglas Gregor436424c2008-11-18 23:14:02 +00003175
Sebastian Redl931e0bd2009-11-18 20:55:52 +00003176 // The implicit object parameter is has the type "reference to cv X",
Douglas Gregor436424c2008-11-18 23:14:02 +00003177 // where X is the class of which the function is a member
3178 // (C++ [over.match.funcs]p4). However, when finding an implicit
3179 // conversion sequence for the argument, we are not allowed to
Mike Stump11289f42009-09-09 15:08:12 +00003180 // create temporaries or perform user-defined conversions
Douglas Gregor436424c2008-11-18 23:14:02 +00003181 // (C++ [over.match.funcs]p5). We perform a simplified version of
3182 // reference binding here, that allows class rvalues to bind to
3183 // non-constant references.
3184
3185 // First check the qualifiers. We don't care about lvalue-vs-rvalue
3186 // with the implicit object parameter (C++ [over.match.funcs]p5).
John McCall5c32be02010-08-24 20:38:10 +00003187 QualType FromTypeCanon = S.Context.getCanonicalType(FromType);
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00003188 if (ImplicitParamType.getCVRQualifiers()
3189 != FromTypeCanon.getLocalCVRQualifiers() &&
John McCall6a61b522010-01-13 09:16:55 +00003190 !ImplicitParamType.isAtLeastAsQualifiedAs(FromTypeCanon)) {
John McCall65eb8792010-02-25 01:37:24 +00003191 ICS.setBad(BadConversionSequence::bad_qualifiers,
3192 OrigFromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003193 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003194 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003195
3196 // Check that we have either the same type or a derived type. It
3197 // affects the conversion rank.
John McCall5c32be02010-08-24 20:38:10 +00003198 QualType ClassTypeCanon = S.Context.getCanonicalType(ClassType);
John McCall65eb8792010-02-25 01:37:24 +00003199 ImplicitConversionKind SecondKind;
3200 if (ClassTypeCanon == FromTypeCanon.getLocalUnqualifiedType()) {
3201 SecondKind = ICK_Identity;
John McCall5c32be02010-08-24 20:38:10 +00003202 } else if (S.IsDerivedFrom(FromType, ClassType))
John McCall65eb8792010-02-25 01:37:24 +00003203 SecondKind = ICK_Derived_To_Base;
John McCall6a61b522010-01-13 09:16:55 +00003204 else {
John McCall65eb8792010-02-25 01:37:24 +00003205 ICS.setBad(BadConversionSequence::unrelated_class,
3206 FromType, ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003207 return ICS;
John McCall6a61b522010-01-13 09:16:55 +00003208 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003209
3210 // Success. Mark this as a reference binding.
John McCall0d1da222010-01-12 00:44:57 +00003211 ICS.setStandard();
John McCall65eb8792010-02-25 01:37:24 +00003212 ICS.Standard.setAsIdentityConversion();
3213 ICS.Standard.Second = SecondKind;
John McCall0d1da222010-01-12 00:44:57 +00003214 ICS.Standard.setFromType(FromType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003215 ICS.Standard.setAllToTypes(ImplicitParamType);
Douglas Gregor436424c2008-11-18 23:14:02 +00003216 ICS.Standard.ReferenceBinding = true;
3217 ICS.Standard.DirectBinding = true;
Sebastian Redlf69a94a2009-03-29 22:46:24 +00003218 ICS.Standard.RRefBinding = false;
Douglas Gregor436424c2008-11-18 23:14:02 +00003219 return ICS;
3220}
3221
3222/// PerformObjectArgumentInitialization - Perform initialization of
3223/// the implicit object parameter for the given Method with the given
3224/// expression.
3225bool
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003226Sema::PerformObjectArgumentInitialization(Expr *&From,
3227 NestedNameSpecifier *Qualifier,
John McCall16df1e52010-03-30 21:47:33 +00003228 NamedDecl *FoundDecl,
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003229 CXXMethodDecl *Method) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003230 QualType FromRecordType, DestType;
Mike Stump11289f42009-09-09 15:08:12 +00003231 QualType ImplicitParamRecordType =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003232 Method->getThisType(Context)->getAs<PointerType>()->getPointeeType();
Mike Stump11289f42009-09-09 15:08:12 +00003233
Ted Kremenekc23c7e62009-07-29 21:53:49 +00003234 if (const PointerType *PT = From->getType()->getAs<PointerType>()) {
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003235 FromRecordType = PT->getPointeeType();
3236 DestType = Method->getThisType(Context);
3237 } else {
3238 FromRecordType = From->getType();
3239 DestType = ImplicitParamRecordType;
3240 }
3241
John McCall6e9f8f62009-12-03 04:06:58 +00003242 // Note that we always use the true parent context when performing
3243 // the actual argument initialization.
Mike Stump11289f42009-09-09 15:08:12 +00003244 ImplicitConversionSequence ICS
John McCall5c32be02010-08-24 20:38:10 +00003245 = TryObjectArgumentInitialization(*this, From->getType(), Method,
John McCall6e9f8f62009-12-03 04:06:58 +00003246 Method->getParent());
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003247 if (ICS.isBad()) {
3248 if (ICS.Bad.Kind == BadConversionSequence::bad_qualifiers) {
3249 Qualifiers FromQs = FromRecordType.getQualifiers();
3250 Qualifiers ToQs = DestType.getQualifiers();
3251 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
3252 if (CVR) {
3253 Diag(From->getSourceRange().getBegin(),
3254 diag::err_member_function_call_bad_cvr)
3255 << Method->getDeclName() << FromRecordType << (CVR - 1)
3256 << From->getSourceRange();
3257 Diag(Method->getLocation(), diag::note_previous_decl)
3258 << Method->getDeclName();
3259 return true;
3260 }
3261 }
3262
Douglas Gregor436424c2008-11-18 23:14:02 +00003263 return Diag(From->getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00003264 diag::err_implicit_object_parameter_init)
Anders Carlssonbfdea0f2009-05-01 18:34:30 +00003265 << ImplicitParamRecordType << FromRecordType << From->getSourceRange();
Argyrios Kyrtzidis9813d322010-11-16 08:04:45 +00003266 }
Mike Stump11289f42009-09-09 15:08:12 +00003267
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003268 if (ICS.Standard.Second == ICK_Derived_To_Base)
John McCall16df1e52010-03-30 21:47:33 +00003269 return PerformObjectMemberConversion(From, Qualifier, FoundDecl, Method);
Douglas Gregor436424c2008-11-18 23:14:02 +00003270
Douglas Gregorcc3f3252010-03-03 23:55:11 +00003271 if (!Context.hasSameType(From->getType(), DestType))
John McCalle3027922010-08-25 11:45:40 +00003272 ImpCastExprToType(From, DestType, CK_NoOp,
John McCall2536c6d2010-08-25 10:28:54 +00003273 From->getType()->isPointerType() ? VK_RValue : VK_LValue);
Douglas Gregor436424c2008-11-18 23:14:02 +00003274 return false;
3275}
3276
Douglas Gregor5fb53972009-01-14 15:45:31 +00003277/// TryContextuallyConvertToBool - Attempt to contextually convert the
3278/// expression From to bool (C++0x [conv]p3).
John McCall5c32be02010-08-24 20:38:10 +00003279static ImplicitConversionSequence
3280TryContextuallyConvertToBool(Sema &S, Expr *From) {
Douglas Gregor0bbe94d2010-05-08 22:41:50 +00003281 // FIXME: This is pretty broken.
John McCall5c32be02010-08-24 20:38:10 +00003282 return TryImplicitConversion(S, From, S.Context.BoolTy,
Anders Carlssonef4c7212009-08-27 17:24:15 +00003283 // FIXME: Are these flags correct?
3284 /*SuppressUserConversions=*/false,
Mike Stump11289f42009-09-09 15:08:12 +00003285 /*AllowExplicit=*/true,
Anders Carlsson228eea32009-08-28 15:33:32 +00003286 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00003287}
3288
3289/// PerformContextuallyConvertToBool - Perform a contextual conversion
3290/// of the expression From to bool (C++0x [conv]p3).
3291bool Sema::PerformContextuallyConvertToBool(Expr *&From) {
John McCall5c32be02010-08-24 20:38:10 +00003292 ImplicitConversionSequence ICS = TryContextuallyConvertToBool(*this, From);
John McCall0d1da222010-01-12 00:44:57 +00003293 if (!ICS.isBad())
3294 return PerformImplicitConversion(From, Context.BoolTy, ICS, AA_Converting);
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003295
Fariborz Jahanian76197412009-11-18 18:26:29 +00003296 if (!DiagnoseMultipleUserDefinedConversion(From, Context.BoolTy))
Fariborz Jahanianf0647a52009-09-22 20:24:30 +00003297 return Diag(From->getSourceRange().getBegin(),
3298 diag::err_typecheck_bool_condition)
3299 << From->getType() << From->getSourceRange();
3300 return true;
Douglas Gregor5fb53972009-01-14 15:45:31 +00003301}
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003302
3303/// TryContextuallyConvertToObjCId - Attempt to contextually convert the
3304/// expression From to 'id'.
John McCall5c32be02010-08-24 20:38:10 +00003305static ImplicitConversionSequence
3306TryContextuallyConvertToObjCId(Sema &S, Expr *From) {
3307 QualType Ty = S.Context.getObjCIdType();
3308 return TryImplicitConversion(S, From, Ty,
3309 // FIXME: Are these flags correct?
3310 /*SuppressUserConversions=*/false,
3311 /*AllowExplicit=*/true,
3312 /*InOverloadResolution=*/false);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003313}
John McCall5c32be02010-08-24 20:38:10 +00003314
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003315/// PerformContextuallyConvertToObjCId - Perform a contextual conversion
3316/// of the expression From to 'id'.
3317bool Sema::PerformContextuallyConvertToObjCId(Expr *&From) {
John McCall8b07ec22010-05-15 11:32:37 +00003318 QualType Ty = Context.getObjCIdType();
John McCall5c32be02010-08-24 20:38:10 +00003319 ImplicitConversionSequence ICS = TryContextuallyConvertToObjCId(*this, From);
Fariborz Jahaniancac49a82010-05-12 23:29:11 +00003320 if (!ICS.isBad())
3321 return PerformImplicitConversion(From, Ty, ICS, AA_Converting);
3322 return true;
3323}
Douglas Gregor5fb53972009-01-14 15:45:31 +00003324
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003325/// \brief Attempt to convert the given expression to an integral or
3326/// enumeration type.
3327///
3328/// This routine will attempt to convert an expression of class type to an
3329/// integral or enumeration type, if that class type only has a single
3330/// conversion to an integral or enumeration type.
3331///
Douglas Gregor4799d032010-06-30 00:20:43 +00003332/// \param Loc The source location of the construct that requires the
3333/// conversion.
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003334///
Douglas Gregor4799d032010-06-30 00:20:43 +00003335/// \param FromE The expression we're converting from.
3336///
3337/// \param NotIntDiag The diagnostic to be emitted if the expression does not
3338/// have integral or enumeration type.
3339///
3340/// \param IncompleteDiag The diagnostic to be emitted if the expression has
3341/// incomplete class type.
3342///
3343/// \param ExplicitConvDiag The diagnostic to be emitted if we're calling an
3344/// explicit conversion function (because no implicit conversion functions
3345/// were available). This is a recovery mode.
3346///
3347/// \param ExplicitConvNote The note to be emitted with \p ExplicitConvDiag,
3348/// showing which conversion was picked.
3349///
3350/// \param AmbigDiag The diagnostic to be emitted if there is more than one
3351/// conversion function that could convert to integral or enumeration type.
3352///
3353/// \param AmbigNote The note to be emitted with \p AmbigDiag for each
3354/// usable conversion function.
3355///
3356/// \param ConvDiag The diagnostic to be emitted if we are calling a conversion
3357/// function, which may be an extension in this case.
3358///
3359/// \returns The expression, converted to an integral or enumeration type if
3360/// successful.
John McCalldadc5752010-08-24 06:29:42 +00003361ExprResult
John McCallb268a282010-08-23 23:25:46 +00003362Sema::ConvertToIntegralOrEnumerationType(SourceLocation Loc, Expr *From,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003363 const PartialDiagnostic &NotIntDiag,
3364 const PartialDiagnostic &IncompleteDiag,
3365 const PartialDiagnostic &ExplicitConvDiag,
3366 const PartialDiagnostic &ExplicitConvNote,
3367 const PartialDiagnostic &AmbigDiag,
Douglas Gregor4799d032010-06-30 00:20:43 +00003368 const PartialDiagnostic &AmbigNote,
3369 const PartialDiagnostic &ConvDiag) {
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003370 // We can't perform any more checking for type-dependent expressions.
3371 if (From->isTypeDependent())
John McCallb268a282010-08-23 23:25:46 +00003372 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003373
3374 // If the expression already has integral or enumeration type, we're golden.
3375 QualType T = From->getType();
3376 if (T->isIntegralOrEnumerationType())
John McCallb268a282010-08-23 23:25:46 +00003377 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003378
3379 // FIXME: Check for missing '()' if T is a function type?
3380
3381 // If we don't have a class type in C++, there's no way we can get an
3382 // expression of integral or enumeration type.
3383 const RecordType *RecordTy = T->getAs<RecordType>();
3384 if (!RecordTy || !getLangOptions().CPlusPlus) {
3385 Diag(Loc, NotIntDiag)
3386 << T << From->getSourceRange();
John McCallb268a282010-08-23 23:25:46 +00003387 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003388 }
3389
3390 // We must have a complete class type.
3391 if (RequireCompleteType(Loc, T, IncompleteDiag))
John McCallb268a282010-08-23 23:25:46 +00003392 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003393
3394 // Look for a conversion to an integral or enumeration type.
3395 UnresolvedSet<4> ViableConversions;
3396 UnresolvedSet<4> ExplicitConversions;
3397 const UnresolvedSetImpl *Conversions
3398 = cast<CXXRecordDecl>(RecordTy->getDecl())->getVisibleConversionFunctions();
3399
3400 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
3401 E = Conversions->end();
3402 I != E;
3403 ++I) {
3404 if (CXXConversionDecl *Conversion
3405 = dyn_cast<CXXConversionDecl>((*I)->getUnderlyingDecl()))
3406 if (Conversion->getConversionType().getNonReferenceType()
3407 ->isIntegralOrEnumerationType()) {
3408 if (Conversion->isExplicit())
3409 ExplicitConversions.addDecl(I.getDecl(), I.getAccess());
3410 else
3411 ViableConversions.addDecl(I.getDecl(), I.getAccess());
3412 }
3413 }
3414
3415 switch (ViableConversions.size()) {
3416 case 0:
3417 if (ExplicitConversions.size() == 1) {
3418 DeclAccessPair Found = ExplicitConversions[0];
3419 CXXConversionDecl *Conversion
3420 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3421
3422 // The user probably meant to invoke the given explicit
3423 // conversion; use it.
3424 QualType ConvTy
3425 = Conversion->getConversionType().getNonReferenceType();
3426 std::string TypeStr;
3427 ConvTy.getAsStringInternal(TypeStr, Context.PrintingPolicy);
3428
3429 Diag(Loc, ExplicitConvDiag)
3430 << T << ConvTy
3431 << FixItHint::CreateInsertion(From->getLocStart(),
3432 "static_cast<" + TypeStr + ">(")
3433 << FixItHint::CreateInsertion(PP.getLocForEndOfToken(From->getLocEnd()),
3434 ")");
3435 Diag(Conversion->getLocation(), ExplicitConvNote)
3436 << ConvTy->isEnumeralType() << ConvTy;
3437
3438 // If we aren't in a SFINAE context, build a call to the
3439 // explicit conversion function.
3440 if (isSFINAEContext())
3441 return ExprError();
3442
3443 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor668443e2011-01-20 00:18:04 +00003444 ExprResult Result = BuildCXXMemberCallExpr(From, Found, Conversion);
3445 if (Result.isInvalid())
3446 return ExprError();
3447
3448 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003449 }
3450
3451 // We'll complain below about a non-integral condition type.
3452 break;
3453
3454 case 1: {
3455 // Apply this conversion.
3456 DeclAccessPair Found = ViableConversions[0];
3457 CheckMemberOperatorAccess(From->getExprLoc(), From, 0, Found);
Douglas Gregor4799d032010-06-30 00:20:43 +00003458
3459 CXXConversionDecl *Conversion
3460 = cast<CXXConversionDecl>(Found->getUnderlyingDecl());
3461 QualType ConvTy
3462 = Conversion->getConversionType().getNonReferenceType();
3463 if (ConvDiag.getDiagID()) {
3464 if (isSFINAEContext())
3465 return ExprError();
3466
3467 Diag(Loc, ConvDiag)
3468 << T << ConvTy->isEnumeralType() << ConvTy << From->getSourceRange();
3469 }
3470
Douglas Gregor668443e2011-01-20 00:18:04 +00003471 ExprResult Result = BuildCXXMemberCallExpr(From, Found,
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003472 cast<CXXConversionDecl>(Found->getUnderlyingDecl()));
Douglas Gregor668443e2011-01-20 00:18:04 +00003473 if (Result.isInvalid())
3474 return ExprError();
3475
3476 From = Result.get();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003477 break;
3478 }
3479
3480 default:
3481 Diag(Loc, AmbigDiag)
3482 << T << From->getSourceRange();
3483 for (unsigned I = 0, N = ViableConversions.size(); I != N; ++I) {
3484 CXXConversionDecl *Conv
3485 = cast<CXXConversionDecl>(ViableConversions[I]->getUnderlyingDecl());
3486 QualType ConvTy = Conv->getConversionType().getNonReferenceType();
3487 Diag(Conv->getLocation(), AmbigNote)
3488 << ConvTy->isEnumeralType() << ConvTy;
3489 }
John McCallb268a282010-08-23 23:25:46 +00003490 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003491 }
3492
Douglas Gregor5823da32010-06-29 23:25:20 +00003493 if (!From->getType()->isIntegralOrEnumerationType())
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003494 Diag(Loc, NotIntDiag)
3495 << From->getType() << From->getSourceRange();
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003496
John McCallb268a282010-08-23 23:25:46 +00003497 return Owned(From);
Douglas Gregorf4ea7252010-06-29 23:17:37 +00003498}
3499
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003500/// AddOverloadCandidate - Adds the given function to the set of
Douglas Gregor2fe98832008-11-03 19:09:14 +00003501/// candidate functions, using the given function call arguments. If
3502/// @p SuppressUserConversions, then don't allow user-defined
3503/// conversions via constructors or conversion operators.
Douglas Gregorcabea402009-09-22 15:41:20 +00003504///
3505/// \para PartialOverloading true if we are performing "partial" overloading
3506/// based on an incomplete set of function arguments. This feature is used by
3507/// code completion.
Mike Stump11289f42009-09-09 15:08:12 +00003508void
3509Sema::AddOverloadCandidate(FunctionDecl *Function,
John McCalla0296f72010-03-19 07:35:19 +00003510 DeclAccessPair FoundDecl,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003511 Expr **Args, unsigned NumArgs,
Douglas Gregor2fe98832008-11-03 19:09:14 +00003512 OverloadCandidateSet& CandidateSet,
Sebastian Redl42e92c42009-04-12 17:16:29 +00003513 bool SuppressUserConversions,
Douglas Gregorcabea402009-09-22 15:41:20 +00003514 bool PartialOverloading) {
Mike Stump11289f42009-09-09 15:08:12 +00003515 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003516 = dyn_cast<FunctionProtoType>(Function->getType()->getAs<FunctionType>());
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003517 assert(Proto && "Functions without a prototype cannot be overloaded");
Mike Stump11289f42009-09-09 15:08:12 +00003518 assert(!Function->getDescribedFunctionTemplate() &&
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003519 "Use AddTemplateOverloadCandidate for function templates");
Mike Stump11289f42009-09-09 15:08:12 +00003520
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003521 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Function)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00003522 if (!isa<CXXConstructorDecl>(Method)) {
3523 // If we get here, it's because we're calling a member function
3524 // that is named without a member access expression (e.g.,
3525 // "this->f") that was either written explicitly or created
3526 // implicitly. This can happen with a qualified call to a member
John McCall6e9f8f62009-12-03 04:06:58 +00003527 // function, e.g., X::f(). We use an empty type for the implied
3528 // object argument (C++ [over.call.func]p3), and the acting context
3529 // is irrelevant.
John McCalla0296f72010-03-19 07:35:19 +00003530 AddMethodCandidate(Method, FoundDecl, Method->getParent(),
John McCall6e9f8f62009-12-03 04:06:58 +00003531 QualType(), Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003532 SuppressUserConversions);
Sebastian Redl1a99f442009-04-16 17:51:27 +00003533 return;
3534 }
3535 // We treat a constructor like a non-member function, since its object
3536 // argument doesn't participate in overload resolution.
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003537 }
3538
Douglas Gregorff7028a2009-11-13 23:59:09 +00003539 if (!CandidateSet.isNewCandidate(Function))
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003540 return;
Douglas Gregorffe14e32009-11-14 01:20:54 +00003541
Douglas Gregor27381f32009-11-23 12:27:39 +00003542 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003543 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003544
Douglas Gregorffe14e32009-11-14 01:20:54 +00003545 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Function)){
3546 // C++ [class.copy]p3:
3547 // A member function template is never instantiated to perform the copy
3548 // of a class object to an object of its class type.
3549 QualType ClassType = Context.getTypeDeclType(Constructor->getParent());
3550 if (NumArgs == 1 &&
Douglas Gregorbd6b17f2010-11-08 17:16:59 +00003551 Constructor->isSpecializationCopyingObject() &&
Douglas Gregor901e7172010-02-21 18:30:38 +00003552 (Context.hasSameUnqualifiedType(ClassType, Args[0]->getType()) ||
3553 IsDerivedFrom(Args[0]->getType(), ClassType)))
Douglas Gregorffe14e32009-11-14 01:20:54 +00003554 return;
3555 }
3556
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003557 // Add this candidate
3558 CandidateSet.push_back(OverloadCandidate());
3559 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003560 Candidate.FoundDecl = FoundDecl;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003561 Candidate.Function = Function;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003562 Candidate.Viable = true;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003563 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003564 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003565 Candidate.ExplicitCallArguments = NumArgs;
3566
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003567 unsigned NumArgsInProto = Proto->getNumArgs();
3568
3569 // (C++ 13.3.2p2): A candidate function having fewer than m
3570 // parameters is viable only if it has an ellipsis in its parameter
3571 // list (8.3.5).
Douglas Gregor2a920012009-09-23 14:56:09 +00003572 if ((NumArgs + (PartialOverloading && NumArgs)) > NumArgsInProto &&
3573 !Proto->isVariadic()) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003574 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003575 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003576 return;
3577 }
3578
3579 // (C++ 13.3.2p2): A candidate function having more than m parameters
3580 // is viable only if the (m+1)st parameter has a default argument
3581 // (8.3.6). For the purposes of overload resolution, the
3582 // parameter list is truncated on the right, so that there are
3583 // exactly m parameters.
3584 unsigned MinRequiredArgs = Function->getMinRequiredArguments();
Douglas Gregorcabea402009-09-22 15:41:20 +00003585 if (NumArgs < MinRequiredArgs && !PartialOverloading) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003586 // Not enough arguments.
3587 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003588 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003589 return;
3590 }
3591
3592 // Determine the implicit conversion sequences for each of the
3593 // arguments.
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003594 Candidate.Conversions.resize(NumArgs);
3595 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3596 if (ArgIdx < NumArgsInProto) {
3597 // (C++ 13.3.2p3): for F to be a viable function, there shall
3598 // exist for each argument an implicit conversion sequence
3599 // (13.3.3.1) that converts that argument to the corresponding
3600 // parameter of F.
3601 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003602 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003603 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorb05275a2010-04-16 17:41:49 +00003604 SuppressUserConversions,
Anders Carlsson20d13322009-08-27 17:37:39 +00003605 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003606 if (Candidate.Conversions[ArgIdx].isBad()) {
3607 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003608 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCall0d1da222010-01-12 00:44:57 +00003609 break;
Douglas Gregor436424c2008-11-18 23:14:02 +00003610 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003611 } else {
3612 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3613 // argument for which there is no corresponding parameter is
3614 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003615 Candidate.Conversions[ArgIdx].setEllipsis();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00003616 }
3617 }
3618}
3619
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003620/// \brief Add all of the function declarations in the given function set to
3621/// the overload canddiate set.
John McCall4c4c1df2010-01-26 03:27:55 +00003622void Sema::AddFunctionCandidates(const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003623 Expr **Args, unsigned NumArgs,
3624 OverloadCandidateSet& CandidateSet,
3625 bool SuppressUserConversions) {
John McCall4c4c1df2010-01-26 03:27:55 +00003626 for (UnresolvedSetIterator F = Fns.begin(), E = Fns.end(); F != E; ++F) {
John McCalla0296f72010-03-19 07:35:19 +00003627 NamedDecl *D = F.getDecl()->getUnderlyingDecl();
3628 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003629 if (isa<CXXMethodDecl>(FD) && !cast<CXXMethodDecl>(FD)->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003630 AddMethodCandidate(cast<CXXMethodDecl>(FD), F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003631 cast<CXXMethodDecl>(FD)->getParent(),
3632 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003633 CandidateSet, SuppressUserConversions);
3634 else
John McCalla0296f72010-03-19 07:35:19 +00003635 AddOverloadCandidate(FD, F.getPair(), Args, NumArgs, CandidateSet,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003636 SuppressUserConversions);
3637 } else {
John McCalla0296f72010-03-19 07:35:19 +00003638 FunctionTemplateDecl *FunTmpl = cast<FunctionTemplateDecl>(D);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003639 if (isa<CXXMethodDecl>(FunTmpl->getTemplatedDecl()) &&
3640 !cast<CXXMethodDecl>(FunTmpl->getTemplatedDecl())->isStatic())
John McCalla0296f72010-03-19 07:35:19 +00003641 AddMethodTemplateCandidate(FunTmpl, F.getPair(),
John McCall6e9f8f62009-12-03 04:06:58 +00003642 cast<CXXRecordDecl>(FunTmpl->getDeclContext()),
John McCall6b51f282009-11-23 01:53:49 +00003643 /*FIXME: explicit args */ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003644 Args[0]->getType(), Args + 1, NumArgs - 1,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003645 CandidateSet,
Douglas Gregor15448f82009-06-27 21:05:07 +00003646 SuppressUserConversions);
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003647 else
John McCalla0296f72010-03-19 07:35:19 +00003648 AddTemplateOverloadCandidate(FunTmpl, F.getPair(),
John McCall6b51f282009-11-23 01:53:49 +00003649 /*FIXME: explicit args */ 0,
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003650 Args, NumArgs, CandidateSet,
3651 SuppressUserConversions);
3652 }
Douglas Gregor15448f82009-06-27 21:05:07 +00003653 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00003654}
3655
John McCallf0f1cf02009-11-17 07:50:12 +00003656/// AddMethodCandidate - Adds a named decl (which is some kind of
3657/// method) as a method candidate to the given overload set.
John McCalla0296f72010-03-19 07:35:19 +00003658void Sema::AddMethodCandidate(DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003659 QualType ObjectType,
John McCallf0f1cf02009-11-17 07:50:12 +00003660 Expr **Args, unsigned NumArgs,
3661 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003662 bool SuppressUserConversions) {
John McCalla0296f72010-03-19 07:35:19 +00003663 NamedDecl *Decl = FoundDecl.getDecl();
John McCall6e9f8f62009-12-03 04:06:58 +00003664 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(Decl->getDeclContext());
John McCallf0f1cf02009-11-17 07:50:12 +00003665
3666 if (isa<UsingShadowDecl>(Decl))
3667 Decl = cast<UsingShadowDecl>(Decl)->getTargetDecl();
3668
3669 if (FunctionTemplateDecl *TD = dyn_cast<FunctionTemplateDecl>(Decl)) {
3670 assert(isa<CXXMethodDecl>(TD->getTemplatedDecl()) &&
3671 "Expected a member function template");
John McCalla0296f72010-03-19 07:35:19 +00003672 AddMethodTemplateCandidate(TD, FoundDecl, ActingContext,
3673 /*ExplicitArgs*/ 0,
John McCall6e9f8f62009-12-03 04:06:58 +00003674 ObjectType, Args, NumArgs,
John McCallf0f1cf02009-11-17 07:50:12 +00003675 CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003676 SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003677 } else {
John McCalla0296f72010-03-19 07:35:19 +00003678 AddMethodCandidate(cast<CXXMethodDecl>(Decl), FoundDecl, ActingContext,
John McCall6e9f8f62009-12-03 04:06:58 +00003679 ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003680 CandidateSet, SuppressUserConversions);
John McCallf0f1cf02009-11-17 07:50:12 +00003681 }
3682}
3683
Douglas Gregor436424c2008-11-18 23:14:02 +00003684/// AddMethodCandidate - Adds the given C++ member function to the set
3685/// of candidate functions, using the given function call arguments
3686/// and the object argument (@c Object). For example, in a call
3687/// @c o.f(a1,a2), @c Object will contain @c o and @c Args will contain
3688/// both @c a1 and @c a2. If @p SuppressUserConversions, then don't
3689/// allow user-defined conversions via constructors or conversion
Douglas Gregorf1e46692010-04-16 17:33:27 +00003690/// operators.
Mike Stump11289f42009-09-09 15:08:12 +00003691void
John McCalla0296f72010-03-19 07:35:19 +00003692Sema::AddMethodCandidate(CXXMethodDecl *Method, DeclAccessPair FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003693 CXXRecordDecl *ActingContext, QualType ObjectType,
3694 Expr **Args, unsigned NumArgs,
Douglas Gregor436424c2008-11-18 23:14:02 +00003695 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003696 bool SuppressUserConversions) {
Mike Stump11289f42009-09-09 15:08:12 +00003697 const FunctionProtoType* Proto
John McCall9dd450b2009-09-21 23:43:11 +00003698 = dyn_cast<FunctionProtoType>(Method->getType()->getAs<FunctionType>());
Douglas Gregor436424c2008-11-18 23:14:02 +00003699 assert(Proto && "Methods without a prototype cannot be overloaded");
Sebastian Redl1a99f442009-04-16 17:51:27 +00003700 assert(!isa<CXXConstructorDecl>(Method) &&
3701 "Use AddOverloadCandidate for constructors");
Douglas Gregor436424c2008-11-18 23:14:02 +00003702
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003703 if (!CandidateSet.isNewCandidate(Method))
3704 return;
3705
Douglas Gregor27381f32009-11-23 12:27:39 +00003706 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003707 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003708
Douglas Gregor436424c2008-11-18 23:14:02 +00003709 // Add this candidate
3710 CandidateSet.push_back(OverloadCandidate());
3711 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003712 Candidate.FoundDecl = FoundDecl;
Douglas Gregor436424c2008-11-18 23:14:02 +00003713 Candidate.Function = Method;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003714 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003715 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003716 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor436424c2008-11-18 23:14:02 +00003717
3718 unsigned NumArgsInProto = Proto->getNumArgs();
3719
3720 // (C++ 13.3.2p2): A candidate function having fewer than m
3721 // parameters is viable only if it has an ellipsis in its parameter
3722 // list (8.3.5).
3723 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
3724 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003725 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003726 return;
3727 }
3728
3729 // (C++ 13.3.2p2): A candidate function having more than m parameters
3730 // is viable only if the (m+1)st parameter has a default argument
3731 // (8.3.6). For the purposes of overload resolution, the
3732 // parameter list is truncated on the right, so that there are
3733 // exactly m parameters.
3734 unsigned MinRequiredArgs = Method->getMinRequiredArguments();
3735 if (NumArgs < MinRequiredArgs) {
3736 // Not enough arguments.
3737 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003738 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregor436424c2008-11-18 23:14:02 +00003739 return;
3740 }
3741
3742 Candidate.Viable = true;
3743 Candidate.Conversions.resize(NumArgs + 1);
3744
John McCall6e9f8f62009-12-03 04:06:58 +00003745 if (Method->isStatic() || ObjectType.isNull())
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003746 // The implicit object argument is ignored.
3747 Candidate.IgnoreObjectArgument = true;
3748 else {
3749 // Determine the implicit conversion sequence for the object
3750 // parameter.
John McCall6e9f8f62009-12-03 04:06:58 +00003751 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003752 = TryObjectArgumentInitialization(*this, ObjectType, Method,
3753 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00003754 if (Candidate.Conversions[0].isBad()) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003755 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003756 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003757 return;
3758 }
Douglas Gregor436424c2008-11-18 23:14:02 +00003759 }
3760
3761 // Determine the implicit conversion sequences for each of the
3762 // arguments.
3763 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
3764 if (ArgIdx < NumArgsInProto) {
3765 // (C++ 13.3.2p3): for F to be a viable function, there shall
3766 // exist for each argument an implicit conversion sequence
3767 // (13.3.3.1) that converts that argument to the corresponding
3768 // parameter of F.
3769 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00003770 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003771 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003772 SuppressUserConversions,
Anders Carlsson228eea32009-08-28 15:33:32 +00003773 /*InOverloadResolution=*/true);
John McCall0d1da222010-01-12 00:44:57 +00003774 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregor436424c2008-11-18 23:14:02 +00003775 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003776 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00003777 break;
3778 }
3779 } else {
3780 // (C++ 13.3.2p2): For the purposes of overload resolution, any
3781 // argument for which there is no corresponding parameter is
3782 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00003783 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregor436424c2008-11-18 23:14:02 +00003784 }
3785 }
3786}
Douglas Gregor3626a5c2010-05-08 17:41:32 +00003787
Douglas Gregor97628d62009-08-21 00:16:32 +00003788/// \brief Add a C++ member function template as a candidate to the candidate
3789/// set, using template argument deduction to produce an appropriate member
3790/// function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003791void
Douglas Gregor97628d62009-08-21 00:16:32 +00003792Sema::AddMethodTemplateCandidate(FunctionTemplateDecl *MethodTmpl,
John McCalla0296f72010-03-19 07:35:19 +00003793 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003794 CXXRecordDecl *ActingContext,
John McCall6b51f282009-11-23 01:53:49 +00003795 const TemplateArgumentListInfo *ExplicitTemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00003796 QualType ObjectType,
3797 Expr **Args, unsigned NumArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003798 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003799 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003800 if (!CandidateSet.isNewCandidate(MethodTmpl))
3801 return;
3802
Douglas Gregor97628d62009-08-21 00:16:32 +00003803 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003804 // In each case where a candidate is a function template, candidate
Douglas Gregor97628d62009-08-21 00:16:32 +00003805 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003806 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregor97628d62009-08-21 00:16:32 +00003807 // candidate functions in the usual way.113) A given name can refer to one
3808 // or more function templates and also to a set of overloaded non-template
3809 // functions. In such a case, the candidate functions generated from each
3810 // function template are combined with the set of non-template candidate
3811 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003812 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor97628d62009-08-21 00:16:32 +00003813 FunctionDecl *Specialization = 0;
3814 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003815 = DeduceTemplateArguments(MethodTmpl, ExplicitTemplateArgs,
Douglas Gregor97628d62009-08-21 00:16:32 +00003816 Args, NumArgs, Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003817 CandidateSet.push_back(OverloadCandidate());
3818 OverloadCandidate &Candidate = CandidateSet.back();
3819 Candidate.FoundDecl = FoundDecl;
3820 Candidate.Function = MethodTmpl->getTemplatedDecl();
3821 Candidate.Viable = false;
3822 Candidate.FailureKind = ovl_fail_bad_deduction;
3823 Candidate.IsSurrogate = false;
3824 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003825 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003826 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3827 Info);
3828 return;
3829 }
Mike Stump11289f42009-09-09 15:08:12 +00003830
Douglas Gregor97628d62009-08-21 00:16:32 +00003831 // Add the function template specialization produced by template argument
3832 // deduction as a candidate.
3833 assert(Specialization && "Missing member function template specialization?");
Mike Stump11289f42009-09-09 15:08:12 +00003834 assert(isa<CXXMethodDecl>(Specialization) &&
Douglas Gregor97628d62009-08-21 00:16:32 +00003835 "Specialization is not a member function?");
John McCalla0296f72010-03-19 07:35:19 +00003836 AddMethodCandidate(cast<CXXMethodDecl>(Specialization), FoundDecl,
John McCallb89836b2010-01-26 01:37:31 +00003837 ActingContext, ObjectType, Args, NumArgs,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003838 CandidateSet, SuppressUserConversions);
Douglas Gregor97628d62009-08-21 00:16:32 +00003839}
3840
Douglas Gregor05155d82009-08-21 23:19:43 +00003841/// \brief Add a C++ function template specialization as a candidate
3842/// in the candidate set, using template argument deduction to produce
3843/// an appropriate function template specialization.
Mike Stump11289f42009-09-09 15:08:12 +00003844void
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003845Sema::AddTemplateOverloadCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00003846 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00003847 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003848 Expr **Args, unsigned NumArgs,
3849 OverloadCandidateSet& CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003850 bool SuppressUserConversions) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003851 if (!CandidateSet.isNewCandidate(FunctionTemplate))
3852 return;
3853
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003854 // C++ [over.match.funcs]p7:
Mike Stump11289f42009-09-09 15:08:12 +00003855 // In each case where a candidate is a function template, candidate
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003856 // function template specializations are generated using template argument
Mike Stump11289f42009-09-09 15:08:12 +00003857 // deduction (14.8.3, 14.8.2). Those candidates are then handled as
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003858 // candidate functions in the usual way.113) A given name can refer to one
3859 // or more function templates and also to a set of overloaded non-template
3860 // functions. In such a case, the candidate functions generated from each
3861 // function template are combined with the set of non-template candidate
3862 // functions.
John McCallbc077cf2010-02-08 23:07:23 +00003863 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003864 FunctionDecl *Specialization = 0;
3865 if (TemplateDeductionResult Result
John McCall6b51f282009-11-23 01:53:49 +00003866 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00003867 Args, NumArgs, Specialization, Info)) {
John McCalld681c392009-12-16 08:11:27 +00003868 CandidateSet.push_back(OverloadCandidate());
3869 OverloadCandidate &Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003870 Candidate.FoundDecl = FoundDecl;
John McCalld681c392009-12-16 08:11:27 +00003871 Candidate.Function = FunctionTemplate->getTemplatedDecl();
3872 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003873 Candidate.FailureKind = ovl_fail_bad_deduction;
John McCalld681c392009-12-16 08:11:27 +00003874 Candidate.IsSurrogate = false;
3875 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00003876 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00003877 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
3878 Info);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003879 return;
3880 }
Mike Stump11289f42009-09-09 15:08:12 +00003881
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003882 // Add the function template specialization produced by template argument
3883 // deduction as a candidate.
3884 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00003885 AddOverloadCandidate(Specialization, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorf1e46692010-04-16 17:33:27 +00003886 SuppressUserConversions);
Douglas Gregorad3f2fc2009-06-25 22:08:12 +00003887}
Mike Stump11289f42009-09-09 15:08:12 +00003888
Douglas Gregora1f013e2008-11-07 22:36:19 +00003889/// AddConversionCandidate - Add a C++ conversion function as a
Mike Stump11289f42009-09-09 15:08:12 +00003890/// candidate in the candidate set (C++ [over.match.conv],
Douglas Gregora1f013e2008-11-07 22:36:19 +00003891/// C++ [over.match.copy]). From is the expression we're converting from,
Mike Stump11289f42009-09-09 15:08:12 +00003892/// and ToType is the type that we're eventually trying to convert to
Douglas Gregora1f013e2008-11-07 22:36:19 +00003893/// (which may or may not be the same type as the type that the
3894/// conversion function produces).
3895void
3896Sema::AddConversionCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00003897 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00003898 CXXRecordDecl *ActingContext,
Douglas Gregora1f013e2008-11-07 22:36:19 +00003899 Expr *From, QualType ToType,
3900 OverloadCandidateSet& CandidateSet) {
Douglas Gregor05155d82009-08-21 23:19:43 +00003901 assert(!Conversion->getDescribedFunctionTemplate() &&
3902 "Conversion function templates use AddTemplateConversionCandidate");
Douglas Gregor5ab11652010-04-17 22:01:05 +00003903 QualType ConvType = Conversion->getConversionType().getNonReferenceType();
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00003904 if (!CandidateSet.isNewCandidate(Conversion))
3905 return;
3906
Douglas Gregor27381f32009-11-23 12:27:39 +00003907 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00003908 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00003909
Douglas Gregora1f013e2008-11-07 22:36:19 +00003910 // Add this candidate
3911 CandidateSet.push_back(OverloadCandidate());
3912 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00003913 Candidate.FoundDecl = FoundDecl;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003914 Candidate.Function = Conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00003915 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00003916 Candidate.IgnoreObjectArgument = false;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003917 Candidate.FinalConversion.setAsIdentityConversion();
Douglas Gregor5ab11652010-04-17 22:01:05 +00003918 Candidate.FinalConversion.setFromType(ConvType);
Douglas Gregor3edc4d52010-01-27 03:51:04 +00003919 Candidate.FinalConversion.setAllToTypes(ToType);
Douglas Gregora1f013e2008-11-07 22:36:19 +00003920 Candidate.Viable = true;
3921 Candidate.Conversions.resize(1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00003922 Candidate.ExplicitCallArguments = 1;
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003923
Douglas Gregor6affc782010-08-19 15:37:02 +00003924 // C++ [over.match.funcs]p4:
3925 // For conversion functions, the function is considered to be a member of
3926 // the class of the implicit implied object argument for the purpose of
3927 // defining the type of the implicit object parameter.
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003928 //
3929 // Determine the implicit conversion sequence for the implicit
3930 // object parameter.
3931 QualType ImplicitParamType = From->getType();
3932 if (const PointerType *FromPtrType = ImplicitParamType->getAs<PointerType>())
3933 ImplicitParamType = FromPtrType->getPointeeType();
3934 CXXRecordDecl *ConversionContext
3935 = cast<CXXRecordDecl>(ImplicitParamType->getAs<RecordType>()->getDecl());
3936
3937 Candidate.Conversions[0]
John McCall5c32be02010-08-24 20:38:10 +00003938 = TryObjectArgumentInitialization(*this, From->getType(), Conversion,
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003939 ConversionContext);
3940
John McCall0d1da222010-01-12 00:44:57 +00003941 if (Candidate.Conversions[0].isBad()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003942 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00003943 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00003944 return;
3945 }
Douglas Gregorc9ed4682010-08-19 15:57:50 +00003946
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003947 // We won't go through a user-define type conversion function to convert a
3948 // derived to base as such conversions are given Conversion Rank. They only
3949 // go through a copy constructor. 13.3.3.1.2-p4 [over.ics.user]
3950 QualType FromCanon
3951 = Context.getCanonicalType(From->getType().getUnqualifiedType());
3952 QualType ToCanon = Context.getCanonicalType(ToType).getUnqualifiedType();
3953 if (FromCanon == ToCanon || IsDerivedFrom(FromCanon, ToCanon)) {
3954 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00003955 Candidate.FailureKind = ovl_fail_trivial_conversion;
Fariborz Jahanian996a6aa2009-10-19 19:18:20 +00003956 return;
3957 }
3958
Douglas Gregora1f013e2008-11-07 22:36:19 +00003959 // To determine what the conversion from the result of calling the
3960 // conversion function to the type we're eventually trying to
3961 // convert to (ToType), we need to synthesize a call to the
3962 // conversion function and attempt copy initialization from it. This
3963 // makes sure that we get the right semantics with respect to
3964 // lvalues/rvalues and the type. Fortunately, we can allocate this
3965 // call on the stack and we don't need its arguments to be
3966 // well-formed.
Mike Stump11289f42009-09-09 15:08:12 +00003967 DeclRefExpr ConversionRef(Conversion, Conversion->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00003968 VK_LValue, From->getLocStart());
John McCallcf142162010-08-07 06:22:56 +00003969 ImplicitCastExpr ConversionFn(ImplicitCastExpr::OnStack,
3970 Context.getPointerType(Conversion->getType()),
John McCalle3027922010-08-25 11:45:40 +00003971 CK_FunctionToPointerDecay,
John McCall2536c6d2010-08-25 10:28:54 +00003972 &ConversionRef, VK_RValue);
Mike Stump11289f42009-09-09 15:08:12 +00003973
Douglas Gregor72ebdab2010-11-13 19:36:57 +00003974 QualType CallResultType
3975 = Conversion->getConversionType().getNonLValueExprType(Context);
3976 if (RequireCompleteType(From->getLocStart(), CallResultType, 0)) {
3977 Candidate.Viable = false;
3978 Candidate.FailureKind = ovl_fail_bad_final_conversion;
3979 return;
3980 }
3981
John McCall7decc9e2010-11-18 06:31:45 +00003982 ExprValueKind VK = Expr::getValueKindForType(Conversion->getConversionType());
3983
Mike Stump11289f42009-09-09 15:08:12 +00003984 // Note that it is safe to allocate CallExpr on the stack here because
Ted Kremenekd7b4f402009-02-09 20:51:47 +00003985 // there are 0 arguments (i.e., nothing is allocated using ASTContext's
3986 // allocator).
John McCall7decc9e2010-11-18 06:31:45 +00003987 CallExpr Call(Context, &ConversionFn, 0, 0, CallResultType, VK,
Douglas Gregore8f080122009-11-17 21:16:22 +00003988 From->getLocStart());
Mike Stump11289f42009-09-09 15:08:12 +00003989 ImplicitConversionSequence ICS =
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00003990 TryCopyInitialization(*this, &Call, ToType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00003991 /*SuppressUserConversions=*/true,
Anders Carlsson20d13322009-08-27 17:37:39 +00003992 /*InOverloadResolution=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00003993
John McCall0d1da222010-01-12 00:44:57 +00003994 switch (ICS.getKind()) {
Douglas Gregora1f013e2008-11-07 22:36:19 +00003995 case ImplicitConversionSequence::StandardConversion:
3996 Candidate.FinalConversion = ICS.Standard;
Douglas Gregor2c326bc2010-04-12 23:42:09 +00003997
3998 // C++ [over.ics.user]p3:
3999 // If the user-defined conversion is specified by a specialization of a
4000 // conversion function template, the second standard conversion sequence
4001 // shall have exact match rank.
4002 if (Conversion->getPrimaryTemplate() &&
4003 GetConversionRank(ICS.Standard.Second) != ICR_Exact_Match) {
4004 Candidate.Viable = false;
4005 Candidate.FailureKind = ovl_fail_final_conversion_not_exact;
4006 }
4007
Douglas Gregora1f013e2008-11-07 22:36:19 +00004008 break;
4009
4010 case ImplicitConversionSequence::BadConversion:
4011 Candidate.Viable = false;
John McCallfe796dd2010-01-23 05:17:32 +00004012 Candidate.FailureKind = ovl_fail_bad_final_conversion;
Douglas Gregora1f013e2008-11-07 22:36:19 +00004013 break;
4014
4015 default:
Mike Stump11289f42009-09-09 15:08:12 +00004016 assert(false &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00004017 "Can only end up with a standard conversion sequence or failure");
4018 }
4019}
4020
Douglas Gregor05155d82009-08-21 23:19:43 +00004021/// \brief Adds a conversion function template specialization
4022/// candidate to the overload set, using template argument deduction
4023/// to deduce the template arguments of the conversion function
4024/// template from the type that we are converting to (C++
4025/// [temp.deduct.conv]).
Mike Stump11289f42009-09-09 15:08:12 +00004026void
Douglas Gregor05155d82009-08-21 23:19:43 +00004027Sema::AddTemplateConversionCandidate(FunctionTemplateDecl *FunctionTemplate,
John McCalla0296f72010-03-19 07:35:19 +00004028 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004029 CXXRecordDecl *ActingDC,
Douglas Gregor05155d82009-08-21 23:19:43 +00004030 Expr *From, QualType ToType,
4031 OverloadCandidateSet &CandidateSet) {
4032 assert(isa<CXXConversionDecl>(FunctionTemplate->getTemplatedDecl()) &&
4033 "Only conversion function templates permitted here");
4034
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004035 if (!CandidateSet.isNewCandidate(FunctionTemplate))
4036 return;
4037
John McCallbc077cf2010-02-08 23:07:23 +00004038 TemplateDeductionInfo Info(Context, CandidateSet.getLocation());
Douglas Gregor05155d82009-08-21 23:19:43 +00004039 CXXConversionDecl *Specialization = 0;
4040 if (TemplateDeductionResult Result
Mike Stump11289f42009-09-09 15:08:12 +00004041 = DeduceTemplateArguments(FunctionTemplate, ToType,
Douglas Gregor05155d82009-08-21 23:19:43 +00004042 Specialization, Info)) {
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004043 CandidateSet.push_back(OverloadCandidate());
4044 OverloadCandidate &Candidate = CandidateSet.back();
4045 Candidate.FoundDecl = FoundDecl;
4046 Candidate.Function = FunctionTemplate->getTemplatedDecl();
4047 Candidate.Viable = false;
4048 Candidate.FailureKind = ovl_fail_bad_deduction;
4049 Candidate.IsSurrogate = false;
4050 Candidate.IgnoreObjectArgument = false;
Douglas Gregor6edd9772011-01-19 23:54:39 +00004051 Candidate.ExplicitCallArguments = 1;
Douglas Gregor90cf2c92010-05-08 20:18:54 +00004052 Candidate.DeductionFailure = MakeDeductionFailureInfo(Context, Result,
4053 Info);
Douglas Gregor05155d82009-08-21 23:19:43 +00004054 return;
4055 }
Mike Stump11289f42009-09-09 15:08:12 +00004056
Douglas Gregor05155d82009-08-21 23:19:43 +00004057 // Add the conversion function template specialization produced by
4058 // template argument deduction as a candidate.
4059 assert(Specialization && "Missing function template specialization?");
John McCalla0296f72010-03-19 07:35:19 +00004060 AddConversionCandidate(Specialization, FoundDecl, ActingDC, From, ToType,
John McCallb89836b2010-01-26 01:37:31 +00004061 CandidateSet);
Douglas Gregor05155d82009-08-21 23:19:43 +00004062}
4063
Douglas Gregorab7897a2008-11-19 22:57:39 +00004064/// AddSurrogateCandidate - Adds a "surrogate" candidate function that
4065/// converts the given @c Object to a function pointer via the
4066/// conversion function @c Conversion, and then attempts to call it
4067/// with the given arguments (C++ [over.call.object]p2-4). Proto is
4068/// the type of function that we'll eventually be calling.
4069void Sema::AddSurrogateCandidate(CXXConversionDecl *Conversion,
John McCalla0296f72010-03-19 07:35:19 +00004070 DeclAccessPair FoundDecl,
John McCall6e9f8f62009-12-03 04:06:58 +00004071 CXXRecordDecl *ActingContext,
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004072 const FunctionProtoType *Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00004073 QualType ObjectType,
4074 Expr **Args, unsigned NumArgs,
Douglas Gregorab7897a2008-11-19 22:57:39 +00004075 OverloadCandidateSet& CandidateSet) {
Douglas Gregor5b0f2a22009-09-28 04:47:19 +00004076 if (!CandidateSet.isNewCandidate(Conversion))
4077 return;
4078
Douglas Gregor27381f32009-11-23 12:27:39 +00004079 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004080 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004081
Douglas Gregorab7897a2008-11-19 22:57:39 +00004082 CandidateSet.push_back(OverloadCandidate());
4083 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004084 Candidate.FoundDecl = FoundDecl;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004085 Candidate.Function = 0;
4086 Candidate.Surrogate = Conversion;
4087 Candidate.Viable = true;
4088 Candidate.IsSurrogate = true;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004089 Candidate.IgnoreObjectArgument = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004090 Candidate.Conversions.resize(NumArgs + 1);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004091 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004092
4093 // Determine the implicit conversion sequence for the implicit
4094 // object parameter.
Mike Stump11289f42009-09-09 15:08:12 +00004095 ImplicitConversionSequence ObjectInit
John McCall5c32be02010-08-24 20:38:10 +00004096 = TryObjectArgumentInitialization(*this, ObjectType, Conversion,
4097 ActingContext);
John McCall0d1da222010-01-12 00:44:57 +00004098 if (ObjectInit.isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004099 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004100 Candidate.FailureKind = ovl_fail_bad_conversion;
John McCallfe796dd2010-01-23 05:17:32 +00004101 Candidate.Conversions[0] = ObjectInit;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004102 return;
4103 }
4104
4105 // The first conversion is actually a user-defined conversion whose
4106 // first conversion is ObjectInit's standard conversion (which is
4107 // effectively a reference binding). Record it as such.
John McCall0d1da222010-01-12 00:44:57 +00004108 Candidate.Conversions[0].setUserDefined();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004109 Candidate.Conversions[0].UserDefined.Before = ObjectInit.Standard;
Fariborz Jahanian55824512009-11-06 00:23:08 +00004110 Candidate.Conversions[0].UserDefined.EllipsisConversion = false;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004111 Candidate.Conversions[0].UserDefined.ConversionFunction = Conversion;
Douglas Gregor2bbfba02011-01-20 01:32:05 +00004112 Candidate.Conversions[0].UserDefined.FoundConversionFunction
4113 = FoundDecl.getDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004114 Candidate.Conversions[0].UserDefined.After
Douglas Gregorab7897a2008-11-19 22:57:39 +00004115 = Candidate.Conversions[0].UserDefined.Before;
4116 Candidate.Conversions[0].UserDefined.After.setAsIdentityConversion();
4117
Mike Stump11289f42009-09-09 15:08:12 +00004118 // Find the
Douglas Gregorab7897a2008-11-19 22:57:39 +00004119 unsigned NumArgsInProto = Proto->getNumArgs();
4120
4121 // (C++ 13.3.2p2): A candidate function having fewer than m
4122 // parameters is viable only if it has an ellipsis in its parameter
4123 // list (8.3.5).
4124 if (NumArgs > NumArgsInProto && !Proto->isVariadic()) {
4125 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004126 Candidate.FailureKind = ovl_fail_too_many_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004127 return;
4128 }
4129
4130 // Function types don't have any default arguments, so just check if
4131 // we have enough arguments.
4132 if (NumArgs < NumArgsInProto) {
4133 // Not enough arguments.
4134 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004135 Candidate.FailureKind = ovl_fail_too_few_arguments;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004136 return;
4137 }
4138
4139 // Determine the implicit conversion sequences for each of the
4140 // arguments.
4141 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4142 if (ArgIdx < NumArgsInProto) {
4143 // (C++ 13.3.2p3): for F to be a viable function, there shall
4144 // exist for each argument an implicit conversion sequence
4145 // (13.3.3.1) that converts that argument to the corresponding
4146 // parameter of F.
4147 QualType ParamType = Proto->getArgType(ArgIdx);
Mike Stump11289f42009-09-09 15:08:12 +00004148 Candidate.Conversions[ArgIdx + 1]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004149 = TryCopyInitialization(*this, Args[ArgIdx], ParamType,
Anders Carlsson03068aa2009-08-27 17:18:13 +00004150 /*SuppressUserConversions=*/false,
Anders Carlsson20d13322009-08-27 17:37:39 +00004151 /*InOverloadResolution=*/false);
John McCall0d1da222010-01-12 00:44:57 +00004152 if (Candidate.Conversions[ArgIdx + 1].isBad()) {
Douglas Gregorab7897a2008-11-19 22:57:39 +00004153 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004154 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregorab7897a2008-11-19 22:57:39 +00004155 break;
4156 }
4157 } else {
4158 // (C++ 13.3.2p2): For the purposes of overload resolution, any
4159 // argument for which there is no corresponding parameter is
4160 // considered to ""match the ellipsis" (C+ 13.3.3.1.3).
John McCall0d1da222010-01-12 00:44:57 +00004161 Candidate.Conversions[ArgIdx + 1].setEllipsis();
Douglas Gregorab7897a2008-11-19 22:57:39 +00004162 }
4163 }
4164}
4165
Douglas Gregor1baf54e2009-03-13 18:40:31 +00004166/// \brief Add overload candidates for overloaded operators that are
4167/// member functions.
4168///
4169/// Add the overloaded operator candidates that are member functions
4170/// for the operator Op that was used in an operator expression such
4171/// as "x Op y". , Args/NumArgs provides the operator arguments, and
4172/// CandidateSet will store the added overload candidates. (C++
4173/// [over.match.oper]).
4174void Sema::AddMemberOperatorCandidates(OverloadedOperatorKind Op,
4175 SourceLocation OpLoc,
4176 Expr **Args, unsigned NumArgs,
4177 OverloadCandidateSet& CandidateSet,
4178 SourceRange OpRange) {
Douglas Gregor436424c2008-11-18 23:14:02 +00004179 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
4180
4181 // C++ [over.match.oper]p3:
4182 // For a unary operator @ with an operand of a type whose
4183 // cv-unqualified version is T1, and for a binary operator @ with
4184 // a left operand of a type whose cv-unqualified version is T1 and
4185 // a right operand of a type whose cv-unqualified version is T2,
4186 // three sets of candidate functions, designated member
4187 // candidates, non-member candidates and built-in candidates, are
4188 // constructed as follows:
4189 QualType T1 = Args[0]->getType();
Douglas Gregor436424c2008-11-18 23:14:02 +00004190
4191 // -- If T1 is a class type, the set of member candidates is the
4192 // result of the qualified lookup of T1::operator@
4193 // (13.3.1.1.1); otherwise, the set of member candidates is
4194 // empty.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004195 if (const RecordType *T1Rec = T1->getAs<RecordType>()) {
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004196 // Complete the type if it can be completed. Otherwise, we're done.
Anders Carlsson7f84ed92009-10-09 23:51:55 +00004197 if (RequireCompleteType(OpLoc, T1, PDiag()))
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004198 return;
Mike Stump11289f42009-09-09 15:08:12 +00004199
John McCall27b18f82009-11-17 02:14:36 +00004200 LookupResult Operators(*this, OpName, OpLoc, LookupOrdinaryName);
4201 LookupQualifiedName(Operators, T1Rec->getDecl());
4202 Operators.suppressDiagnostics();
4203
Mike Stump11289f42009-09-09 15:08:12 +00004204 for (LookupResult::iterator Oper = Operators.begin(),
Douglas Gregor6a1f9652009-08-27 23:35:55 +00004205 OperEnd = Operators.end();
4206 Oper != OperEnd;
John McCallf0f1cf02009-11-17 07:50:12 +00004207 ++Oper)
John McCalla0296f72010-03-19 07:35:19 +00004208 AddMethodCandidate(Oper.getPair(), Args[0]->getType(),
John McCall6e9f8f62009-12-03 04:06:58 +00004209 Args + 1, NumArgs - 1, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00004210 /* SuppressUserConversions = */ false);
Douglas Gregor436424c2008-11-18 23:14:02 +00004211 }
Douglas Gregor436424c2008-11-18 23:14:02 +00004212}
4213
Douglas Gregora11693b2008-11-12 17:17:38 +00004214/// AddBuiltinCandidate - Add a candidate for a built-in
4215/// operator. ResultTy and ParamTys are the result and parameter types
4216/// of the built-in candidate, respectively. Args and NumArgs are the
Douglas Gregorc5e61072009-01-13 00:52:54 +00004217/// arguments being passed to the candidate. IsAssignmentOperator
4218/// should be true when this built-in candidate is an assignment
Douglas Gregor5fb53972009-01-14 15:45:31 +00004219/// operator. NumContextualBoolArguments is the number of arguments
4220/// (at the beginning of the argument list) that will be contextually
4221/// converted to bool.
Mike Stump11289f42009-09-09 15:08:12 +00004222void Sema::AddBuiltinCandidate(QualType ResultTy, QualType *ParamTys,
Douglas Gregora11693b2008-11-12 17:17:38 +00004223 Expr **Args, unsigned NumArgs,
Douglas Gregorc5e61072009-01-13 00:52:54 +00004224 OverloadCandidateSet& CandidateSet,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004225 bool IsAssignmentOperator,
4226 unsigned NumContextualBoolArguments) {
Douglas Gregor27381f32009-11-23 12:27:39 +00004227 // Overload resolution is always an unevaluated context.
John McCallfaf5fb42010-08-26 23:41:50 +00004228 EnterExpressionEvaluationContext Unevaluated(*this, Sema::Unevaluated);
Douglas Gregor27381f32009-11-23 12:27:39 +00004229
Douglas Gregora11693b2008-11-12 17:17:38 +00004230 // Add this candidate
4231 CandidateSet.push_back(OverloadCandidate());
4232 OverloadCandidate& Candidate = CandidateSet.back();
John McCalla0296f72010-03-19 07:35:19 +00004233 Candidate.FoundDecl = DeclAccessPair::make(0, AS_none);
Douglas Gregora11693b2008-11-12 17:17:38 +00004234 Candidate.Function = 0;
Douglas Gregor1d248c52008-12-12 02:00:36 +00004235 Candidate.IsSurrogate = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00004236 Candidate.IgnoreObjectArgument = false;
Douglas Gregora11693b2008-11-12 17:17:38 +00004237 Candidate.BuiltinTypes.ResultTy = ResultTy;
4238 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
4239 Candidate.BuiltinTypes.ParamTypes[ArgIdx] = ParamTys[ArgIdx];
4240
4241 // Determine the implicit conversion sequences for each of the
4242 // arguments.
4243 Candidate.Viable = true;
4244 Candidate.Conversions.resize(NumArgs);
Douglas Gregor6edd9772011-01-19 23:54:39 +00004245 Candidate.ExplicitCallArguments = NumArgs;
Douglas Gregora11693b2008-11-12 17:17:38 +00004246 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
Douglas Gregorc5e61072009-01-13 00:52:54 +00004247 // C++ [over.match.oper]p4:
4248 // For the built-in assignment operators, conversions of the
4249 // left operand are restricted as follows:
4250 // -- no temporaries are introduced to hold the left operand, and
4251 // -- no user-defined conversions are applied to the left
4252 // operand to achieve a type match with the left-most
Mike Stump11289f42009-09-09 15:08:12 +00004253 // parameter of a built-in candidate.
Douglas Gregorc5e61072009-01-13 00:52:54 +00004254 //
4255 // We block these conversions by turning off user-defined
4256 // conversions, since that is the only way that initialization of
4257 // a reference to a non-class type can occur from something that
4258 // is not of the same type.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004259 if (ArgIdx < NumContextualBoolArguments) {
Mike Stump11289f42009-09-09 15:08:12 +00004260 assert(ParamTys[ArgIdx] == Context.BoolTy &&
Douglas Gregor5fb53972009-01-14 15:45:31 +00004261 "Contextual conversion to bool requires bool type");
John McCall5c32be02010-08-24 20:38:10 +00004262 Candidate.Conversions[ArgIdx]
4263 = TryContextuallyConvertToBool(*this, Args[ArgIdx]);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004264 } else {
Mike Stump11289f42009-09-09 15:08:12 +00004265 Candidate.Conversions[ArgIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00004266 = TryCopyInitialization(*this, Args[ArgIdx], ParamTys[ArgIdx],
Anders Carlsson03068aa2009-08-27 17:18:13 +00004267 ArgIdx == 0 && IsAssignmentOperator,
Anders Carlsson20d13322009-08-27 17:37:39 +00004268 /*InOverloadResolution=*/false);
Douglas Gregor5fb53972009-01-14 15:45:31 +00004269 }
John McCall0d1da222010-01-12 00:44:57 +00004270 if (Candidate.Conversions[ArgIdx].isBad()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004271 Candidate.Viable = false;
John McCall6a61b522010-01-13 09:16:55 +00004272 Candidate.FailureKind = ovl_fail_bad_conversion;
Douglas Gregor436424c2008-11-18 23:14:02 +00004273 break;
4274 }
Douglas Gregora11693b2008-11-12 17:17:38 +00004275 }
4276}
4277
4278/// BuiltinCandidateTypeSet - A set of types that will be used for the
4279/// candidate operator functions for built-in operators (C++
4280/// [over.built]). The types are separated into pointer types and
4281/// enumeration types.
4282class BuiltinCandidateTypeSet {
4283 /// TypeSet - A set of types.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004284 typedef llvm::SmallPtrSet<QualType, 8> TypeSet;
Douglas Gregora11693b2008-11-12 17:17:38 +00004285
4286 /// PointerTypes - The set of pointer types that will be used in the
4287 /// built-in candidates.
4288 TypeSet PointerTypes;
4289
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004290 /// MemberPointerTypes - The set of member pointer types that will be
4291 /// used in the built-in candidates.
4292 TypeSet MemberPointerTypes;
4293
Douglas Gregora11693b2008-11-12 17:17:38 +00004294 /// EnumerationTypes - The set of enumeration types that will be
4295 /// used in the built-in candidates.
4296 TypeSet EnumerationTypes;
4297
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004298 /// \brief The set of vector types that will be used in the built-in
4299 /// candidates.
4300 TypeSet VectorTypes;
Chandler Carruth00a38332010-12-13 01:44:01 +00004301
4302 /// \brief A flag indicating non-record types are viable candidates
4303 bool HasNonRecordTypes;
4304
4305 /// \brief A flag indicating whether either arithmetic or enumeration types
4306 /// were present in the candidate set.
4307 bool HasArithmeticOrEnumeralTypes;
4308
Douglas Gregor8a2e6012009-08-24 15:23:48 +00004309 /// Sema - The semantic analysis instance where we are building the
4310 /// candidate type set.
4311 Sema &SemaRef;
Mike Stump11289f42009-09-09 15:08:12 +00004312
Douglas Gregora11693b2008-11-12 17:17:38 +00004313 /// Context - The AST context in which we will build the type sets.
4314 ASTContext &Context;
4315
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004316 bool AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4317 const Qualifiers &VisibleQuals);
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004318 bool AddMemberPointerWithMoreQualifiedTypeVariants(QualType Ty);
Douglas Gregora11693b2008-11-12 17:17:38 +00004319
4320public:
4321 /// iterator - Iterates through the types that are part of the set.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004322 typedef TypeSet::iterator iterator;
Douglas Gregora11693b2008-11-12 17:17:38 +00004323
Mike Stump11289f42009-09-09 15:08:12 +00004324 BuiltinCandidateTypeSet(Sema &SemaRef)
Chandler Carruth00a38332010-12-13 01:44:01 +00004325 : HasNonRecordTypes(false),
4326 HasArithmeticOrEnumeralTypes(false),
4327 SemaRef(SemaRef),
4328 Context(SemaRef.Context) { }
Douglas Gregora11693b2008-11-12 17:17:38 +00004329
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004330 void AddTypesConvertedFrom(QualType Ty,
4331 SourceLocation Loc,
4332 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004333 bool AllowExplicitConversions,
4334 const Qualifiers &VisibleTypeConversionsQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004335
4336 /// pointer_begin - First pointer type found;
4337 iterator pointer_begin() { return PointerTypes.begin(); }
4338
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004339 /// pointer_end - Past the last pointer type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004340 iterator pointer_end() { return PointerTypes.end(); }
4341
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004342 /// member_pointer_begin - First member pointer type found;
4343 iterator member_pointer_begin() { return MemberPointerTypes.begin(); }
4344
4345 /// member_pointer_end - Past the last member pointer type found;
4346 iterator member_pointer_end() { return MemberPointerTypes.end(); }
4347
Douglas Gregora11693b2008-11-12 17:17:38 +00004348 /// enumeration_begin - First enumeration type found;
4349 iterator enumeration_begin() { return EnumerationTypes.begin(); }
4350
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004351 /// enumeration_end - Past the last enumeration type found;
Douglas Gregora11693b2008-11-12 17:17:38 +00004352 iterator enumeration_end() { return EnumerationTypes.end(); }
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004353
4354 iterator vector_begin() { return VectorTypes.begin(); }
4355 iterator vector_end() { return VectorTypes.end(); }
Chandler Carruth00a38332010-12-13 01:44:01 +00004356
4357 bool hasNonRecordTypes() { return HasNonRecordTypes; }
4358 bool hasArithmeticOrEnumeralTypes() { return HasArithmeticOrEnumeralTypes; }
Douglas Gregora11693b2008-11-12 17:17:38 +00004359};
4360
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004361/// AddPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty to
Douglas Gregora11693b2008-11-12 17:17:38 +00004362/// the set of pointer types along with any more-qualified variants of
4363/// that type. For example, if @p Ty is "int const *", this routine
4364/// will add "int const *", "int const volatile *", "int const
4365/// restrict *", and "int const volatile restrict *" to the set of
4366/// pointer types. Returns true if the add of @p Ty itself succeeded,
4367/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004368///
4369/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004370bool
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004371BuiltinCandidateTypeSet::AddPointerWithMoreQualifiedTypeVariants(QualType Ty,
4372 const Qualifiers &VisibleQuals) {
John McCall8ccfcb52009-09-24 19:53:00 +00004373
Douglas Gregora11693b2008-11-12 17:17:38 +00004374 // Insert this type.
Chris Lattnera59a3e22009-03-29 00:04:01 +00004375 if (!PointerTypes.insert(Ty))
Douglas Gregora11693b2008-11-12 17:17:38 +00004376 return false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004377
4378 QualType PointeeTy;
John McCall8ccfcb52009-09-24 19:53:00 +00004379 const PointerType *PointerTy = Ty->getAs<PointerType>();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004380 bool buildObjCPtr = false;
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004381 if (!PointerTy) {
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004382 if (const ObjCObjectPointerType *PTy = Ty->getAs<ObjCObjectPointerType>()) {
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004383 PointeeTy = PTy->getPointeeType();
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004384 buildObjCPtr = true;
4385 }
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004386 else
4387 assert(false && "type was not a pointer type!");
4388 }
4389 else
4390 PointeeTy = PointerTy->getPointeeType();
4391
Sebastian Redl4990a632009-11-18 20:39:26 +00004392 // Don't add qualified variants of arrays. For one, they're not allowed
4393 // (the qualifier would sink to the element type), and for another, the
4394 // only overload situation where it matters is subscript or pointer +- int,
4395 // and those shouldn't have qualifier variants anyway.
4396 if (PointeeTy->isArrayType())
4397 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004398 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
Douglas Gregor4ef1d402009-11-09 22:08:55 +00004399 if (const ConstantArrayType *Array =Context.getAsConstantArrayType(PointeeTy))
Fariborz Jahanianfacfdd42009-11-09 21:02:05 +00004400 BaseCVR = Array->getElementType().getCVRQualifiers();
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004401 bool hasVolatile = VisibleQuals.hasVolatile();
4402 bool hasRestrict = VisibleQuals.hasRestrict();
4403
John McCall8ccfcb52009-09-24 19:53:00 +00004404 // Iterate through all strict supersets of BaseCVR.
4405 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4406 if ((CVR | BaseCVR) != CVR) continue;
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004407 // Skip over Volatile/Restrict if no Volatile/Restrict found anywhere
4408 // in the types.
4409 if ((CVR & Qualifiers::Volatile) && !hasVolatile) continue;
4410 if ((CVR & Qualifiers::Restrict) && !hasRestrict) continue;
John McCall8ccfcb52009-09-24 19:53:00 +00004411 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Fariborz Jahanianf2afc802010-08-21 17:11:09 +00004412 if (!buildObjCPtr)
4413 PointerTypes.insert(Context.getPointerType(QPointeeTy));
4414 else
4415 PointerTypes.insert(Context.getObjCObjectPointerType(QPointeeTy));
Douglas Gregora11693b2008-11-12 17:17:38 +00004416 }
4417
4418 return true;
4419}
4420
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004421/// AddMemberPointerWithMoreQualifiedTypeVariants - Add the pointer type @p Ty
4422/// to the set of pointer types along with any more-qualified variants of
4423/// that type. For example, if @p Ty is "int const *", this routine
4424/// will add "int const *", "int const volatile *", "int const
4425/// restrict *", and "int const volatile restrict *" to the set of
4426/// pointer types. Returns true if the add of @p Ty itself succeeded,
4427/// false otherwise.
John McCall8ccfcb52009-09-24 19:53:00 +00004428///
4429/// FIXME: what to do about extended qualifiers?
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004430bool
4431BuiltinCandidateTypeSet::AddMemberPointerWithMoreQualifiedTypeVariants(
4432 QualType Ty) {
4433 // Insert this type.
4434 if (!MemberPointerTypes.insert(Ty))
4435 return false;
4436
John McCall8ccfcb52009-09-24 19:53:00 +00004437 const MemberPointerType *PointerTy = Ty->getAs<MemberPointerType>();
4438 assert(PointerTy && "type was not a member pointer type!");
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004439
John McCall8ccfcb52009-09-24 19:53:00 +00004440 QualType PointeeTy = PointerTy->getPointeeType();
Sebastian Redl4990a632009-11-18 20:39:26 +00004441 // Don't add qualified variants of arrays. For one, they're not allowed
4442 // (the qualifier would sink to the element type), and for another, the
4443 // only overload situation where it matters is subscript or pointer +- int,
4444 // and those shouldn't have qualifier variants anyway.
4445 if (PointeeTy->isArrayType())
4446 return true;
John McCall8ccfcb52009-09-24 19:53:00 +00004447 const Type *ClassTy = PointerTy->getClass();
4448
4449 // Iterate through all strict supersets of the pointee type's CVR
4450 // qualifiers.
4451 unsigned BaseCVR = PointeeTy.getCVRQualifiers();
4452 for (unsigned CVR = BaseCVR+1; CVR <= Qualifiers::CVRMask; ++CVR) {
4453 if ((CVR | BaseCVR) != CVR) continue;
4454
4455 QualType QPointeeTy = Context.getCVRQualifiedType(PointeeTy, CVR);
Chandler Carruth8e543b32010-12-12 08:17:55 +00004456 MemberPointerTypes.insert(
4457 Context.getMemberPointerType(QPointeeTy, ClassTy));
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004458 }
4459
4460 return true;
4461}
4462
Douglas Gregora11693b2008-11-12 17:17:38 +00004463/// AddTypesConvertedFrom - Add each of the types to which the type @p
4464/// Ty can be implicit converted to the given set of @p Types. We're
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004465/// primarily interested in pointer types and enumeration types. We also
4466/// take member pointer types, for the conditional operator.
Douglas Gregor5fb53972009-01-14 15:45:31 +00004467/// AllowUserConversions is true if we should look at the conversion
4468/// functions of a class type, and AllowExplicitConversions if we
4469/// should also include the explicit conversion functions of a class
4470/// type.
Mike Stump11289f42009-09-09 15:08:12 +00004471void
Douglas Gregor5fb53972009-01-14 15:45:31 +00004472BuiltinCandidateTypeSet::AddTypesConvertedFrom(QualType Ty,
Douglas Gregorc02cfe22009-10-21 23:19:44 +00004473 SourceLocation Loc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00004474 bool AllowUserConversions,
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004475 bool AllowExplicitConversions,
4476 const Qualifiers &VisibleQuals) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004477 // Only deal with canonical types.
4478 Ty = Context.getCanonicalType(Ty);
4479
4480 // Look through reference types; they aren't part of the type of an
4481 // expression for the purposes of conversions.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004482 if (const ReferenceType *RefTy = Ty->getAs<ReferenceType>())
Douglas Gregora11693b2008-11-12 17:17:38 +00004483 Ty = RefTy->getPointeeType();
4484
John McCall33ddac02011-01-19 10:06:00 +00004485 // If we're dealing with an array type, decay to the pointer.
4486 if (Ty->isArrayType())
4487 Ty = SemaRef.Context.getArrayDecayedType(Ty);
4488
4489 // Otherwise, we don't care about qualifiers on the type.
Douglas Gregor1b8fe5b72009-11-16 21:35:15 +00004490 Ty = Ty.getLocalUnqualifiedType();
Douglas Gregora11693b2008-11-12 17:17:38 +00004491
Chandler Carruth00a38332010-12-13 01:44:01 +00004492 // Flag if we ever add a non-record type.
4493 const RecordType *TyRec = Ty->getAs<RecordType>();
4494 HasNonRecordTypes = HasNonRecordTypes || !TyRec;
4495
Chandler Carruth00a38332010-12-13 01:44:01 +00004496 // Flag if we encounter an arithmetic type.
4497 HasArithmeticOrEnumeralTypes =
4498 HasArithmeticOrEnumeralTypes || Ty->isArithmeticType();
4499
Fariborz Jahaniane4151b52010-08-21 00:10:36 +00004500 if (Ty->isObjCIdType() || Ty->isObjCClassType())
4501 PointerTypes.insert(Ty);
4502 else if (Ty->getAs<PointerType>() || Ty->getAs<ObjCObjectPointerType>()) {
Douglas Gregora11693b2008-11-12 17:17:38 +00004503 // Insert our type, and its more-qualified variants, into the set
4504 // of types.
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004505 if (!AddPointerWithMoreQualifiedTypeVariants(Ty, VisibleQuals))
Douglas Gregora11693b2008-11-12 17:17:38 +00004506 return;
Sebastian Redl8ce189f2009-04-19 21:53:20 +00004507 } else if (Ty->isMemberPointerType()) {
4508 // Member pointers are far easier, since the pointee can't be converted.
4509 if (!AddMemberPointerWithMoreQualifiedTypeVariants(Ty))
4510 return;
Douglas Gregora11693b2008-11-12 17:17:38 +00004511 } else if (Ty->isEnumeralType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004512 HasArithmeticOrEnumeralTypes = true;
Chris Lattnera59a3e22009-03-29 00:04:01 +00004513 EnumerationTypes.insert(Ty);
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004514 } else if (Ty->isVectorType()) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004515 // We treat vector types as arithmetic types in many contexts as an
4516 // extension.
4517 HasArithmeticOrEnumeralTypes = true;
Douglas Gregorcbfbca12010-05-19 03:21:00 +00004518 VectorTypes.insert(Ty);
Chandler Carruth00a38332010-12-13 01:44:01 +00004519 } else if (AllowUserConversions && TyRec) {
4520 // No conversion functions in incomplete types.
4521 if (SemaRef.RequireCompleteType(Loc, Ty, 0))
4522 return;
Mike Stump11289f42009-09-09 15:08:12 +00004523
Chandler Carruth00a38332010-12-13 01:44:01 +00004524 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
4525 const UnresolvedSetImpl *Conversions
4526 = ClassDecl->getVisibleConversionFunctions();
4527 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
4528 E = Conversions->end(); I != E; ++I) {
4529 NamedDecl *D = I.getDecl();
4530 if (isa<UsingShadowDecl>(D))
4531 D = cast<UsingShadowDecl>(D)->getTargetDecl();
Douglas Gregor05155d82009-08-21 23:19:43 +00004532
Chandler Carruth00a38332010-12-13 01:44:01 +00004533 // Skip conversion function templates; they don't tell us anything
4534 // about which builtin types we can convert to.
4535 if (isa<FunctionTemplateDecl>(D))
4536 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00004537
Chandler Carruth00a38332010-12-13 01:44:01 +00004538 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
4539 if (AllowExplicitConversions || !Conv->isExplicit()) {
4540 AddTypesConvertedFrom(Conv->getConversionType(), Loc, false, false,
4541 VisibleQuals);
Douglas Gregora11693b2008-11-12 17:17:38 +00004542 }
4543 }
4544 }
4545}
4546
Douglas Gregor84605ae2009-08-24 13:43:27 +00004547/// \brief Helper function for AddBuiltinOperatorCandidates() that adds
4548/// the volatile- and non-volatile-qualified assignment operators for the
4549/// given type to the candidate set.
4550static void AddBuiltinAssignmentOperatorCandidates(Sema &S,
4551 QualType T,
Mike Stump11289f42009-09-09 15:08:12 +00004552 Expr **Args,
Douglas Gregor84605ae2009-08-24 13:43:27 +00004553 unsigned NumArgs,
4554 OverloadCandidateSet &CandidateSet) {
4555 QualType ParamTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00004556
Douglas Gregor84605ae2009-08-24 13:43:27 +00004557 // T& operator=(T&, T)
4558 ParamTypes[0] = S.Context.getLValueReferenceType(T);
4559 ParamTypes[1] = T;
4560 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
4561 /*IsAssignmentOperator=*/true);
Mike Stump11289f42009-09-09 15:08:12 +00004562
Douglas Gregor84605ae2009-08-24 13:43:27 +00004563 if (!S.Context.getCanonicalType(T).isVolatileQualified()) {
4564 // volatile T& operator=(volatile T&, T)
John McCall8ccfcb52009-09-24 19:53:00 +00004565 ParamTypes[0]
4566 = S.Context.getLValueReferenceType(S.Context.getVolatileType(T));
Douglas Gregor84605ae2009-08-24 13:43:27 +00004567 ParamTypes[1] = T;
4568 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
Mike Stump11289f42009-09-09 15:08:12 +00004569 /*IsAssignmentOperator=*/true);
Douglas Gregor84605ae2009-08-24 13:43:27 +00004570 }
4571}
Mike Stump11289f42009-09-09 15:08:12 +00004572
Sebastian Redl1054fae2009-10-25 17:03:50 +00004573/// CollectVRQualifiers - This routine returns Volatile/Restrict qualifiers,
4574/// if any, found in visible type conversion functions found in ArgExpr's type.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004575static Qualifiers CollectVRQualifiers(ASTContext &Context, Expr* ArgExpr) {
4576 Qualifiers VRQuals;
4577 const RecordType *TyRec;
4578 if (const MemberPointerType *RHSMPType =
4579 ArgExpr->getType()->getAs<MemberPointerType>())
Douglas Gregord0ace022010-04-25 00:55:24 +00004580 TyRec = RHSMPType->getClass()->getAs<RecordType>();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004581 else
4582 TyRec = ArgExpr->getType()->getAs<RecordType>();
4583 if (!TyRec) {
Fariborz Jahanianb06ec052009-10-16 22:08:05 +00004584 // Just to be safe, assume the worst case.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004585 VRQuals.addVolatile();
4586 VRQuals.addRestrict();
4587 return VRQuals;
4588 }
4589
4590 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(TyRec->getDecl());
John McCall67da35c2010-02-04 22:26:26 +00004591 if (!ClassDecl->hasDefinition())
4592 return VRQuals;
4593
John McCallad371252010-01-20 00:46:10 +00004594 const UnresolvedSetImpl *Conversions =
Sebastian Redl1054fae2009-10-25 17:03:50 +00004595 ClassDecl->getVisibleConversionFunctions();
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004596
John McCallad371252010-01-20 00:46:10 +00004597 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00004598 E = Conversions->end(); I != E; ++I) {
John McCallda4458e2010-03-31 01:36:47 +00004599 NamedDecl *D = I.getDecl();
4600 if (isa<UsingShadowDecl>(D))
4601 D = cast<UsingShadowDecl>(D)->getTargetDecl();
4602 if (CXXConversionDecl *Conv = dyn_cast<CXXConversionDecl>(D)) {
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00004603 QualType CanTy = Context.getCanonicalType(Conv->getConversionType());
4604 if (const ReferenceType *ResTypeRef = CanTy->getAs<ReferenceType>())
4605 CanTy = ResTypeRef->getPointeeType();
4606 // Need to go down the pointer/mempointer chain and add qualifiers
4607 // as see them.
4608 bool done = false;
4609 while (!done) {
4610 if (const PointerType *ResTypePtr = CanTy->getAs<PointerType>())
4611 CanTy = ResTypePtr->getPointeeType();
4612 else if (const MemberPointerType *ResTypeMPtr =
4613 CanTy->getAs<MemberPointerType>())
4614 CanTy = ResTypeMPtr->getPointeeType();
4615 else
4616 done = true;
4617 if (CanTy.isVolatileQualified())
4618 VRQuals.addVolatile();
4619 if (CanTy.isRestrictQualified())
4620 VRQuals.addRestrict();
4621 if (VRQuals.hasRestrict() && VRQuals.hasVolatile())
4622 return VRQuals;
4623 }
4624 }
4625 }
4626 return VRQuals;
4627}
John McCall52872982010-11-13 05:51:15 +00004628
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004629namespace {
John McCall52872982010-11-13 05:51:15 +00004630
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004631/// \brief Helper class to manage the addition of builtin operator overload
4632/// candidates. It provides shared state and utility methods used throughout
4633/// the process, as well as a helper method to add each group of builtin
4634/// operator overloads from the standard to a candidate set.
4635class BuiltinOperatorOverloadBuilder {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004636 // Common instance state available to all overload candidate addition methods.
4637 Sema &S;
4638 Expr **Args;
4639 unsigned NumArgs;
4640 Qualifiers VisibleTypeConversionsQuals;
Chandler Carruth00a38332010-12-13 01:44:01 +00004641 bool HasArithmeticOrEnumeralCandidateType;
Chandler Carruthc6586e52010-12-12 10:35:00 +00004642 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes;
4643 OverloadCandidateSet &CandidateSet;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004644
Chandler Carruthc6586e52010-12-12 10:35:00 +00004645 // Define some constants used to index and iterate over the arithemetic types
4646 // provided via the getArithmeticType() method below.
John McCall52872982010-11-13 05:51:15 +00004647 // The "promoted arithmetic types" are the arithmetic
4648 // types are that preserved by promotion (C++ [over.built]p2).
John McCall52872982010-11-13 05:51:15 +00004649 static const unsigned FirstIntegralType = 3;
4650 static const unsigned LastIntegralType = 18;
4651 static const unsigned FirstPromotedIntegralType = 3,
4652 LastPromotedIntegralType = 9;
4653 static const unsigned FirstPromotedArithmeticType = 0,
4654 LastPromotedArithmeticType = 9;
4655 static const unsigned NumArithmeticTypes = 18;
4656
Chandler Carruthc6586e52010-12-12 10:35:00 +00004657 /// \brief Get the canonical type for a given arithmetic type index.
4658 CanQualType getArithmeticType(unsigned index) {
4659 assert(index < NumArithmeticTypes);
4660 static CanQualType ASTContext::* const
4661 ArithmeticTypes[NumArithmeticTypes] = {
4662 // Start of promoted types.
4663 &ASTContext::FloatTy,
4664 &ASTContext::DoubleTy,
4665 &ASTContext::LongDoubleTy,
John McCall52872982010-11-13 05:51:15 +00004666
Chandler Carruthc6586e52010-12-12 10:35:00 +00004667 // Start of integral types.
4668 &ASTContext::IntTy,
4669 &ASTContext::LongTy,
4670 &ASTContext::LongLongTy,
4671 &ASTContext::UnsignedIntTy,
4672 &ASTContext::UnsignedLongTy,
4673 &ASTContext::UnsignedLongLongTy,
4674 // End of promoted types.
4675
4676 &ASTContext::BoolTy,
4677 &ASTContext::CharTy,
4678 &ASTContext::WCharTy,
4679 &ASTContext::Char16Ty,
4680 &ASTContext::Char32Ty,
4681 &ASTContext::SignedCharTy,
4682 &ASTContext::ShortTy,
4683 &ASTContext::UnsignedCharTy,
4684 &ASTContext::UnsignedShortTy,
4685 // End of integral types.
4686 // FIXME: What about complex?
4687 };
4688 return S.Context.*ArithmeticTypes[index];
4689 }
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004690
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004691 /// \brief Gets the canonical type resulting from the usual arithemetic
4692 /// converions for the given arithmetic types.
4693 CanQualType getUsualArithmeticConversions(unsigned L, unsigned R) {
4694 // Accelerator table for performing the usual arithmetic conversions.
4695 // The rules are basically:
4696 // - if either is floating-point, use the wider floating-point
4697 // - if same signedness, use the higher rank
4698 // - if same size, use unsigned of the higher rank
4699 // - use the larger type
4700 // These rules, together with the axiom that higher ranks are
4701 // never smaller, are sufficient to precompute all of these results
4702 // *except* when dealing with signed types of higher rank.
4703 // (we could precompute SLL x UI for all known platforms, but it's
4704 // better not to make any assumptions).
4705 enum PromotedType {
4706 Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL, Dep=-1
4707 };
4708 static PromotedType ConversionsTable[LastPromotedArithmeticType]
4709 [LastPromotedArithmeticType] = {
4710 /* Flt*/ { Flt, Dbl, LDbl, Flt, Flt, Flt, Flt, Flt, Flt },
4711 /* Dbl*/ { Dbl, Dbl, LDbl, Dbl, Dbl, Dbl, Dbl, Dbl, Dbl },
4712 /*LDbl*/ { LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl, LDbl },
4713 /* SI*/ { Flt, Dbl, LDbl, SI, SL, SLL, UI, UL, ULL },
4714 /* SL*/ { Flt, Dbl, LDbl, SL, SL, SLL, Dep, UL, ULL },
4715 /* SLL*/ { Flt, Dbl, LDbl, SLL, SLL, SLL, Dep, Dep, ULL },
4716 /* UI*/ { Flt, Dbl, LDbl, UI, Dep, Dep, UI, UL, ULL },
4717 /* UL*/ { Flt, Dbl, LDbl, UL, UL, Dep, UL, UL, ULL },
4718 /* ULL*/ { Flt, Dbl, LDbl, ULL, ULL, ULL, ULL, ULL, ULL },
4719 };
4720
4721 assert(L < LastPromotedArithmeticType);
4722 assert(R < LastPromotedArithmeticType);
4723 int Idx = ConversionsTable[L][R];
4724
4725 // Fast path: the table gives us a concrete answer.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004726 if (Idx != Dep) return getArithmeticType(Idx);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004727
4728 // Slow path: we need to compare widths.
4729 // An invariant is that the signed type has higher rank.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004730 CanQualType LT = getArithmeticType(L),
4731 RT = getArithmeticType(R);
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00004732 unsigned LW = S.Context.getIntWidth(LT),
4733 RW = S.Context.getIntWidth(RT);
4734
4735 // If they're different widths, use the signed type.
4736 if (LW > RW) return LT;
4737 else if (LW < RW) return RT;
4738
4739 // Otherwise, use the unsigned type of the signed type's rank.
4740 if (L == SL || R == SL) return S.Context.UnsignedLongTy;
4741 assert(L == SLL || R == SLL);
4742 return S.Context.UnsignedLongLongTy;
4743 }
4744
Chandler Carruth5659c0c2010-12-12 09:22:45 +00004745 /// \brief Helper method to factor out the common pattern of adding overloads
4746 /// for '++' and '--' builtin operators.
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004747 void addPlusPlusMinusMinusStyleOverloads(QualType CandidateTy,
4748 bool HasVolatile) {
4749 QualType ParamTypes[2] = {
4750 S.Context.getLValueReferenceType(CandidateTy),
4751 S.Context.IntTy
4752 };
4753
4754 // Non-volatile version.
4755 if (NumArgs == 1)
4756 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4757 else
4758 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4759
4760 // Use a heuristic to reduce number of builtin candidates in the set:
4761 // add volatile version only if there are conversions to a volatile type.
4762 if (HasVolatile) {
4763 ParamTypes[0] =
4764 S.Context.getLValueReferenceType(
4765 S.Context.getVolatileType(CandidateTy));
4766 if (NumArgs == 1)
4767 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 1, CandidateSet);
4768 else
4769 S.AddBuiltinCandidate(CandidateTy, ParamTypes, Args, 2, CandidateSet);
4770 }
4771 }
4772
4773public:
4774 BuiltinOperatorOverloadBuilder(
4775 Sema &S, Expr **Args, unsigned NumArgs,
4776 Qualifiers VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00004777 bool HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004778 llvm::SmallVectorImpl<BuiltinCandidateTypeSet> &CandidateTypes,
4779 OverloadCandidateSet &CandidateSet)
4780 : S(S), Args(Args), NumArgs(NumArgs),
4781 VisibleTypeConversionsQuals(VisibleTypeConversionsQuals),
Chandler Carruth00a38332010-12-13 01:44:01 +00004782 HasArithmeticOrEnumeralCandidateType(
4783 HasArithmeticOrEnumeralCandidateType),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004784 CandidateTypes(CandidateTypes),
4785 CandidateSet(CandidateSet) {
4786 // Validate some of our static helper constants in debug builds.
Chandler Carruthc6586e52010-12-12 10:35:00 +00004787 assert(getArithmeticType(FirstPromotedIntegralType) == S.Context.IntTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004788 "Invalid first promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004789 assert(getArithmeticType(LastPromotedIntegralType - 1)
4790 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004791 "Invalid last promoted integral type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004792 assert(getArithmeticType(FirstPromotedArithmeticType)
4793 == S.Context.FloatTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004794 "Invalid first promoted arithmetic type");
Chandler Carruthc6586e52010-12-12 10:35:00 +00004795 assert(getArithmeticType(LastPromotedArithmeticType - 1)
4796 == S.Context.UnsignedLongLongTy &&
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004797 "Invalid last promoted arithmetic type");
4798 }
4799
4800 // C++ [over.built]p3:
4801 //
4802 // For every pair (T, VQ), where T is an arithmetic type, and VQ
4803 // is either volatile or empty, there exist candidate operator
4804 // functions of the form
4805 //
4806 // VQ T& operator++(VQ T&);
4807 // T operator++(VQ T&, int);
4808 //
4809 // C++ [over.built]p4:
4810 //
4811 // For every pair (T, VQ), where T is an arithmetic type other
4812 // than bool, and VQ is either volatile or empty, there exist
4813 // candidate operator functions of the form
4814 //
4815 // VQ T& operator--(VQ T&);
4816 // T operator--(VQ T&, int);
4817 void addPlusPlusMinusMinusArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00004818 if (!HasArithmeticOrEnumeralCandidateType)
4819 return;
4820
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004821 for (unsigned Arith = (Op == OO_PlusPlus? 0 : 1);
4822 Arith < NumArithmeticTypes; ++Arith) {
4823 addPlusPlusMinusMinusStyleOverloads(
Chandler Carruthc6586e52010-12-12 10:35:00 +00004824 getArithmeticType(Arith),
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004825 VisibleTypeConversionsQuals.hasVolatile());
4826 }
4827 }
4828
4829 // C++ [over.built]p5:
4830 //
4831 // For every pair (T, VQ), where T is a cv-qualified or
4832 // cv-unqualified object type, and VQ is either volatile or
4833 // empty, there exist candidate operator functions of the form
4834 //
4835 // T*VQ& operator++(T*VQ&);
4836 // T*VQ& operator--(T*VQ&);
4837 // T* operator++(T*VQ&, int);
4838 // T* operator--(T*VQ&, int);
4839 void addPlusPlusMinusMinusPointerOverloads() {
4840 for (BuiltinCandidateTypeSet::iterator
4841 Ptr = CandidateTypes[0].pointer_begin(),
4842 PtrEnd = CandidateTypes[0].pointer_end();
4843 Ptr != PtrEnd; ++Ptr) {
4844 // Skip pointer types that aren't pointers to object types.
Douglas Gregor66990032011-01-05 00:13:17 +00004845 if (!(*Ptr)->getPointeeType()->isObjectType())
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004846 continue;
4847
4848 addPlusPlusMinusMinusStyleOverloads(*Ptr,
4849 (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
4850 VisibleTypeConversionsQuals.hasVolatile()));
4851 }
4852 }
4853
4854 // C++ [over.built]p6:
4855 // For every cv-qualified or cv-unqualified object type T, there
4856 // exist candidate operator functions of the form
4857 //
4858 // T& operator*(T*);
4859 //
4860 // C++ [over.built]p7:
4861 // For every function type T, there exist candidate operator
4862 // functions of the form
4863 // T& operator*(T*);
4864 void addUnaryStarPointerOverloads() {
4865 for (BuiltinCandidateTypeSet::iterator
4866 Ptr = CandidateTypes[0].pointer_begin(),
4867 PtrEnd = CandidateTypes[0].pointer_end();
4868 Ptr != PtrEnd; ++Ptr) {
4869 QualType ParamTy = *Ptr;
4870 QualType PointeeTy = ParamTy->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00004871 if (!PointeeTy->isObjectType() && !PointeeTy->isFunctionType())
4872 continue;
4873
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004874 S.AddBuiltinCandidate(S.Context.getLValueReferenceType(PointeeTy),
4875 &ParamTy, Args, 1, CandidateSet);
4876 }
4877 }
4878
4879 // C++ [over.built]p9:
4880 // For every promoted arithmetic type T, there exist candidate
4881 // operator functions of the form
4882 //
4883 // T operator+(T);
4884 // T operator-(T);
4885 void addUnaryPlusOrMinusArithmeticOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00004886 if (!HasArithmeticOrEnumeralCandidateType)
4887 return;
4888
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004889 for (unsigned Arith = FirstPromotedArithmeticType;
4890 Arith < LastPromotedArithmeticType; ++Arith) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004891 QualType ArithTy = getArithmeticType(Arith);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004892 S.AddBuiltinCandidate(ArithTy, &ArithTy, Args, 1, CandidateSet);
4893 }
4894
4895 // Extension: We also add these operators for vector types.
4896 for (BuiltinCandidateTypeSet::iterator
4897 Vec = CandidateTypes[0].vector_begin(),
4898 VecEnd = CandidateTypes[0].vector_end();
4899 Vec != VecEnd; ++Vec) {
4900 QualType VecTy = *Vec;
4901 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4902 }
4903 }
4904
4905 // C++ [over.built]p8:
4906 // For every type T, there exist candidate operator functions of
4907 // the form
4908 //
4909 // T* operator+(T*);
4910 void addUnaryPlusPointerOverloads() {
4911 for (BuiltinCandidateTypeSet::iterator
4912 Ptr = CandidateTypes[0].pointer_begin(),
4913 PtrEnd = CandidateTypes[0].pointer_end();
4914 Ptr != PtrEnd; ++Ptr) {
4915 QualType ParamTy = *Ptr;
4916 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet);
4917 }
4918 }
4919
4920 // C++ [over.built]p10:
4921 // For every promoted integral type T, there exist candidate
4922 // operator functions of the form
4923 //
4924 // T operator~(T);
4925 void addUnaryTildePromotedIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00004926 if (!HasArithmeticOrEnumeralCandidateType)
4927 return;
4928
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004929 for (unsigned Int = FirstPromotedIntegralType;
4930 Int < LastPromotedIntegralType; ++Int) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00004931 QualType IntTy = getArithmeticType(Int);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00004932 S.AddBuiltinCandidate(IntTy, &IntTy, Args, 1, CandidateSet);
4933 }
4934
4935 // Extension: We also add this operator for vector types.
4936 for (BuiltinCandidateTypeSet::iterator
4937 Vec = CandidateTypes[0].vector_begin(),
4938 VecEnd = CandidateTypes[0].vector_end();
4939 Vec != VecEnd; ++Vec) {
4940 QualType VecTy = *Vec;
4941 S.AddBuiltinCandidate(VecTy, &VecTy, Args, 1, CandidateSet);
4942 }
4943 }
4944
4945 // C++ [over.match.oper]p16:
4946 // For every pointer to member type T, there exist candidate operator
4947 // functions of the form
4948 //
4949 // bool operator==(T,T);
4950 // bool operator!=(T,T);
4951 void addEqualEqualOrNotEqualMemberPointerOverloads() {
4952 /// Set of (canonical) types that we've already handled.
4953 llvm::SmallPtrSet<QualType, 8> AddedTypes;
4954
4955 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
4956 for (BuiltinCandidateTypeSet::iterator
4957 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
4958 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
4959 MemPtr != MemPtrEnd;
4960 ++MemPtr) {
4961 // Don't add the same builtin candidate twice.
4962 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
4963 continue;
4964
4965 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
4966 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
4967 CandidateSet);
4968 }
4969 }
4970 }
4971
4972 // C++ [over.built]p15:
4973 //
4974 // For every pointer or enumeration type T, there exist
4975 // candidate operator functions of the form
4976 //
4977 // bool operator<(T, T);
4978 // bool operator>(T, T);
4979 // bool operator<=(T, T);
4980 // bool operator>=(T, T);
4981 // bool operator==(T, T);
4982 // bool operator!=(T, T);
Chandler Carruthc02db8c2010-12-12 09:14:11 +00004983 void addRelationalPointerOrEnumeralOverloads() {
4984 // C++ [over.built]p1:
4985 // If there is a user-written candidate with the same name and parameter
4986 // types as a built-in candidate operator function, the built-in operator
4987 // function is hidden and is not included in the set of candidate
4988 // functions.
4989 //
4990 // The text is actually in a note, but if we don't implement it then we end
4991 // up with ambiguities when the user provides an overloaded operator for
4992 // an enumeration type. Note that only enumeration types have this problem,
4993 // so we track which enumeration types we've seen operators for. Also, the
4994 // only other overloaded operator with enumeration argumenst, operator=,
4995 // cannot be overloaded for enumeration types, so this is the only place
4996 // where we must suppress candidates like this.
4997 llvm::DenseSet<std::pair<CanQualType, CanQualType> >
4998 UserDefinedBinaryOperators;
4999
5000 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5001 if (CandidateTypes[ArgIdx].enumeration_begin() !=
5002 CandidateTypes[ArgIdx].enumeration_end()) {
5003 for (OverloadCandidateSet::iterator C = CandidateSet.begin(),
5004 CEnd = CandidateSet.end();
5005 C != CEnd; ++C) {
5006 if (!C->Viable || !C->Function || C->Function->getNumParams() != 2)
5007 continue;
5008
5009 QualType FirstParamType =
5010 C->Function->getParamDecl(0)->getType().getUnqualifiedType();
5011 QualType SecondParamType =
5012 C->Function->getParamDecl(1)->getType().getUnqualifiedType();
5013
5014 // Skip if either parameter isn't of enumeral type.
5015 if (!FirstParamType->isEnumeralType() ||
5016 !SecondParamType->isEnumeralType())
5017 continue;
5018
5019 // Add this operator to the set of known user-defined operators.
5020 UserDefinedBinaryOperators.insert(
5021 std::make_pair(S.Context.getCanonicalType(FirstParamType),
5022 S.Context.getCanonicalType(SecondParamType)));
5023 }
5024 }
5025 }
5026
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005027 /// Set of (canonical) types that we've already handled.
5028 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5029
5030 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5031 for (BuiltinCandidateTypeSet::iterator
5032 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5033 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5034 Ptr != PtrEnd; ++Ptr) {
5035 // Don't add the same builtin candidate twice.
5036 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5037 continue;
5038
5039 QualType ParamTypes[2] = { *Ptr, *Ptr };
5040 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5041 CandidateSet);
5042 }
5043 for (BuiltinCandidateTypeSet::iterator
5044 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5045 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5046 Enum != EnumEnd; ++Enum) {
5047 CanQualType CanonType = S.Context.getCanonicalType(*Enum);
5048
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005049 // Don't add the same builtin candidate twice, or if a user defined
5050 // candidate exists.
5051 if (!AddedTypes.insert(CanonType) ||
5052 UserDefinedBinaryOperators.count(std::make_pair(CanonType,
5053 CanonType)))
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005054 continue;
5055
5056 QualType ParamTypes[2] = { *Enum, *Enum };
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005057 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2,
5058 CandidateSet);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005059 }
5060 }
5061 }
5062
5063 // C++ [over.built]p13:
5064 //
5065 // For every cv-qualified or cv-unqualified object type T
5066 // there exist candidate operator functions of the form
5067 //
5068 // T* operator+(T*, ptrdiff_t);
5069 // T& operator[](T*, ptrdiff_t); [BELOW]
5070 // T* operator-(T*, ptrdiff_t);
5071 // T* operator+(ptrdiff_t, T*);
5072 // T& operator[](ptrdiff_t, T*); [BELOW]
5073 //
5074 // C++ [over.built]p14:
5075 //
5076 // For every T, where T is a pointer to object type, there
5077 // exist candidate operator functions of the form
5078 //
5079 // ptrdiff_t operator-(T, T);
5080 void addBinaryPlusOrMinusPointerOverloads(OverloadedOperatorKind Op) {
5081 /// Set of (canonical) types that we've already handled.
5082 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5083
5084 for (int Arg = 0; Arg < 2; ++Arg) {
5085 QualType AsymetricParamTypes[2] = {
5086 S.Context.getPointerDiffType(),
5087 S.Context.getPointerDiffType(),
5088 };
5089 for (BuiltinCandidateTypeSet::iterator
5090 Ptr = CandidateTypes[Arg].pointer_begin(),
5091 PtrEnd = CandidateTypes[Arg].pointer_end();
5092 Ptr != PtrEnd; ++Ptr) {
Douglas Gregor66990032011-01-05 00:13:17 +00005093 QualType PointeeTy = (*Ptr)->getPointeeType();
5094 if (!PointeeTy->isObjectType())
5095 continue;
5096
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005097 AsymetricParamTypes[Arg] = *Ptr;
5098 if (Arg == 0 || Op == OO_Plus) {
5099 // operator+(T*, ptrdiff_t) or operator-(T*, ptrdiff_t)
5100 // T* operator+(ptrdiff_t, T*);
5101 S.AddBuiltinCandidate(*Ptr, AsymetricParamTypes, Args, 2,
5102 CandidateSet);
5103 }
5104 if (Op == OO_Minus) {
5105 // ptrdiff_t operator-(T, T);
5106 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5107 continue;
5108
5109 QualType ParamTypes[2] = { *Ptr, *Ptr };
5110 S.AddBuiltinCandidate(S.Context.getPointerDiffType(), ParamTypes,
5111 Args, 2, CandidateSet);
5112 }
5113 }
5114 }
5115 }
5116
5117 // C++ [over.built]p12:
5118 //
5119 // For every pair of promoted arithmetic types L and R, there
5120 // exist candidate operator functions of the form
5121 //
5122 // LR operator*(L, R);
5123 // LR operator/(L, R);
5124 // LR operator+(L, R);
5125 // LR operator-(L, R);
5126 // bool operator<(L, R);
5127 // bool operator>(L, R);
5128 // bool operator<=(L, R);
5129 // bool operator>=(L, R);
5130 // bool operator==(L, R);
5131 // bool operator!=(L, R);
5132 //
5133 // where LR is the result of the usual arithmetic conversions
5134 // between types L and R.
5135 //
5136 // C++ [over.built]p24:
5137 //
5138 // For every pair of promoted arithmetic types L and R, there exist
5139 // candidate operator functions of the form
5140 //
5141 // LR operator?(bool, L, R);
5142 //
5143 // where LR is the result of the usual arithmetic conversions
5144 // between types L and R.
5145 // Our candidates ignore the first parameter.
5146 void addGenericBinaryArithmeticOverloads(bool isComparison) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005147 if (!HasArithmeticOrEnumeralCandidateType)
5148 return;
5149
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005150 for (unsigned Left = FirstPromotedArithmeticType;
5151 Left < LastPromotedArithmeticType; ++Left) {
5152 for (unsigned Right = FirstPromotedArithmeticType;
5153 Right < LastPromotedArithmeticType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005154 QualType LandR[2] = { getArithmeticType(Left),
5155 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005156 QualType Result =
5157 isComparison ? S.Context.BoolTy
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005158 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005159 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5160 }
5161 }
5162
5163 // Extension: Add the binary operators ==, !=, <, <=, >=, >, *, /, and the
5164 // conditional operator for vector types.
5165 for (BuiltinCandidateTypeSet::iterator
5166 Vec1 = CandidateTypes[0].vector_begin(),
5167 Vec1End = CandidateTypes[0].vector_end();
5168 Vec1 != Vec1End; ++Vec1) {
5169 for (BuiltinCandidateTypeSet::iterator
5170 Vec2 = CandidateTypes[1].vector_begin(),
5171 Vec2End = CandidateTypes[1].vector_end();
5172 Vec2 != Vec2End; ++Vec2) {
5173 QualType LandR[2] = { *Vec1, *Vec2 };
5174 QualType Result = S.Context.BoolTy;
5175 if (!isComparison) {
5176 if ((*Vec1)->isExtVectorType() || !(*Vec2)->isExtVectorType())
5177 Result = *Vec1;
5178 else
5179 Result = *Vec2;
5180 }
5181
5182 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5183 }
5184 }
5185 }
5186
5187 // C++ [over.built]p17:
5188 //
5189 // For every pair of promoted integral types L and R, there
5190 // exist candidate operator functions of the form
5191 //
5192 // LR operator%(L, R);
5193 // LR operator&(L, R);
5194 // LR operator^(L, R);
5195 // LR operator|(L, R);
5196 // L operator<<(L, R);
5197 // L operator>>(L, R);
5198 //
5199 // where LR is the result of the usual arithmetic conversions
5200 // between types L and R.
5201 void addBinaryBitwiseArithmeticOverloads(OverloadedOperatorKind Op) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005202 if (!HasArithmeticOrEnumeralCandidateType)
5203 return;
5204
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005205 for (unsigned Left = FirstPromotedIntegralType;
5206 Left < LastPromotedIntegralType; ++Left) {
5207 for (unsigned Right = FirstPromotedIntegralType;
5208 Right < LastPromotedIntegralType; ++Right) {
Chandler Carruthc6586e52010-12-12 10:35:00 +00005209 QualType LandR[2] = { getArithmeticType(Left),
5210 getArithmeticType(Right) };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005211 QualType Result = (Op == OO_LessLess || Op == OO_GreaterGreater)
5212 ? LandR[0]
Chandler Carruth3b35b78d2010-12-12 09:59:53 +00005213 : getUsualArithmeticConversions(Left, Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005214 S.AddBuiltinCandidate(Result, LandR, Args, 2, CandidateSet);
5215 }
5216 }
5217 }
5218
5219 // C++ [over.built]p20:
5220 //
5221 // For every pair (T, VQ), where T is an enumeration or
5222 // pointer to member type and VQ is either volatile or
5223 // empty, there exist candidate operator functions of the form
5224 //
5225 // VQ T& operator=(VQ T&, T);
5226 void addAssignmentMemberPointerOrEnumeralOverloads() {
5227 /// Set of (canonical) types that we've already handled.
5228 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5229
5230 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5231 for (BuiltinCandidateTypeSet::iterator
5232 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5233 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5234 Enum != EnumEnd; ++Enum) {
5235 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5236 continue;
5237
5238 AddBuiltinAssignmentOperatorCandidates(S, *Enum, Args, 2,
5239 CandidateSet);
5240 }
5241
5242 for (BuiltinCandidateTypeSet::iterator
5243 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5244 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5245 MemPtr != MemPtrEnd; ++MemPtr) {
5246 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5247 continue;
5248
5249 AddBuiltinAssignmentOperatorCandidates(S, *MemPtr, Args, 2,
5250 CandidateSet);
5251 }
5252 }
5253 }
5254
5255 // C++ [over.built]p19:
5256 //
5257 // For every pair (T, VQ), where T is any type and VQ is either
5258 // volatile or empty, there exist candidate operator functions
5259 // of the form
5260 //
5261 // T*VQ& operator=(T*VQ&, T*);
5262 //
5263 // C++ [over.built]p21:
5264 //
5265 // For every pair (T, VQ), where T is a cv-qualified or
5266 // cv-unqualified object type and VQ is either volatile or
5267 // empty, there exist candidate operator functions of the form
5268 //
5269 // T*VQ& operator+=(T*VQ&, ptrdiff_t);
5270 // T*VQ& operator-=(T*VQ&, ptrdiff_t);
5271 void addAssignmentPointerOverloads(bool isEqualOp) {
5272 /// Set of (canonical) types that we've already handled.
5273 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5274
5275 for (BuiltinCandidateTypeSet::iterator
5276 Ptr = CandidateTypes[0].pointer_begin(),
5277 PtrEnd = CandidateTypes[0].pointer_end();
5278 Ptr != PtrEnd; ++Ptr) {
5279 // If this is operator=, keep track of the builtin candidates we added.
5280 if (isEqualOp)
5281 AddedTypes.insert(S.Context.getCanonicalType(*Ptr));
Douglas Gregor66990032011-01-05 00:13:17 +00005282 else if (!(*Ptr)->getPointeeType()->isObjectType())
5283 continue;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005284
5285 // non-volatile version
5286 QualType ParamTypes[2] = {
5287 S.Context.getLValueReferenceType(*Ptr),
5288 isEqualOp ? *Ptr : S.Context.getPointerDiffType(),
5289 };
5290 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5291 /*IsAssigmentOperator=*/ isEqualOp);
5292
5293 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5294 VisibleTypeConversionsQuals.hasVolatile()) {
5295 // volatile version
5296 ParamTypes[0] =
5297 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
5298 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5299 /*IsAssigmentOperator=*/isEqualOp);
5300 }
5301 }
5302
5303 if (isEqualOp) {
5304 for (BuiltinCandidateTypeSet::iterator
5305 Ptr = CandidateTypes[1].pointer_begin(),
5306 PtrEnd = CandidateTypes[1].pointer_end();
5307 Ptr != PtrEnd; ++Ptr) {
5308 // Make sure we don't add the same candidate twice.
5309 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5310 continue;
5311
Chandler Carruth8e543b32010-12-12 08:17:55 +00005312 QualType ParamTypes[2] = {
5313 S.Context.getLValueReferenceType(*Ptr),
5314 *Ptr,
5315 };
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005316
5317 // non-volatile version
5318 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5319 /*IsAssigmentOperator=*/true);
5320
5321 if (!S.Context.getCanonicalType(*Ptr).isVolatileQualified() &&
5322 VisibleTypeConversionsQuals.hasVolatile()) {
5323 // volatile version
5324 ParamTypes[0] =
5325 S.Context.getLValueReferenceType(S.Context.getVolatileType(*Ptr));
Chandler Carruth8e543b32010-12-12 08:17:55 +00005326 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5327 CandidateSet, /*IsAssigmentOperator=*/true);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005328 }
5329 }
5330 }
5331 }
5332
5333 // C++ [over.built]p18:
5334 //
5335 // For every triple (L, VQ, R), where L is an arithmetic type,
5336 // VQ is either volatile or empty, and R is a promoted
5337 // arithmetic type, there exist candidate operator functions of
5338 // the form
5339 //
5340 // VQ L& operator=(VQ L&, R);
5341 // VQ L& operator*=(VQ L&, R);
5342 // VQ L& operator/=(VQ L&, R);
5343 // VQ L& operator+=(VQ L&, R);
5344 // VQ L& operator-=(VQ L&, R);
5345 void addAssignmentArithmeticOverloads(bool isEqualOp) {
Chandler Carruth00a38332010-12-13 01:44:01 +00005346 if (!HasArithmeticOrEnumeralCandidateType)
5347 return;
5348
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005349 for (unsigned Left = 0; Left < NumArithmeticTypes; ++Left) {
5350 for (unsigned Right = FirstPromotedArithmeticType;
5351 Right < LastPromotedArithmeticType; ++Right) {
5352 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005353 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005354
5355 // Add this built-in operator as a candidate (VQ is empty).
5356 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005357 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005358 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5359 /*IsAssigmentOperator=*/isEqualOp);
5360
5361 // Add this built-in operator as a candidate (VQ is 'volatile').
5362 if (VisibleTypeConversionsQuals.hasVolatile()) {
5363 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005364 S.Context.getVolatileType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005365 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005366 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5367 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005368 /*IsAssigmentOperator=*/isEqualOp);
5369 }
5370 }
5371 }
5372
5373 // Extension: Add the binary operators =, +=, -=, *=, /= for vector types.
5374 for (BuiltinCandidateTypeSet::iterator
5375 Vec1 = CandidateTypes[0].vector_begin(),
5376 Vec1End = CandidateTypes[0].vector_end();
5377 Vec1 != Vec1End; ++Vec1) {
5378 for (BuiltinCandidateTypeSet::iterator
5379 Vec2 = CandidateTypes[1].vector_begin(),
5380 Vec2End = CandidateTypes[1].vector_end();
5381 Vec2 != Vec2End; ++Vec2) {
5382 QualType ParamTypes[2];
5383 ParamTypes[1] = *Vec2;
5384 // Add this built-in operator as a candidate (VQ is empty).
5385 ParamTypes[0] = S.Context.getLValueReferenceType(*Vec1);
5386 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet,
5387 /*IsAssigmentOperator=*/isEqualOp);
5388
5389 // Add this built-in operator as a candidate (VQ is 'volatile').
5390 if (VisibleTypeConversionsQuals.hasVolatile()) {
5391 ParamTypes[0] = S.Context.getVolatileType(*Vec1);
5392 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
Chandler Carruth8e543b32010-12-12 08:17:55 +00005393 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5394 CandidateSet,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005395 /*IsAssigmentOperator=*/isEqualOp);
5396 }
5397 }
5398 }
5399 }
5400
5401 // C++ [over.built]p22:
5402 //
5403 // For every triple (L, VQ, R), where L is an integral type, VQ
5404 // is either volatile or empty, and R is a promoted integral
5405 // type, there exist candidate operator functions of the form
5406 //
5407 // VQ L& operator%=(VQ L&, R);
5408 // VQ L& operator<<=(VQ L&, R);
5409 // VQ L& operator>>=(VQ L&, R);
5410 // VQ L& operator&=(VQ L&, R);
5411 // VQ L& operator^=(VQ L&, R);
5412 // VQ L& operator|=(VQ L&, R);
5413 void addAssignmentIntegralOverloads() {
Chandler Carruth00a38332010-12-13 01:44:01 +00005414 if (!HasArithmeticOrEnumeralCandidateType)
5415 return;
5416
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005417 for (unsigned Left = FirstIntegralType; Left < LastIntegralType; ++Left) {
5418 for (unsigned Right = FirstPromotedIntegralType;
5419 Right < LastPromotedIntegralType; ++Right) {
5420 QualType ParamTypes[2];
Chandler Carruthc6586e52010-12-12 10:35:00 +00005421 ParamTypes[1] = getArithmeticType(Right);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005422
5423 // Add this built-in operator as a candidate (VQ is empty).
5424 ParamTypes[0] =
Chandler Carruthc6586e52010-12-12 10:35:00 +00005425 S.Context.getLValueReferenceType(getArithmeticType(Left));
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005426 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2, CandidateSet);
5427 if (VisibleTypeConversionsQuals.hasVolatile()) {
5428 // Add this built-in operator as a candidate (VQ is 'volatile').
Chandler Carruthc6586e52010-12-12 10:35:00 +00005429 ParamTypes[0] = getArithmeticType(Left);
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005430 ParamTypes[0] = S.Context.getVolatileType(ParamTypes[0]);
5431 ParamTypes[0] = S.Context.getLValueReferenceType(ParamTypes[0]);
5432 S.AddBuiltinCandidate(ParamTypes[0], ParamTypes, Args, 2,
5433 CandidateSet);
5434 }
5435 }
5436 }
5437 }
5438
5439 // C++ [over.operator]p23:
5440 //
5441 // There also exist candidate operator functions of the form
5442 //
5443 // bool operator!(bool);
5444 // bool operator&&(bool, bool);
5445 // bool operator||(bool, bool);
5446 void addExclaimOverload() {
5447 QualType ParamTy = S.Context.BoolTy;
5448 S.AddBuiltinCandidate(ParamTy, &ParamTy, Args, 1, CandidateSet,
5449 /*IsAssignmentOperator=*/false,
5450 /*NumContextualBoolArguments=*/1);
5451 }
5452 void addAmpAmpOrPipePipeOverload() {
5453 QualType ParamTypes[2] = { S.Context.BoolTy, S.Context.BoolTy };
5454 S.AddBuiltinCandidate(S.Context.BoolTy, ParamTypes, Args, 2, CandidateSet,
5455 /*IsAssignmentOperator=*/false,
5456 /*NumContextualBoolArguments=*/2);
5457 }
5458
5459 // C++ [over.built]p13:
5460 //
5461 // For every cv-qualified or cv-unqualified object type T there
5462 // exist candidate operator functions of the form
5463 //
5464 // T* operator+(T*, ptrdiff_t); [ABOVE]
5465 // T& operator[](T*, ptrdiff_t);
5466 // T* operator-(T*, ptrdiff_t); [ABOVE]
5467 // T* operator+(ptrdiff_t, T*); [ABOVE]
5468 // T& operator[](ptrdiff_t, T*);
5469 void addSubscriptOverloads() {
5470 for (BuiltinCandidateTypeSet::iterator
5471 Ptr = CandidateTypes[0].pointer_begin(),
5472 PtrEnd = CandidateTypes[0].pointer_end();
5473 Ptr != PtrEnd; ++Ptr) {
5474 QualType ParamTypes[2] = { *Ptr, S.Context.getPointerDiffType() };
5475 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005476 if (!PointeeType->isObjectType())
5477 continue;
5478
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005479 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5480
5481 // T& operator[](T*, ptrdiff_t)
5482 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5483 }
5484
5485 for (BuiltinCandidateTypeSet::iterator
5486 Ptr = CandidateTypes[1].pointer_begin(),
5487 PtrEnd = CandidateTypes[1].pointer_end();
5488 Ptr != PtrEnd; ++Ptr) {
5489 QualType ParamTypes[2] = { S.Context.getPointerDiffType(), *Ptr };
5490 QualType PointeeType = (*Ptr)->getPointeeType();
Douglas Gregor66990032011-01-05 00:13:17 +00005491 if (!PointeeType->isObjectType())
5492 continue;
5493
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005494 QualType ResultTy = S.Context.getLValueReferenceType(PointeeType);
5495
5496 // T& operator[](ptrdiff_t, T*)
5497 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5498 }
5499 }
5500
5501 // C++ [over.built]p11:
5502 // For every quintuple (C1, C2, T, CV1, CV2), where C2 is a class type,
5503 // C1 is the same type as C2 or is a derived class of C2, T is an object
5504 // type or a function type, and CV1 and CV2 are cv-qualifier-seqs,
5505 // there exist candidate operator functions of the form
5506 //
5507 // CV12 T& operator->*(CV1 C1*, CV2 T C2::*);
5508 //
5509 // where CV12 is the union of CV1 and CV2.
5510 void addArrowStarOverloads() {
5511 for (BuiltinCandidateTypeSet::iterator
5512 Ptr = CandidateTypes[0].pointer_begin(),
5513 PtrEnd = CandidateTypes[0].pointer_end();
5514 Ptr != PtrEnd; ++Ptr) {
5515 QualType C1Ty = (*Ptr);
5516 QualType C1;
5517 QualifierCollector Q1;
5518 C1 = QualType(Q1.strip(C1Ty->getPointeeType()), 0);
5519 if (!isa<RecordType>(C1))
5520 continue;
5521 // heuristic to reduce number of builtin candidates in the set.
5522 // Add volatile/restrict version only if there are conversions to a
5523 // volatile/restrict type.
5524 if (!VisibleTypeConversionsQuals.hasVolatile() && Q1.hasVolatile())
5525 continue;
5526 if (!VisibleTypeConversionsQuals.hasRestrict() && Q1.hasRestrict())
5527 continue;
5528 for (BuiltinCandidateTypeSet::iterator
5529 MemPtr = CandidateTypes[1].member_pointer_begin(),
5530 MemPtrEnd = CandidateTypes[1].member_pointer_end();
5531 MemPtr != MemPtrEnd; ++MemPtr) {
5532 const MemberPointerType *mptr = cast<MemberPointerType>(*MemPtr);
5533 QualType C2 = QualType(mptr->getClass(), 0);
5534 C2 = C2.getUnqualifiedType();
5535 if (C1 != C2 && !S.IsDerivedFrom(C1, C2))
5536 break;
5537 QualType ParamTypes[2] = { *Ptr, *MemPtr };
5538 // build CV12 T&
5539 QualType T = mptr->getPointeeType();
5540 if (!VisibleTypeConversionsQuals.hasVolatile() &&
5541 T.isVolatileQualified())
5542 continue;
5543 if (!VisibleTypeConversionsQuals.hasRestrict() &&
5544 T.isRestrictQualified())
5545 continue;
5546 T = Q1.apply(S.Context, T);
5547 QualType ResultTy = S.Context.getLValueReferenceType(T);
5548 S.AddBuiltinCandidate(ResultTy, ParamTypes, Args, 2, CandidateSet);
5549 }
5550 }
5551 }
5552
5553 // Note that we don't consider the first argument, since it has been
5554 // contextually converted to bool long ago. The candidates below are
5555 // therefore added as binary.
5556 //
5557 // C++ [over.built]p25:
5558 // For every type T, where T is a pointer, pointer-to-member, or scoped
5559 // enumeration type, there exist candidate operator functions of the form
5560 //
5561 // T operator?(bool, T, T);
5562 //
5563 void addConditionalOperatorOverloads() {
5564 /// Set of (canonical) types that we've already handled.
5565 llvm::SmallPtrSet<QualType, 8> AddedTypes;
5566
5567 for (unsigned ArgIdx = 0; ArgIdx < 2; ++ArgIdx) {
5568 for (BuiltinCandidateTypeSet::iterator
5569 Ptr = CandidateTypes[ArgIdx].pointer_begin(),
5570 PtrEnd = CandidateTypes[ArgIdx].pointer_end();
5571 Ptr != PtrEnd; ++Ptr) {
5572 if (!AddedTypes.insert(S.Context.getCanonicalType(*Ptr)))
5573 continue;
5574
5575 QualType ParamTypes[2] = { *Ptr, *Ptr };
5576 S.AddBuiltinCandidate(*Ptr, ParamTypes, Args, 2, CandidateSet);
5577 }
5578
5579 for (BuiltinCandidateTypeSet::iterator
5580 MemPtr = CandidateTypes[ArgIdx].member_pointer_begin(),
5581 MemPtrEnd = CandidateTypes[ArgIdx].member_pointer_end();
5582 MemPtr != MemPtrEnd; ++MemPtr) {
5583 if (!AddedTypes.insert(S.Context.getCanonicalType(*MemPtr)))
5584 continue;
5585
5586 QualType ParamTypes[2] = { *MemPtr, *MemPtr };
5587 S.AddBuiltinCandidate(*MemPtr, ParamTypes, Args, 2, CandidateSet);
5588 }
5589
5590 if (S.getLangOptions().CPlusPlus0x) {
5591 for (BuiltinCandidateTypeSet::iterator
5592 Enum = CandidateTypes[ArgIdx].enumeration_begin(),
5593 EnumEnd = CandidateTypes[ArgIdx].enumeration_end();
5594 Enum != EnumEnd; ++Enum) {
5595 if (!(*Enum)->getAs<EnumType>()->getDecl()->isScoped())
5596 continue;
5597
5598 if (!AddedTypes.insert(S.Context.getCanonicalType(*Enum)))
5599 continue;
5600
5601 QualType ParamTypes[2] = { *Enum, *Enum };
5602 S.AddBuiltinCandidate(*Enum, ParamTypes, Args, 2, CandidateSet);
5603 }
5604 }
5605 }
5606 }
5607};
5608
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005609} // end anonymous namespace
5610
5611/// AddBuiltinOperatorCandidates - Add the appropriate built-in
5612/// operator overloads to the candidate set (C++ [over.built]), based
5613/// on the operator @p Op and the arguments given. For example, if the
5614/// operator is a binary '+', this routine might add "int
5615/// operator+(int, int)" to cover integer addition.
5616void
5617Sema::AddBuiltinOperatorCandidates(OverloadedOperatorKind Op,
5618 SourceLocation OpLoc,
5619 Expr **Args, unsigned NumArgs,
5620 OverloadCandidateSet& CandidateSet) {
Douglas Gregora11693b2008-11-12 17:17:38 +00005621 // Find all of the types that the arguments can convert to, but only
5622 // if the operator we're looking at has built-in operator candidates
Chandler Carruth00a38332010-12-13 01:44:01 +00005623 // that make use of these types. Also record whether we encounter non-record
5624 // candidate types or either arithmetic or enumeral candidate types.
Fariborz Jahanian3b937fa2009-10-15 17:14:05 +00005625 Qualifiers VisibleTypeConversionsQuals;
5626 VisibleTypeConversionsQuals.addConst();
Fariborz Jahanianb9e8c422009-10-19 21:30:45 +00005627 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
5628 VisibleTypeConversionsQuals += CollectVRQualifiers(Context, Args[ArgIdx]);
Chandler Carruth00a38332010-12-13 01:44:01 +00005629
5630 bool HasNonRecordCandidateType = false;
5631 bool HasArithmeticOrEnumeralCandidateType = false;
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005632 llvm::SmallVector<BuiltinCandidateTypeSet, 2> CandidateTypes;
5633 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx) {
5634 CandidateTypes.push_back(BuiltinCandidateTypeSet(*this));
5635 CandidateTypes[ArgIdx].AddTypesConvertedFrom(Args[ArgIdx]->getType(),
5636 OpLoc,
5637 true,
5638 (Op == OO_Exclaim ||
5639 Op == OO_AmpAmp ||
5640 Op == OO_PipePipe),
5641 VisibleTypeConversionsQuals);
Chandler Carruth00a38332010-12-13 01:44:01 +00005642 HasNonRecordCandidateType = HasNonRecordCandidateType ||
5643 CandidateTypes[ArgIdx].hasNonRecordTypes();
5644 HasArithmeticOrEnumeralCandidateType =
5645 HasArithmeticOrEnumeralCandidateType ||
5646 CandidateTypes[ArgIdx].hasArithmeticOrEnumeralTypes();
Douglas Gregorb37c9af2010-11-03 17:00:07 +00005647 }
Douglas Gregora11693b2008-11-12 17:17:38 +00005648
Chandler Carruth00a38332010-12-13 01:44:01 +00005649 // Exit early when no non-record types have been added to the candidate set
5650 // for any of the arguments to the operator.
5651 if (!HasNonRecordCandidateType)
5652 return;
5653
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005654 // Setup an object to manage the common state for building overloads.
5655 BuiltinOperatorOverloadBuilder OpBuilder(*this, Args, NumArgs,
5656 VisibleTypeConversionsQuals,
Chandler Carruth00a38332010-12-13 01:44:01 +00005657 HasArithmeticOrEnumeralCandidateType,
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005658 CandidateTypes, CandidateSet);
5659
5660 // Dispatch over the operation to add in only those overloads which apply.
Douglas Gregora11693b2008-11-12 17:17:38 +00005661 switch (Op) {
5662 case OO_None:
5663 case NUM_OVERLOADED_OPERATORS:
5664 assert(false && "Expected an overloaded operator");
5665 break;
5666
Chandler Carruth5184de02010-12-12 08:51:33 +00005667 case OO_New:
5668 case OO_Delete:
5669 case OO_Array_New:
5670 case OO_Array_Delete:
5671 case OO_Call:
5672 assert(false && "Special operators don't use AddBuiltinOperatorCandidates");
5673 break;
5674
5675 case OO_Comma:
5676 case OO_Arrow:
5677 // C++ [over.match.oper]p3:
5678 // -- For the operator ',', the unary operator '&', or the
5679 // operator '->', the built-in candidates set is empty.
Douglas Gregord08452f2008-11-19 15:42:04 +00005680 break;
5681
5682 case OO_Plus: // '+' is either unary or binary
Chandler Carruth9694b9c2010-12-12 08:41:34 +00005683 if (NumArgs == 1)
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005684 OpBuilder.addUnaryPlusPointerOverloads();
Chandler Carruth9694b9c2010-12-12 08:41:34 +00005685 // Fall through.
Douglas Gregord08452f2008-11-19 15:42:04 +00005686
5687 case OO_Minus: // '-' is either unary or binary
Chandler Carruthf9802442010-12-12 08:39:38 +00005688 if (NumArgs == 1) {
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005689 OpBuilder.addUnaryPlusOrMinusArithmeticOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00005690 } else {
5691 OpBuilder.addBinaryPlusOrMinusPointerOverloads(Op);
5692 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5693 }
Douglas Gregord08452f2008-11-19 15:42:04 +00005694 break;
5695
Chandler Carruth5184de02010-12-12 08:51:33 +00005696 case OO_Star: // '*' is either unary or binary
Douglas Gregord08452f2008-11-19 15:42:04 +00005697 if (NumArgs == 1)
Chandler Carruth5184de02010-12-12 08:51:33 +00005698 OpBuilder.addUnaryStarPointerOverloads();
5699 else
5700 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5701 break;
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005702
Chandler Carruth5184de02010-12-12 08:51:33 +00005703 case OO_Slash:
5704 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
Chandler Carruth9de23cd2010-12-12 08:45:02 +00005705 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005706
5707 case OO_PlusPlus:
5708 case OO_MinusMinus:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005709 OpBuilder.addPlusPlusMinusMinusArithmeticOverloads(Op);
5710 OpBuilder.addPlusPlusMinusMinusPointerOverloads();
Douglas Gregord08452f2008-11-19 15:42:04 +00005711 break;
5712
Douglas Gregor84605ae2009-08-24 13:43:27 +00005713 case OO_EqualEqual:
5714 case OO_ExclaimEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005715 OpBuilder.addEqualEqualOrNotEqualMemberPointerOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00005716 // Fall through.
Chandler Carruth9de23cd2010-12-12 08:45:02 +00005717
Douglas Gregora11693b2008-11-12 17:17:38 +00005718 case OO_Less:
5719 case OO_Greater:
5720 case OO_LessEqual:
5721 case OO_GreaterEqual:
Chandler Carruthc02db8c2010-12-12 09:14:11 +00005722 OpBuilder.addRelationalPointerOrEnumeralOverloads();
Chandler Carruth0375e952010-12-12 08:32:28 +00005723 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/true);
5724 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005725
Douglas Gregora11693b2008-11-12 17:17:38 +00005726 case OO_Percent:
Douglas Gregora11693b2008-11-12 17:17:38 +00005727 case OO_Caret:
5728 case OO_Pipe:
5729 case OO_LessLess:
5730 case OO_GreaterGreater:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005731 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
Douglas Gregora11693b2008-11-12 17:17:38 +00005732 break;
5733
Chandler Carruth5184de02010-12-12 08:51:33 +00005734 case OO_Amp: // '&' is either unary or binary
5735 if (NumArgs == 1)
5736 // C++ [over.match.oper]p3:
5737 // -- For the operator ',', the unary operator '&', or the
5738 // operator '->', the built-in candidates set is empty.
5739 break;
5740
5741 OpBuilder.addBinaryBitwiseArithmeticOverloads(Op);
5742 break;
5743
5744 case OO_Tilde:
5745 OpBuilder.addUnaryTildePromotedIntegralOverloads();
5746 break;
5747
Douglas Gregora11693b2008-11-12 17:17:38 +00005748 case OO_Equal:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005749 OpBuilder.addAssignmentMemberPointerOrEnumeralOverloads();
Douglas Gregorcbfbca12010-05-19 03:21:00 +00005750 // Fall through.
Douglas Gregora11693b2008-11-12 17:17:38 +00005751
5752 case OO_PlusEqual:
5753 case OO_MinusEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005754 OpBuilder.addAssignmentPointerOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005755 // Fall through.
5756
5757 case OO_StarEqual:
5758 case OO_SlashEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005759 OpBuilder.addAssignmentArithmeticOverloads(Op == OO_Equal);
Douglas Gregora11693b2008-11-12 17:17:38 +00005760 break;
5761
5762 case OO_PercentEqual:
5763 case OO_LessLessEqual:
5764 case OO_GreaterGreaterEqual:
5765 case OO_AmpEqual:
5766 case OO_CaretEqual:
5767 case OO_PipeEqual:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005768 OpBuilder.addAssignmentIntegralOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005769 break;
5770
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005771 case OO_Exclaim:
5772 OpBuilder.addExclaimOverload();
Douglas Gregord08452f2008-11-19 15:42:04 +00005773 break;
Douglas Gregord08452f2008-11-19 15:42:04 +00005774
Douglas Gregora11693b2008-11-12 17:17:38 +00005775 case OO_AmpAmp:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005776 case OO_PipePipe:
5777 OpBuilder.addAmpAmpOrPipePipeOverload();
Douglas Gregora11693b2008-11-12 17:17:38 +00005778 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005779
5780 case OO_Subscript:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005781 OpBuilder.addSubscriptOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005782 break;
5783
5784 case OO_ArrowStar:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005785 OpBuilder.addArrowStarOverloads();
Douglas Gregora11693b2008-11-12 17:17:38 +00005786 break;
Sebastian Redl1a99f442009-04-16 17:51:27 +00005787
5788 case OO_Conditional:
Chandler Carruth85c2d09a2010-12-12 08:11:30 +00005789 OpBuilder.addConditionalOperatorOverloads();
Chandler Carruthf9802442010-12-12 08:39:38 +00005790 OpBuilder.addGenericBinaryArithmeticOverloads(/*isComparison=*/false);
5791 break;
Douglas Gregora11693b2008-11-12 17:17:38 +00005792 }
5793}
5794
Douglas Gregore254f902009-02-04 00:32:51 +00005795/// \brief Add function candidates found via argument-dependent lookup
5796/// to the set of overloading candidates.
5797///
5798/// This routine performs argument-dependent name lookup based on the
5799/// given function name (which may also be an operator name) and adds
5800/// all of the overload candidates found by ADL to the overload
5801/// candidate set (C++ [basic.lookup.argdep]).
Mike Stump11289f42009-09-09 15:08:12 +00005802void
Douglas Gregore254f902009-02-04 00:32:51 +00005803Sema::AddArgumentDependentLookupCandidates(DeclarationName Name,
John McCall4c4c1df2010-01-26 03:27:55 +00005804 bool Operator,
Douglas Gregore254f902009-02-04 00:32:51 +00005805 Expr **Args, unsigned NumArgs,
John McCall6b51f282009-11-23 01:53:49 +00005806 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00005807 OverloadCandidateSet& CandidateSet,
5808 bool PartialOverloading) {
John McCall8fe68082010-01-26 07:16:45 +00005809 ADLResult Fns;
Douglas Gregore254f902009-02-04 00:32:51 +00005810
John McCall91f61fc2010-01-26 06:04:06 +00005811 // FIXME: This approach for uniquing ADL results (and removing
5812 // redundant candidates from the set) relies on pointer-equality,
5813 // which means we need to key off the canonical decl. However,
5814 // always going back to the canonical decl might not get us the
5815 // right set of default arguments. What default arguments are
5816 // we supposed to consider on ADL candidates, anyway?
5817
Douglas Gregorcabea402009-09-22 15:41:20 +00005818 // FIXME: Pass in the explicit template arguments?
John McCall8fe68082010-01-26 07:16:45 +00005819 ArgumentDependentLookup(Name, Operator, Args, NumArgs, Fns);
Douglas Gregore254f902009-02-04 00:32:51 +00005820
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005821 // Erase all of the candidates we already knew about.
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005822 for (OverloadCandidateSet::iterator Cand = CandidateSet.begin(),
5823 CandEnd = CandidateSet.end();
5824 Cand != CandEnd; ++Cand)
Douglas Gregor15448f82009-06-27 21:05:07 +00005825 if (Cand->Function) {
John McCall8fe68082010-01-26 07:16:45 +00005826 Fns.erase(Cand->Function);
Douglas Gregor15448f82009-06-27 21:05:07 +00005827 if (FunctionTemplateDecl *FunTmpl = Cand->Function->getPrimaryTemplate())
John McCall8fe68082010-01-26 07:16:45 +00005828 Fns.erase(FunTmpl);
Douglas Gregor15448f82009-06-27 21:05:07 +00005829 }
Douglas Gregord2b7ef62009-03-13 00:33:25 +00005830
5831 // For each of the ADL candidates we found, add it to the overload
5832 // set.
John McCall8fe68082010-01-26 07:16:45 +00005833 for (ADLResult::iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
John McCalla0296f72010-03-19 07:35:19 +00005834 DeclAccessPair FoundDecl = DeclAccessPair::make(*I, AS_none);
John McCall4c4c1df2010-01-26 03:27:55 +00005835 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(*I)) {
John McCall6b51f282009-11-23 01:53:49 +00005836 if (ExplicitTemplateArgs)
Douglas Gregorcabea402009-09-22 15:41:20 +00005837 continue;
5838
John McCalla0296f72010-03-19 07:35:19 +00005839 AddOverloadCandidate(FD, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00005840 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00005841 } else
John McCall4c4c1df2010-01-26 03:27:55 +00005842 AddTemplateOverloadCandidate(cast<FunctionTemplateDecl>(*I),
John McCalla0296f72010-03-19 07:35:19 +00005843 FoundDecl, ExplicitTemplateArgs,
Douglas Gregor89026b52009-06-30 23:57:56 +00005844 Args, NumArgs, CandidateSet);
Douglas Gregor15448f82009-06-27 21:05:07 +00005845 }
Douglas Gregore254f902009-02-04 00:32:51 +00005846}
5847
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005848/// isBetterOverloadCandidate - Determines whether the first overload
5849/// candidate is a better candidate than the second (C++ 13.3.3p1).
Mike Stump11289f42009-09-09 15:08:12 +00005850bool
John McCall5c32be02010-08-24 20:38:10 +00005851isBetterOverloadCandidate(Sema &S,
Nick Lewycky9331ed82010-11-20 01:29:55 +00005852 const OverloadCandidate &Cand1,
5853 const OverloadCandidate &Cand2,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005854 SourceLocation Loc,
5855 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005856 // Define viable functions to be better candidates than non-viable
5857 // functions.
5858 if (!Cand2.Viable)
5859 return Cand1.Viable;
5860 else if (!Cand1.Viable)
5861 return false;
5862
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005863 // C++ [over.match.best]p1:
5864 //
5865 // -- if F is a static member function, ICS1(F) is defined such
5866 // that ICS1(F) is neither better nor worse than ICS1(G) for
5867 // any function G, and, symmetrically, ICS1(G) is neither
5868 // better nor worse than ICS1(F).
5869 unsigned StartArg = 0;
5870 if (Cand1.IgnoreObjectArgument || Cand2.IgnoreObjectArgument)
5871 StartArg = 1;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005872
Douglas Gregord3cb3562009-07-07 23:38:56 +00005873 // C++ [over.match.best]p1:
Mike Stump11289f42009-09-09 15:08:12 +00005874 // A viable function F1 is defined to be a better function than another
5875 // viable function F2 if for all arguments i, ICSi(F1) is not a worse
Douglas Gregord3cb3562009-07-07 23:38:56 +00005876 // conversion sequence than ICSi(F2), and then...
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005877 unsigned NumArgs = Cand1.Conversions.size();
5878 assert(Cand2.Conversions.size() == NumArgs && "Overload candidate mismatch");
5879 bool HasBetterConversion = false;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00005880 for (unsigned ArgIdx = StartArg; ArgIdx < NumArgs; ++ArgIdx) {
John McCall5c32be02010-08-24 20:38:10 +00005881 switch (CompareImplicitConversionSequences(S,
5882 Cand1.Conversions[ArgIdx],
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005883 Cand2.Conversions[ArgIdx])) {
5884 case ImplicitConversionSequence::Better:
5885 // Cand1 has a better conversion sequence.
5886 HasBetterConversion = true;
5887 break;
5888
5889 case ImplicitConversionSequence::Worse:
5890 // Cand1 can't be better than Cand2.
5891 return false;
5892
5893 case ImplicitConversionSequence::Indistinguishable:
5894 // Do nothing.
5895 break;
5896 }
5897 }
5898
Mike Stump11289f42009-09-09 15:08:12 +00005899 // -- for some argument j, ICSj(F1) is a better conversion sequence than
Douglas Gregord3cb3562009-07-07 23:38:56 +00005900 // ICSj(F2), or, if not that,
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005901 if (HasBetterConversion)
5902 return true;
5903
Mike Stump11289f42009-09-09 15:08:12 +00005904 // - F1 is a non-template function and F2 is a function template
Douglas Gregord3cb3562009-07-07 23:38:56 +00005905 // specialization, or, if not that,
Douglas Gregorce21919b2010-06-08 21:03:17 +00005906 if ((!Cand1.Function || !Cand1.Function->getPrimaryTemplate()) &&
Douglas Gregord3cb3562009-07-07 23:38:56 +00005907 Cand2.Function && Cand2.Function->getPrimaryTemplate())
5908 return true;
Mike Stump11289f42009-09-09 15:08:12 +00005909
5910 // -- F1 and F2 are function template specializations, and the function
5911 // template for F1 is more specialized than the template for F2
5912 // according to the partial ordering rules described in 14.5.5.2, or,
Douglas Gregord3cb3562009-07-07 23:38:56 +00005913 // if not that,
Douglas Gregor55137cb2009-08-02 23:46:29 +00005914 if (Cand1.Function && Cand1.Function->getPrimaryTemplate() &&
Douglas Gregor6edd9772011-01-19 23:54:39 +00005915 Cand2.Function && Cand2.Function->getPrimaryTemplate()) {
Douglas Gregor05155d82009-08-21 23:19:43 +00005916 if (FunctionTemplateDecl *BetterTemplate
John McCall5c32be02010-08-24 20:38:10 +00005917 = S.getMoreSpecializedTemplate(Cand1.Function->getPrimaryTemplate(),
5918 Cand2.Function->getPrimaryTemplate(),
5919 Loc,
Douglas Gregor6010da02009-09-14 23:02:14 +00005920 isa<CXXConversionDecl>(Cand1.Function)? TPOC_Conversion
Douglas Gregorb837ea42011-01-11 17:34:58 +00005921 : TPOC_Call,
Douglas Gregor6edd9772011-01-19 23:54:39 +00005922 Cand1.ExplicitCallArguments))
Douglas Gregor05155d82009-08-21 23:19:43 +00005923 return BetterTemplate == Cand1.Function->getPrimaryTemplate();
Douglas Gregor6edd9772011-01-19 23:54:39 +00005924 }
5925
Douglas Gregora1f013e2008-11-07 22:36:19 +00005926 // -- the context is an initialization by user-defined conversion
5927 // (see 8.5, 13.3.1.5) and the standard conversion sequence
5928 // from the return type of F1 to the destination type (i.e.,
5929 // the type of the entity being initialized) is a better
5930 // conversion sequence than the standard conversion sequence
5931 // from the return type of F2 to the destination type.
Douglas Gregord5b730c92010-09-12 08:07:23 +00005932 if (UserDefinedConversion && Cand1.Function && Cand2.Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005933 isa<CXXConversionDecl>(Cand1.Function) &&
Douglas Gregora1f013e2008-11-07 22:36:19 +00005934 isa<CXXConversionDecl>(Cand2.Function)) {
John McCall5c32be02010-08-24 20:38:10 +00005935 switch (CompareStandardConversionSequences(S,
5936 Cand1.FinalConversion,
Douglas Gregora1f013e2008-11-07 22:36:19 +00005937 Cand2.FinalConversion)) {
5938 case ImplicitConversionSequence::Better:
5939 // Cand1 has a better conversion sequence.
5940 return true;
5941
5942 case ImplicitConversionSequence::Worse:
5943 // Cand1 can't be better than Cand2.
5944 return false;
5945
5946 case ImplicitConversionSequence::Indistinguishable:
5947 // Do nothing
5948 break;
5949 }
5950 }
5951
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005952 return false;
5953}
5954
Mike Stump11289f42009-09-09 15:08:12 +00005955/// \brief Computes the best viable function (C++ 13.3.3)
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005956/// within an overload candidate set.
5957///
5958/// \param CandidateSet the set of candidate functions.
5959///
5960/// \param Loc the location of the function name (or operator symbol) for
5961/// which overload resolution occurs.
5962///
Mike Stump11289f42009-09-09 15:08:12 +00005963/// \param Best f overload resolution was successful or found a deleted
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00005964/// function, Best points to the candidate function found.
5965///
5966/// \returns The result of overload resolution.
John McCall5c32be02010-08-24 20:38:10 +00005967OverloadingResult
5968OverloadCandidateSet::BestViableFunction(Sema &S, SourceLocation Loc,
Nick Lewycky9331ed82010-11-20 01:29:55 +00005969 iterator &Best,
Douglas Gregord5b730c92010-09-12 08:07:23 +00005970 bool UserDefinedConversion) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005971 // Find the best viable function.
John McCall5c32be02010-08-24 20:38:10 +00005972 Best = end();
5973 for (iterator Cand = begin(); Cand != end(); ++Cand) {
5974 if (Cand->Viable)
Douglas Gregord5b730c92010-09-12 08:07:23 +00005975 if (Best == end() || isBetterOverloadCandidate(S, *Cand, *Best, Loc,
5976 UserDefinedConversion))
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005977 Best = Cand;
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005978 }
5979
5980 // If we didn't find any viable functions, abort.
John McCall5c32be02010-08-24 20:38:10 +00005981 if (Best == end())
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005982 return OR_No_Viable_Function;
5983
5984 // Make sure that this function is better than every other viable
5985 // function. If not, we have an ambiguity.
John McCall5c32be02010-08-24 20:38:10 +00005986 for (iterator Cand = begin(); Cand != end(); ++Cand) {
Mike Stump11289f42009-09-09 15:08:12 +00005987 if (Cand->Viable &&
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005988 Cand != Best &&
Douglas Gregord5b730c92010-09-12 08:07:23 +00005989 !isBetterOverloadCandidate(S, *Best, *Cand, Loc,
5990 UserDefinedConversion)) {
John McCall5c32be02010-08-24 20:38:10 +00005991 Best = end();
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005992 return OR_Ambiguous;
Douglas Gregorab7897a2008-11-19 22:57:39 +00005993 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005994 }
Mike Stump11289f42009-09-09 15:08:12 +00005995
Douglas Gregor5251f1b2008-10-21 16:13:35 +00005996 // Best is the best viable function.
Douglas Gregor171c45a2009-02-18 21:56:37 +00005997 if (Best->Function &&
Mike Stump11289f42009-09-09 15:08:12 +00005998 (Best->Function->isDeleted() ||
Argyrios Kyrtzidisb4b64ca2009-06-30 02:34:44 +00005999 Best->Function->getAttr<UnavailableAttr>()))
Douglas Gregor171c45a2009-02-18 21:56:37 +00006000 return OR_Deleted;
6001
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006002 // C++ [basic.def.odr]p2:
6003 // An overloaded function is used if it is selected by overload resolution
Mike Stump11289f42009-09-09 15:08:12 +00006004 // when referred to from a potentially-evaluated expression. [Note: this
6005 // covers calls to named functions (5.2.2), operator overloading
Douglas Gregorc9c02ed2009-06-19 23:52:42 +00006006 // (clause 13), user-defined conversions (12.3.2), allocation function for
6007 // placement new (5.3.4), as well as non-default initialization (8.5).
6008 if (Best->Function)
John McCall5c32be02010-08-24 20:38:10 +00006009 S.MarkDeclarationReferenced(Loc, Best->Function);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006010
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006011 return OR_Success;
6012}
6013
John McCall53262c92010-01-12 02:15:36 +00006014namespace {
6015
6016enum OverloadCandidateKind {
6017 oc_function,
6018 oc_method,
6019 oc_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006020 oc_function_template,
6021 oc_method_template,
6022 oc_constructor_template,
John McCall53262c92010-01-12 02:15:36 +00006023 oc_implicit_default_constructor,
6024 oc_implicit_copy_constructor,
John McCalle1ac8d12010-01-13 00:25:19 +00006025 oc_implicit_copy_assignment
John McCall53262c92010-01-12 02:15:36 +00006026};
6027
John McCalle1ac8d12010-01-13 00:25:19 +00006028OverloadCandidateKind ClassifyOverloadCandidate(Sema &S,
6029 FunctionDecl *Fn,
6030 std::string &Description) {
6031 bool isTemplate = false;
6032
6033 if (FunctionTemplateDecl *FunTmpl = Fn->getPrimaryTemplate()) {
6034 isTemplate = true;
6035 Description = S.getTemplateArgumentBindingsText(
6036 FunTmpl->getTemplateParameters(), *Fn->getTemplateSpecializationArgs());
6037 }
John McCallfd0b2f82010-01-06 09:43:14 +00006038
6039 if (CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Fn)) {
John McCall53262c92010-01-12 02:15:36 +00006040 if (!Ctor->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006041 return isTemplate ? oc_constructor_template : oc_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006042
John McCall53262c92010-01-12 02:15:36 +00006043 return Ctor->isCopyConstructor() ? oc_implicit_copy_constructor
6044 : oc_implicit_default_constructor;
John McCallfd0b2f82010-01-06 09:43:14 +00006045 }
6046
6047 if (CXXMethodDecl *Meth = dyn_cast<CXXMethodDecl>(Fn)) {
6048 // This actually gets spelled 'candidate function' for now, but
6049 // it doesn't hurt to split it out.
John McCall53262c92010-01-12 02:15:36 +00006050 if (!Meth->isImplicit())
John McCalle1ac8d12010-01-13 00:25:19 +00006051 return isTemplate ? oc_method_template : oc_method;
John McCallfd0b2f82010-01-06 09:43:14 +00006052
Douglas Gregorec3bec02010-09-27 22:37:28 +00006053 assert(Meth->isCopyAssignmentOperator()
John McCallfd0b2f82010-01-06 09:43:14 +00006054 && "implicit method is not copy assignment operator?");
John McCall53262c92010-01-12 02:15:36 +00006055 return oc_implicit_copy_assignment;
6056 }
6057
John McCalle1ac8d12010-01-13 00:25:19 +00006058 return isTemplate ? oc_function_template : oc_function;
John McCall53262c92010-01-12 02:15:36 +00006059}
6060
6061} // end anonymous namespace
6062
6063// Notes the location of an overload candidate.
6064void Sema::NoteOverloadCandidate(FunctionDecl *Fn) {
John McCalle1ac8d12010-01-13 00:25:19 +00006065 std::string FnDesc;
6066 OverloadCandidateKind K = ClassifyOverloadCandidate(*this, Fn, FnDesc);
6067 Diag(Fn->getLocation(), diag::note_ovl_candidate)
6068 << (unsigned) K << FnDesc;
John McCallfd0b2f82010-01-06 09:43:14 +00006069}
6070
John McCall0d1da222010-01-12 00:44:57 +00006071/// Diagnoses an ambiguous conversion. The partial diagnostic is the
6072/// "lead" diagnostic; it will be given two arguments, the source and
6073/// target types of the conversion.
John McCall5c32be02010-08-24 20:38:10 +00006074void ImplicitConversionSequence::DiagnoseAmbiguousConversion(
6075 Sema &S,
6076 SourceLocation CaretLoc,
6077 const PartialDiagnostic &PDiag) const {
6078 S.Diag(CaretLoc, PDiag)
6079 << Ambiguous.getFromType() << Ambiguous.getToType();
John McCall0d1da222010-01-12 00:44:57 +00006080 for (AmbiguousConversionSequence::const_iterator
John McCall5c32be02010-08-24 20:38:10 +00006081 I = Ambiguous.begin(), E = Ambiguous.end(); I != E; ++I) {
6082 S.NoteOverloadCandidate(*I);
John McCall0d1da222010-01-12 00:44:57 +00006083 }
John McCall12f97bc2010-01-08 04:41:39 +00006084}
6085
John McCall0d1da222010-01-12 00:44:57 +00006086namespace {
6087
John McCall6a61b522010-01-13 09:16:55 +00006088void DiagnoseBadConversion(Sema &S, OverloadCandidate *Cand, unsigned I) {
6089 const ImplicitConversionSequence &Conv = Cand->Conversions[I];
6090 assert(Conv.isBad());
John McCalle1ac8d12010-01-13 00:25:19 +00006091 assert(Cand->Function && "for now, candidate must be a function");
6092 FunctionDecl *Fn = Cand->Function;
6093
6094 // There's a conversion slot for the object argument if this is a
6095 // non-constructor method. Note that 'I' corresponds the
6096 // conversion-slot index.
John McCall6a61b522010-01-13 09:16:55 +00006097 bool isObjectArgument = false;
John McCalle1ac8d12010-01-13 00:25:19 +00006098 if (isa<CXXMethodDecl>(Fn) && !isa<CXXConstructorDecl>(Fn)) {
John McCall6a61b522010-01-13 09:16:55 +00006099 if (I == 0)
6100 isObjectArgument = true;
6101 else
6102 I--;
John McCalle1ac8d12010-01-13 00:25:19 +00006103 }
6104
John McCalle1ac8d12010-01-13 00:25:19 +00006105 std::string FnDesc;
6106 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
6107
John McCall6a61b522010-01-13 09:16:55 +00006108 Expr *FromExpr = Conv.Bad.FromExpr;
6109 QualType FromTy = Conv.Bad.getFromType();
6110 QualType ToTy = Conv.Bad.getToType();
John McCalle1ac8d12010-01-13 00:25:19 +00006111
John McCallfb7ad0f2010-02-02 02:42:52 +00006112 if (FromTy == S.Context.OverloadTy) {
John McCall65eb8792010-02-25 01:37:24 +00006113 assert(FromExpr && "overload set argument came from implicit argument?");
John McCallfb7ad0f2010-02-02 02:42:52 +00006114 Expr *E = FromExpr->IgnoreParens();
6115 if (isa<UnaryOperator>(E))
6116 E = cast<UnaryOperator>(E)->getSubExpr()->IgnoreParens();
John McCall1acbbb52010-02-02 06:20:04 +00006117 DeclarationName Name = cast<OverloadExpr>(E)->getName();
John McCallfb7ad0f2010-02-02 02:42:52 +00006118
6119 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_overload)
6120 << (unsigned) FnKind << FnDesc
6121 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6122 << ToTy << Name << I+1;
6123 return;
6124 }
6125
John McCall6d174642010-01-23 08:10:49 +00006126 // Do some hand-waving analysis to see if the non-viability is due
6127 // to a qualifier mismatch.
John McCall47000992010-01-14 03:28:57 +00006128 CanQualType CFromTy = S.Context.getCanonicalType(FromTy);
6129 CanQualType CToTy = S.Context.getCanonicalType(ToTy);
6130 if (CanQual<ReferenceType> RT = CToTy->getAs<ReferenceType>())
6131 CToTy = RT->getPointeeType();
6132 else {
6133 // TODO: detect and diagnose the full richness of const mismatches.
6134 if (CanQual<PointerType> FromPT = CFromTy->getAs<PointerType>())
6135 if (CanQual<PointerType> ToPT = CToTy->getAs<PointerType>())
6136 CFromTy = FromPT->getPointeeType(), CToTy = ToPT->getPointeeType();
6137 }
6138
6139 if (CToTy.getUnqualifiedType() == CFromTy.getUnqualifiedType() &&
6140 !CToTy.isAtLeastAsQualifiedAs(CFromTy)) {
6141 // It is dumb that we have to do this here.
6142 while (isa<ArrayType>(CFromTy))
6143 CFromTy = CFromTy->getAs<ArrayType>()->getElementType();
6144 while (isa<ArrayType>(CToTy))
6145 CToTy = CFromTy->getAs<ArrayType>()->getElementType();
6146
6147 Qualifiers FromQs = CFromTy.getQualifiers();
6148 Qualifiers ToQs = CToTy.getQualifiers();
6149
6150 if (FromQs.getAddressSpace() != ToQs.getAddressSpace()) {
6151 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_addrspace)
6152 << (unsigned) FnKind << FnDesc
6153 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6154 << FromTy
6155 << FromQs.getAddressSpace() << ToQs.getAddressSpace()
6156 << (unsigned) isObjectArgument << I+1;
6157 return;
6158 }
6159
6160 unsigned CVR = FromQs.getCVRQualifiers() & ~ToQs.getCVRQualifiers();
6161 assert(CVR && "unexpected qualifiers mismatch");
6162
6163 if (isObjectArgument) {
6164 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr_this)
6165 << (unsigned) FnKind << FnDesc
6166 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6167 << FromTy << (CVR - 1);
6168 } else {
6169 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_cvr)
6170 << (unsigned) FnKind << FnDesc
6171 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6172 << FromTy << (CVR - 1) << I+1;
6173 }
6174 return;
6175 }
6176
John McCall6d174642010-01-23 08:10:49 +00006177 // Diagnose references or pointers to incomplete types differently,
6178 // since it's far from impossible that the incompleteness triggered
6179 // the failure.
6180 QualType TempFromTy = FromTy.getNonReferenceType();
6181 if (const PointerType *PTy = TempFromTy->getAs<PointerType>())
6182 TempFromTy = PTy->getPointeeType();
6183 if (TempFromTy->isIncompleteType()) {
6184 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv_incomplete)
6185 << (unsigned) FnKind << FnDesc
6186 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
6187 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
6188 return;
6189 }
6190
Douglas Gregor56f2e342010-06-30 23:01:39 +00006191 // Diagnose base -> derived pointer conversions.
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006192 unsigned BaseToDerivedConversion = 0;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006193 if (const PointerType *FromPtrTy = FromTy->getAs<PointerType>()) {
6194 if (const PointerType *ToPtrTy = ToTy->getAs<PointerType>()) {
6195 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6196 FromPtrTy->getPointeeType()) &&
6197 !FromPtrTy->getPointeeType()->isIncompleteType() &&
6198 !ToPtrTy->getPointeeType()->isIncompleteType() &&
6199 S.IsDerivedFrom(ToPtrTy->getPointeeType(),
6200 FromPtrTy->getPointeeType()))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006201 BaseToDerivedConversion = 1;
Douglas Gregor56f2e342010-06-30 23:01:39 +00006202 }
6203 } else if (const ObjCObjectPointerType *FromPtrTy
6204 = FromTy->getAs<ObjCObjectPointerType>()) {
6205 if (const ObjCObjectPointerType *ToPtrTy
6206 = ToTy->getAs<ObjCObjectPointerType>())
6207 if (const ObjCInterfaceDecl *FromIface = FromPtrTy->getInterfaceDecl())
6208 if (const ObjCInterfaceDecl *ToIface = ToPtrTy->getInterfaceDecl())
6209 if (ToPtrTy->getPointeeType().isAtLeastAsQualifiedAs(
6210 FromPtrTy->getPointeeType()) &&
6211 FromIface->isSuperClassOf(ToIface))
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006212 BaseToDerivedConversion = 2;
6213 } else if (const ReferenceType *ToRefTy = ToTy->getAs<ReferenceType>()) {
6214 if (ToRefTy->getPointeeType().isAtLeastAsQualifiedAs(FromTy) &&
6215 !FromTy->isIncompleteType() &&
6216 !ToRefTy->getPointeeType()->isIncompleteType() &&
6217 S.IsDerivedFrom(ToRefTy->getPointeeType(), FromTy))
6218 BaseToDerivedConversion = 3;
6219 }
6220
6221 if (BaseToDerivedConversion) {
Douglas Gregor56f2e342010-06-30 23:01:39 +00006222 S.Diag(Fn->getLocation(),
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006223 diag::note_ovl_candidate_bad_base_to_derived_conv)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006224 << (unsigned) FnKind << FnDesc
6225 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
Douglas Gregorfb0c0d32010-07-01 02:14:45 +00006226 << (BaseToDerivedConversion - 1)
Douglas Gregor56f2e342010-06-30 23:01:39 +00006227 << FromTy << ToTy << I+1;
6228 return;
6229 }
6230
John McCall47000992010-01-14 03:28:57 +00006231 // TODO: specialize more based on the kind of mismatch
John McCalle1ac8d12010-01-13 00:25:19 +00006232 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_conv)
6233 << (unsigned) FnKind << FnDesc
John McCall6a61b522010-01-13 09:16:55 +00006234 << (FromExpr ? FromExpr->getSourceRange() : SourceRange())
John McCalla1709fd2010-01-14 00:56:20 +00006235 << FromTy << ToTy << (unsigned) isObjectArgument << I+1;
John McCall6a61b522010-01-13 09:16:55 +00006236}
6237
6238void DiagnoseArityMismatch(Sema &S, OverloadCandidate *Cand,
6239 unsigned NumFormalArgs) {
6240 // TODO: treat calls to a missing default constructor as a special case
6241
6242 FunctionDecl *Fn = Cand->Function;
6243 const FunctionProtoType *FnTy = Fn->getType()->getAs<FunctionProtoType>();
6244
6245 unsigned MinParams = Fn->getMinRequiredArguments();
6246
6247 // at least / at most / exactly
6248 unsigned mode, modeCount;
6249 if (NumFormalArgs < MinParams) {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006250 assert((Cand->FailureKind == ovl_fail_too_few_arguments) ||
6251 (Cand->FailureKind == ovl_fail_bad_deduction &&
6252 Cand->DeductionFailure.Result == Sema::TDK_TooFewArguments));
Douglas Gregor7825bf32011-01-06 22:09:01 +00006253 if (MinParams != FnTy->getNumArgs() ||
6254 FnTy->isVariadic() || FnTy->isTemplateVariadic())
John McCall6a61b522010-01-13 09:16:55 +00006255 mode = 0; // "at least"
6256 else
6257 mode = 2; // "exactly"
6258 modeCount = MinParams;
6259 } else {
Douglas Gregor02eb4832010-05-08 18:13:28 +00006260 assert((Cand->FailureKind == ovl_fail_too_many_arguments) ||
6261 (Cand->FailureKind == ovl_fail_bad_deduction &&
6262 Cand->DeductionFailure.Result == Sema::TDK_TooManyArguments));
John McCall6a61b522010-01-13 09:16:55 +00006263 if (MinParams != FnTy->getNumArgs())
6264 mode = 1; // "at most"
6265 else
6266 mode = 2; // "exactly"
6267 modeCount = FnTy->getNumArgs();
6268 }
6269
6270 std::string Description;
6271 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, Description);
6272
6273 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_arity)
Douglas Gregor02eb4832010-05-08 18:13:28 +00006274 << (unsigned) FnKind << (Fn->getDescribedFunctionTemplate() != 0) << mode
6275 << modeCount << NumFormalArgs;
John McCalle1ac8d12010-01-13 00:25:19 +00006276}
6277
John McCall8b9ed552010-02-01 18:53:26 +00006278/// Diagnose a failed template-argument deduction.
6279void DiagnoseBadDeduction(Sema &S, OverloadCandidate *Cand,
6280 Expr **Args, unsigned NumArgs) {
6281 FunctionDecl *Fn = Cand->Function; // pattern
6282
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006283 TemplateParameter Param = Cand->DeductionFailure.getTemplateParameter();
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006284 NamedDecl *ParamD;
6285 (ParamD = Param.dyn_cast<TemplateTypeParmDecl*>()) ||
6286 (ParamD = Param.dyn_cast<NonTypeTemplateParmDecl*>()) ||
6287 (ParamD = Param.dyn_cast<TemplateTemplateParmDecl*>());
John McCall8b9ed552010-02-01 18:53:26 +00006288 switch (Cand->DeductionFailure.Result) {
6289 case Sema::TDK_Success:
6290 llvm_unreachable("TDK_success while diagnosing bad deduction");
6291
6292 case Sema::TDK_Incomplete: {
John McCall8b9ed552010-02-01 18:53:26 +00006293 assert(ParamD && "no parameter found for incomplete deduction result");
6294 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_incomplete_deduction)
6295 << ParamD->getDeclName();
6296 return;
6297 }
6298
John McCall42d7d192010-08-05 09:05:08 +00006299 case Sema::TDK_Underqualified: {
6300 assert(ParamD && "no parameter found for bad qualifiers deduction result");
6301 TemplateTypeParmDecl *TParam = cast<TemplateTypeParmDecl>(ParamD);
6302
6303 QualType Param = Cand->DeductionFailure.getFirstArg()->getAsType();
6304
6305 // Param will have been canonicalized, but it should just be a
6306 // qualified version of ParamD, so move the qualifiers to that.
John McCall717d9b02010-12-10 11:01:00 +00006307 QualifierCollector Qs;
John McCall42d7d192010-08-05 09:05:08 +00006308 Qs.strip(Param);
John McCall717d9b02010-12-10 11:01:00 +00006309 QualType NonCanonParam = Qs.apply(S.Context, TParam->getTypeForDecl());
John McCall42d7d192010-08-05 09:05:08 +00006310 assert(S.Context.hasSameType(Param, NonCanonParam));
6311
6312 // Arg has also been canonicalized, but there's nothing we can do
6313 // about that. It also doesn't matter as much, because it won't
6314 // have any template parameters in it (because deduction isn't
6315 // done on dependent types).
6316 QualType Arg = Cand->DeductionFailure.getSecondArg()->getAsType();
6317
6318 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_underqualified)
6319 << ParamD->getDeclName() << Arg << NonCanonParam;
6320 return;
6321 }
6322
6323 case Sema::TDK_Inconsistent: {
Chandler Carruth8e543b32010-12-12 08:17:55 +00006324 assert(ParamD && "no parameter found for inconsistent deduction result");
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006325 int which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006326 if (isa<TemplateTypeParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006327 which = 0;
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006328 else if (isa<NonTypeTemplateParmDecl>(ParamD))
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006329 which = 1;
6330 else {
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006331 which = 2;
6332 }
6333
6334 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_inconsistent_deduction)
6335 << which << ParamD->getDeclName()
6336 << *Cand->DeductionFailure.getFirstArg()
6337 << *Cand->DeductionFailure.getSecondArg();
6338 return;
6339 }
Douglas Gregor02eb4832010-05-08 18:13:28 +00006340
Douglas Gregor1d72edd2010-05-08 19:15:54 +00006341 case Sema::TDK_InvalidExplicitArguments:
6342 assert(ParamD && "no parameter found for invalid explicit arguments");
6343 if (ParamD->getDeclName())
6344 S.Diag(Fn->getLocation(),
6345 diag::note_ovl_candidate_explicit_arg_mismatch_named)
6346 << ParamD->getDeclName();
6347 else {
6348 int index = 0;
6349 if (TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(ParamD))
6350 index = TTP->getIndex();
6351 else if (NonTypeTemplateParmDecl *NTTP
6352 = dyn_cast<NonTypeTemplateParmDecl>(ParamD))
6353 index = NTTP->getIndex();
6354 else
6355 index = cast<TemplateTemplateParmDecl>(ParamD)->getIndex();
6356 S.Diag(Fn->getLocation(),
6357 diag::note_ovl_candidate_explicit_arg_mismatch_unnamed)
6358 << (index + 1);
6359 }
6360 return;
6361
Douglas Gregor02eb4832010-05-08 18:13:28 +00006362 case Sema::TDK_TooManyArguments:
6363 case Sema::TDK_TooFewArguments:
6364 DiagnoseArityMismatch(S, Cand, NumArgs);
6365 return;
Douglas Gregord09efd42010-05-08 20:07:26 +00006366
6367 case Sema::TDK_InstantiationDepth:
6368 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_instantiation_depth);
6369 return;
6370
6371 case Sema::TDK_SubstitutionFailure: {
6372 std::string ArgString;
6373 if (TemplateArgumentList *Args
6374 = Cand->DeductionFailure.getTemplateArgumentList())
6375 ArgString = S.getTemplateArgumentBindingsText(
6376 Fn->getDescribedFunctionTemplate()->getTemplateParameters(),
6377 *Args);
6378 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_substitution_failure)
6379 << ArgString;
6380 return;
6381 }
Douglas Gregor3626a5c2010-05-08 17:41:32 +00006382
John McCall8b9ed552010-02-01 18:53:26 +00006383 // TODO: diagnose these individually, then kill off
6384 // note_ovl_candidate_bad_deduction, which is uselessly vague.
John McCall8b9ed552010-02-01 18:53:26 +00006385 case Sema::TDK_NonDeducedMismatch:
John McCall8b9ed552010-02-01 18:53:26 +00006386 case Sema::TDK_FailedOverloadResolution:
6387 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_bad_deduction);
6388 return;
6389 }
6390}
6391
6392/// Generates a 'note' diagnostic for an overload candidate. We've
6393/// already generated a primary error at the call site.
6394///
6395/// It really does need to be a single diagnostic with its caret
6396/// pointed at the candidate declaration. Yes, this creates some
6397/// major challenges of technical writing. Yes, this makes pointing
6398/// out problems with specific arguments quite awkward. It's still
6399/// better than generating twenty screens of text for every failed
6400/// overload.
6401///
6402/// It would be great to be able to express per-candidate problems
6403/// more richly for those diagnostic clients that cared, but we'd
6404/// still have to be just as careful with the default diagnostics.
John McCalle1ac8d12010-01-13 00:25:19 +00006405void NoteFunctionCandidate(Sema &S, OverloadCandidate *Cand,
6406 Expr **Args, unsigned NumArgs) {
John McCall53262c92010-01-12 02:15:36 +00006407 FunctionDecl *Fn = Cand->Function;
6408
John McCall12f97bc2010-01-08 04:41:39 +00006409 // Note deleted candidates, but only if they're viable.
John McCall53262c92010-01-12 02:15:36 +00006410 if (Cand->Viable && (Fn->isDeleted() || Fn->hasAttr<UnavailableAttr>())) {
John McCalle1ac8d12010-01-13 00:25:19 +00006411 std::string FnDesc;
6412 OverloadCandidateKind FnKind = ClassifyOverloadCandidate(S, Fn, FnDesc);
John McCall53262c92010-01-12 02:15:36 +00006413
6414 S.Diag(Fn->getLocation(), diag::note_ovl_candidate_deleted)
John McCalle1ac8d12010-01-13 00:25:19 +00006415 << FnKind << FnDesc << Fn->isDeleted();
John McCalld3224162010-01-08 00:58:21 +00006416 return;
John McCall12f97bc2010-01-08 04:41:39 +00006417 }
6418
John McCalle1ac8d12010-01-13 00:25:19 +00006419 // We don't really have anything else to say about viable candidates.
6420 if (Cand->Viable) {
6421 S.NoteOverloadCandidate(Fn);
6422 return;
6423 }
John McCall0d1da222010-01-12 00:44:57 +00006424
John McCall6a61b522010-01-13 09:16:55 +00006425 switch (Cand->FailureKind) {
6426 case ovl_fail_too_many_arguments:
6427 case ovl_fail_too_few_arguments:
6428 return DiagnoseArityMismatch(S, Cand, NumArgs);
John McCalle1ac8d12010-01-13 00:25:19 +00006429
John McCall6a61b522010-01-13 09:16:55 +00006430 case ovl_fail_bad_deduction:
John McCall8b9ed552010-02-01 18:53:26 +00006431 return DiagnoseBadDeduction(S, Cand, Args, NumArgs);
6432
John McCallfe796dd2010-01-23 05:17:32 +00006433 case ovl_fail_trivial_conversion:
6434 case ovl_fail_bad_final_conversion:
Douglas Gregor2c326bc2010-04-12 23:42:09 +00006435 case ovl_fail_final_conversion_not_exact:
John McCall6a61b522010-01-13 09:16:55 +00006436 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006437
John McCall65eb8792010-02-25 01:37:24 +00006438 case ovl_fail_bad_conversion: {
6439 unsigned I = (Cand->IgnoreObjectArgument ? 1 : 0);
6440 for (unsigned N = Cand->Conversions.size(); I != N; ++I)
John McCall6a61b522010-01-13 09:16:55 +00006441 if (Cand->Conversions[I].isBad())
6442 return DiagnoseBadConversion(S, Cand, I);
6443
6444 // FIXME: this currently happens when we're called from SemaInit
6445 // when user-conversion overload fails. Figure out how to handle
6446 // those conditions and diagnose them well.
6447 return S.NoteOverloadCandidate(Fn);
John McCalle1ac8d12010-01-13 00:25:19 +00006448 }
John McCall65eb8792010-02-25 01:37:24 +00006449 }
John McCalld3224162010-01-08 00:58:21 +00006450}
6451
6452void NoteSurrogateCandidate(Sema &S, OverloadCandidate *Cand) {
6453 // Desugar the type of the surrogate down to a function type,
6454 // retaining as many typedefs as possible while still showing
6455 // the function type (and, therefore, its parameter types).
6456 QualType FnType = Cand->Surrogate->getConversionType();
6457 bool isLValueReference = false;
6458 bool isRValueReference = false;
6459 bool isPointer = false;
6460 if (const LValueReferenceType *FnTypeRef =
6461 FnType->getAs<LValueReferenceType>()) {
6462 FnType = FnTypeRef->getPointeeType();
6463 isLValueReference = true;
6464 } else if (const RValueReferenceType *FnTypeRef =
6465 FnType->getAs<RValueReferenceType>()) {
6466 FnType = FnTypeRef->getPointeeType();
6467 isRValueReference = true;
6468 }
6469 if (const PointerType *FnTypePtr = FnType->getAs<PointerType>()) {
6470 FnType = FnTypePtr->getPointeeType();
6471 isPointer = true;
6472 }
6473 // Desugar down to a function type.
6474 FnType = QualType(FnType->getAs<FunctionType>(), 0);
6475 // Reconstruct the pointer/reference as appropriate.
6476 if (isPointer) FnType = S.Context.getPointerType(FnType);
6477 if (isRValueReference) FnType = S.Context.getRValueReferenceType(FnType);
6478 if (isLValueReference) FnType = S.Context.getLValueReferenceType(FnType);
6479
6480 S.Diag(Cand->Surrogate->getLocation(), diag::note_ovl_surrogate_cand)
6481 << FnType;
6482}
6483
6484void NoteBuiltinOperatorCandidate(Sema &S,
6485 const char *Opc,
6486 SourceLocation OpLoc,
6487 OverloadCandidate *Cand) {
6488 assert(Cand->Conversions.size() <= 2 && "builtin operator is not binary");
6489 std::string TypeStr("operator");
6490 TypeStr += Opc;
6491 TypeStr += "(";
6492 TypeStr += Cand->BuiltinTypes.ParamTypes[0].getAsString();
6493 if (Cand->Conversions.size() == 1) {
6494 TypeStr += ")";
6495 S.Diag(OpLoc, diag::note_ovl_builtin_unary_candidate) << TypeStr;
6496 } else {
6497 TypeStr += ", ";
6498 TypeStr += Cand->BuiltinTypes.ParamTypes[1].getAsString();
6499 TypeStr += ")";
6500 S.Diag(OpLoc, diag::note_ovl_builtin_binary_candidate) << TypeStr;
6501 }
6502}
6503
6504void NoteAmbiguousUserConversions(Sema &S, SourceLocation OpLoc,
6505 OverloadCandidate *Cand) {
6506 unsigned NoOperands = Cand->Conversions.size();
6507 for (unsigned ArgIdx = 0; ArgIdx < NoOperands; ++ArgIdx) {
6508 const ImplicitConversionSequence &ICS = Cand->Conversions[ArgIdx];
John McCall0d1da222010-01-12 00:44:57 +00006509 if (ICS.isBad()) break; // all meaningless after first invalid
6510 if (!ICS.isAmbiguous()) continue;
6511
John McCall5c32be02010-08-24 20:38:10 +00006512 ICS.DiagnoseAmbiguousConversion(S, OpLoc,
Douglas Gregor89336232010-03-29 23:34:08 +00006513 S.PDiag(diag::note_ambiguous_type_conversion));
John McCalld3224162010-01-08 00:58:21 +00006514 }
6515}
6516
John McCall3712d9e2010-01-15 23:32:50 +00006517SourceLocation GetLocationForCandidate(const OverloadCandidate *Cand) {
6518 if (Cand->Function)
6519 return Cand->Function->getLocation();
John McCall982adb52010-01-16 03:50:16 +00006520 if (Cand->IsSurrogate)
John McCall3712d9e2010-01-15 23:32:50 +00006521 return Cand->Surrogate->getLocation();
6522 return SourceLocation();
6523}
6524
John McCallad2587a2010-01-12 00:48:53 +00006525struct CompareOverloadCandidatesForDisplay {
6526 Sema &S;
6527 CompareOverloadCandidatesForDisplay(Sema &S) : S(S) {}
John McCall12f97bc2010-01-08 04:41:39 +00006528
6529 bool operator()(const OverloadCandidate *L,
6530 const OverloadCandidate *R) {
John McCall982adb52010-01-16 03:50:16 +00006531 // Fast-path this check.
6532 if (L == R) return false;
6533
John McCall12f97bc2010-01-08 04:41:39 +00006534 // Order first by viability.
John McCallad2587a2010-01-12 00:48:53 +00006535 if (L->Viable) {
6536 if (!R->Viable) return true;
6537
6538 // TODO: introduce a tri-valued comparison for overload
6539 // candidates. Would be more worthwhile if we had a sort
6540 // that could exploit it.
John McCall5c32be02010-08-24 20:38:10 +00006541 if (isBetterOverloadCandidate(S, *L, *R, SourceLocation())) return true;
6542 if (isBetterOverloadCandidate(S, *R, *L, SourceLocation())) return false;
John McCallad2587a2010-01-12 00:48:53 +00006543 } else if (R->Viable)
6544 return false;
John McCall12f97bc2010-01-08 04:41:39 +00006545
John McCall3712d9e2010-01-15 23:32:50 +00006546 assert(L->Viable == R->Viable);
John McCall12f97bc2010-01-08 04:41:39 +00006547
John McCall3712d9e2010-01-15 23:32:50 +00006548 // Criteria by which we can sort non-viable candidates:
6549 if (!L->Viable) {
6550 // 1. Arity mismatches come after other candidates.
6551 if (L->FailureKind == ovl_fail_too_many_arguments ||
6552 L->FailureKind == ovl_fail_too_few_arguments)
6553 return false;
6554 if (R->FailureKind == ovl_fail_too_many_arguments ||
6555 R->FailureKind == ovl_fail_too_few_arguments)
6556 return true;
John McCall12f97bc2010-01-08 04:41:39 +00006557
John McCallfe796dd2010-01-23 05:17:32 +00006558 // 2. Bad conversions come first and are ordered by the number
6559 // of bad conversions and quality of good conversions.
6560 if (L->FailureKind == ovl_fail_bad_conversion) {
6561 if (R->FailureKind != ovl_fail_bad_conversion)
6562 return true;
6563
6564 // If there's any ordering between the defined conversions...
6565 // FIXME: this might not be transitive.
6566 assert(L->Conversions.size() == R->Conversions.size());
6567
6568 int leftBetter = 0;
John McCall21b57fa2010-02-25 10:46:05 +00006569 unsigned I = (L->IgnoreObjectArgument || R->IgnoreObjectArgument);
6570 for (unsigned E = L->Conversions.size(); I != E; ++I) {
John McCall5c32be02010-08-24 20:38:10 +00006571 switch (CompareImplicitConversionSequences(S,
6572 L->Conversions[I],
6573 R->Conversions[I])) {
John McCallfe796dd2010-01-23 05:17:32 +00006574 case ImplicitConversionSequence::Better:
6575 leftBetter++;
6576 break;
6577
6578 case ImplicitConversionSequence::Worse:
6579 leftBetter--;
6580 break;
6581
6582 case ImplicitConversionSequence::Indistinguishable:
6583 break;
6584 }
6585 }
6586 if (leftBetter > 0) return true;
6587 if (leftBetter < 0) return false;
6588
6589 } else if (R->FailureKind == ovl_fail_bad_conversion)
6590 return false;
6591
John McCall3712d9e2010-01-15 23:32:50 +00006592 // TODO: others?
6593 }
6594
6595 // Sort everything else by location.
6596 SourceLocation LLoc = GetLocationForCandidate(L);
6597 SourceLocation RLoc = GetLocationForCandidate(R);
6598
6599 // Put candidates without locations (e.g. builtins) at the end.
6600 if (LLoc.isInvalid()) return false;
6601 if (RLoc.isInvalid()) return true;
6602
6603 return S.SourceMgr.isBeforeInTranslationUnit(LLoc, RLoc);
John McCall12f97bc2010-01-08 04:41:39 +00006604 }
6605};
6606
John McCallfe796dd2010-01-23 05:17:32 +00006607/// CompleteNonViableCandidate - Normally, overload resolution only
6608/// computes up to the first
6609void CompleteNonViableCandidate(Sema &S, OverloadCandidate *Cand,
6610 Expr **Args, unsigned NumArgs) {
6611 assert(!Cand->Viable);
6612
6613 // Don't do anything on failures other than bad conversion.
6614 if (Cand->FailureKind != ovl_fail_bad_conversion) return;
6615
6616 // Skip forward to the first bad conversion.
John McCall65eb8792010-02-25 01:37:24 +00006617 unsigned ConvIdx = (Cand->IgnoreObjectArgument ? 1 : 0);
John McCallfe796dd2010-01-23 05:17:32 +00006618 unsigned ConvCount = Cand->Conversions.size();
6619 while (true) {
6620 assert(ConvIdx != ConvCount && "no bad conversion in candidate");
6621 ConvIdx++;
6622 if (Cand->Conversions[ConvIdx - 1].isBad())
6623 break;
6624 }
6625
6626 if (ConvIdx == ConvCount)
6627 return;
6628
John McCall65eb8792010-02-25 01:37:24 +00006629 assert(!Cand->Conversions[ConvIdx].isInitialized() &&
6630 "remaining conversion is initialized?");
6631
Douglas Gregoradc7a702010-04-16 17:45:54 +00006632 // FIXME: this should probably be preserved from the overload
John McCallfe796dd2010-01-23 05:17:32 +00006633 // operation somehow.
6634 bool SuppressUserConversions = false;
John McCallfe796dd2010-01-23 05:17:32 +00006635
6636 const FunctionProtoType* Proto;
6637 unsigned ArgIdx = ConvIdx;
6638
6639 if (Cand->IsSurrogate) {
6640 QualType ConvType
6641 = Cand->Surrogate->getConversionType().getNonReferenceType();
6642 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
6643 ConvType = ConvPtrType->getPointeeType();
6644 Proto = ConvType->getAs<FunctionProtoType>();
6645 ArgIdx--;
6646 } else if (Cand->Function) {
6647 Proto = Cand->Function->getType()->getAs<FunctionProtoType>();
6648 if (isa<CXXMethodDecl>(Cand->Function) &&
6649 !isa<CXXConstructorDecl>(Cand->Function))
6650 ArgIdx--;
6651 } else {
6652 // Builtin binary operator with a bad first conversion.
6653 assert(ConvCount <= 3);
6654 for (; ConvIdx != ConvCount; ++ConvIdx)
6655 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006656 = TryCopyInitialization(S, Args[ConvIdx],
6657 Cand->BuiltinTypes.ParamTypes[ConvIdx],
6658 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006659 /*InOverloadResolution*/ true);
John McCallfe796dd2010-01-23 05:17:32 +00006660 return;
6661 }
6662
6663 // Fill in the rest of the conversions.
6664 unsigned NumArgsInProto = Proto->getNumArgs();
6665 for (; ConvIdx != ConvCount; ++ConvIdx, ++ArgIdx) {
6666 if (ArgIdx < NumArgsInProto)
6667 Cand->Conversions[ConvIdx]
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006668 = TryCopyInitialization(S, Args[ArgIdx], Proto->getArgType(ArgIdx),
6669 SuppressUserConversions,
Douglas Gregorcb13cfc2010-04-16 17:51:22 +00006670 /*InOverloadResolution=*/true);
John McCallfe796dd2010-01-23 05:17:32 +00006671 else
6672 Cand->Conversions[ConvIdx].setEllipsis();
6673 }
6674}
6675
John McCalld3224162010-01-08 00:58:21 +00006676} // end anonymous namespace
6677
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006678/// PrintOverloadCandidates - When overload resolution fails, prints
6679/// diagnostic messages containing the candidates in the candidate
John McCall12f97bc2010-01-08 04:41:39 +00006680/// set.
John McCall5c32be02010-08-24 20:38:10 +00006681void OverloadCandidateSet::NoteCandidates(Sema &S,
6682 OverloadCandidateDisplayKind OCD,
6683 Expr **Args, unsigned NumArgs,
6684 const char *Opc,
6685 SourceLocation OpLoc) {
John McCall12f97bc2010-01-08 04:41:39 +00006686 // Sort the candidates by viability and position. Sorting directly would
6687 // be prohibitive, so we make a set of pointers and sort those.
6688 llvm::SmallVector<OverloadCandidate*, 32> Cands;
John McCall5c32be02010-08-24 20:38:10 +00006689 if (OCD == OCD_AllCandidates) Cands.reserve(size());
6690 for (iterator Cand = begin(), LastCand = end(); Cand != LastCand; ++Cand) {
John McCallfe796dd2010-01-23 05:17:32 +00006691 if (Cand->Viable)
John McCall12f97bc2010-01-08 04:41:39 +00006692 Cands.push_back(Cand);
John McCallfe796dd2010-01-23 05:17:32 +00006693 else if (OCD == OCD_AllCandidates) {
John McCall5c32be02010-08-24 20:38:10 +00006694 CompleteNonViableCandidate(S, Cand, Args, NumArgs);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006695 if (Cand->Function || Cand->IsSurrogate)
6696 Cands.push_back(Cand);
6697 // Otherwise, this a non-viable builtin candidate. We do not, in general,
6698 // want to list every possible builtin candidate.
John McCallfe796dd2010-01-23 05:17:32 +00006699 }
6700 }
6701
John McCallad2587a2010-01-12 00:48:53 +00006702 std::sort(Cands.begin(), Cands.end(),
John McCall5c32be02010-08-24 20:38:10 +00006703 CompareOverloadCandidatesForDisplay(S));
John McCall12f97bc2010-01-08 04:41:39 +00006704
John McCall0d1da222010-01-12 00:44:57 +00006705 bool ReportedAmbiguousConversions = false;
John McCalld3224162010-01-08 00:58:21 +00006706
John McCall12f97bc2010-01-08 04:41:39 +00006707 llvm::SmallVectorImpl<OverloadCandidate*>::iterator I, E;
John McCall5c32be02010-08-24 20:38:10 +00006708 const Diagnostic::OverloadsShown ShowOverloads = S.Diags.getShowOverloads();
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006709 unsigned CandsShown = 0;
John McCall12f97bc2010-01-08 04:41:39 +00006710 for (I = Cands.begin(), E = Cands.end(); I != E; ++I) {
6711 OverloadCandidate *Cand = *I;
Douglas Gregor4fc308b2008-11-21 02:54:28 +00006712
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006713 // Set an arbitrary limit on the number of candidate functions we'll spam
6714 // the user with. FIXME: This limit should depend on details of the
6715 // candidate list.
6716 if (CandsShown >= 4 && ShowOverloads == Diagnostic::Ovl_Best) {
6717 break;
6718 }
6719 ++CandsShown;
6720
John McCalld3224162010-01-08 00:58:21 +00006721 if (Cand->Function)
John McCall5c32be02010-08-24 20:38:10 +00006722 NoteFunctionCandidate(S, Cand, Args, NumArgs);
John McCalld3224162010-01-08 00:58:21 +00006723 else if (Cand->IsSurrogate)
John McCall5c32be02010-08-24 20:38:10 +00006724 NoteSurrogateCandidate(S, Cand);
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006725 else {
6726 assert(Cand->Viable &&
6727 "Non-viable built-in candidates are not added to Cands.");
John McCall0d1da222010-01-12 00:44:57 +00006728 // Generally we only see ambiguities including viable builtin
6729 // operators if overload resolution got screwed up by an
6730 // ambiguous user-defined conversion.
6731 //
6732 // FIXME: It's quite possible for different conversions to see
6733 // different ambiguities, though.
6734 if (!ReportedAmbiguousConversions) {
John McCall5c32be02010-08-24 20:38:10 +00006735 NoteAmbiguousUserConversions(S, OpLoc, Cand);
John McCall0d1da222010-01-12 00:44:57 +00006736 ReportedAmbiguousConversions = true;
6737 }
John McCalld3224162010-01-08 00:58:21 +00006738
John McCall0d1da222010-01-12 00:44:57 +00006739 // If this is a viable builtin, print it.
John McCall5c32be02010-08-24 20:38:10 +00006740 NoteBuiltinOperatorCandidate(S, Opc, OpLoc, Cand);
Douglas Gregora11693b2008-11-12 17:17:38 +00006741 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006742 }
Jeffrey Yasskin2b99c6f2010-06-11 05:57:47 +00006743
6744 if (I != E)
John McCall5c32be02010-08-24 20:38:10 +00006745 S.Diag(OpLoc, diag::note_ovl_too_many_candidates) << int(E - I);
Douglas Gregor5251f1b2008-10-21 16:13:35 +00006746}
6747
John McCalla0296f72010-03-19 07:35:19 +00006748static bool CheckUnresolvedAccess(Sema &S, OverloadExpr *E, DeclAccessPair D) {
John McCall58cc69d2010-01-27 01:50:18 +00006749 if (isa<UnresolvedLookupExpr>(E))
John McCalla0296f72010-03-19 07:35:19 +00006750 return S.CheckUnresolvedLookupAccess(cast<UnresolvedLookupExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006751
John McCalla0296f72010-03-19 07:35:19 +00006752 return S.CheckUnresolvedMemberAccess(cast<UnresolvedMemberExpr>(E), D);
John McCall58cc69d2010-01-27 01:50:18 +00006753}
6754
Douglas Gregorcd695e52008-11-10 20:40:00 +00006755/// ResolveAddressOfOverloadedFunction - Try to resolve the address of
6756/// an overloaded function (C++ [over.over]), where @p From is an
6757/// expression with overloaded function type and @p ToType is the type
6758/// we're trying to resolve to. For example:
6759///
6760/// @code
6761/// int f(double);
6762/// int f(int);
Mike Stump11289f42009-09-09 15:08:12 +00006763///
Douglas Gregorcd695e52008-11-10 20:40:00 +00006764/// int (*pfd)(double) = f; // selects f(double)
6765/// @endcode
6766///
6767/// This routine returns the resulting FunctionDecl if it could be
6768/// resolved, and NULL otherwise. When @p Complain is true, this
6769/// routine will emit diagnostics if there is an error.
6770FunctionDecl *
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006771Sema::ResolveAddressOfOverloadedFunction(Expr *From, QualType ToType,
John McCall16df1e52010-03-30 21:47:33 +00006772 bool Complain,
6773 DeclAccessPair &FoundResult) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00006774 QualType FunctionType = ToType;
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006775 bool IsMember = false;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006776 if (const PointerType *ToTypePtr = ToType->getAs<PointerType>())
Douglas Gregorcd695e52008-11-10 20:40:00 +00006777 FunctionType = ToTypePtr->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006778 else if (const ReferenceType *ToTypeRef = ToType->getAs<ReferenceType>())
Daniel Dunbarb566c6c2009-02-26 19:13:44 +00006779 FunctionType = ToTypeRef->getPointeeType();
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006780 else if (const MemberPointerType *MemTypePtr =
Ted Kremenekc23c7e62009-07-29 21:53:49 +00006781 ToType->getAs<MemberPointerType>()) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006782 FunctionType = MemTypePtr->getPointeeType();
6783 IsMember = true;
6784 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006785
Douglas Gregorcd695e52008-11-10 20:40:00 +00006786 // C++ [over.over]p1:
6787 // [...] [Note: any redundant set of parentheses surrounding the
6788 // overloaded function name is ignored (5.1). ]
Douglas Gregorcd695e52008-11-10 20:40:00 +00006789 // C++ [over.over]p1:
6790 // [...] The overloaded function name can be preceded by the &
6791 // operator.
John McCall7d460512010-08-24 23:26:21 +00006792 // However, remember whether the expression has member-pointer form:
6793 // C++ [expr.unary.op]p4:
6794 // A pointer to member is only formed when an explicit & is used
6795 // and its operand is a qualified-id not enclosed in
6796 // parentheses.
John McCall8d08b9b2010-08-27 09:08:28 +00006797 OverloadExpr::FindResult Ovl = OverloadExpr::find(From);
6798 OverloadExpr *OvlExpr = Ovl.Expression;
John McCall7d460512010-08-24 23:26:21 +00006799
Douglas Gregor064fdb22010-04-14 23:11:21 +00006800 // We expect a pointer or reference to function, or a function pointer.
6801 FunctionType = Context.getCanonicalType(FunctionType).getUnqualifiedType();
6802 if (!FunctionType->isFunctionType()) {
6803 if (Complain)
6804 Diag(From->getLocStart(), diag::err_addr_ovl_not_func_ptrref)
6805 << OvlExpr->getName() << ToType;
6806
6807 return 0;
6808 }
6809
John McCall24d18942010-08-24 22:52:39 +00006810 // If the overload expression doesn't have the form of a pointer to
John McCall7d460512010-08-24 23:26:21 +00006811 // member, don't try to convert it to a pointer-to-member type.
John McCall8d08b9b2010-08-27 09:08:28 +00006812 if (IsMember && !Ovl.HasFormOfMemberPointer) {
John McCall24d18942010-08-24 22:52:39 +00006813 if (!Complain) return 0;
6814
6815 // TODO: Should we condition this on whether any functions might
6816 // have matched, or is it more appropriate to do that in callers?
6817 // TODO: a fixit wouldn't hurt.
6818 Diag(OvlExpr->getNameLoc(), diag::err_addr_ovl_no_qualifier)
6819 << ToType << OvlExpr->getSourceRange();
6820 return 0;
6821 }
6822
6823 TemplateArgumentListInfo ETABuffer, *ExplicitTemplateArgs = 0;
6824 if (OvlExpr->hasExplicitTemplateArgs()) {
6825 OvlExpr->getExplicitTemplateArgs().copyInto(ETABuffer);
6826 ExplicitTemplateArgs = &ETABuffer;
6827 }
6828
Douglas Gregor064fdb22010-04-14 23:11:21 +00006829 assert(From->getType() == Context.OverloadTy);
Douglas Gregorcd695e52008-11-10 20:40:00 +00006830
Douglas Gregorcd695e52008-11-10 20:40:00 +00006831 // Look through all of the overloaded functions, searching for one
6832 // whose type matches exactly.
John McCalla0296f72010-03-19 07:35:19 +00006833 llvm::SmallVector<std::pair<DeclAccessPair, FunctionDecl*>, 4> Matches;
Douglas Gregorb242683d2010-04-01 18:32:35 +00006834 llvm::SmallVector<FunctionDecl *, 4> NonMatches;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006835
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006836 bool FoundNonTemplateFunction = false;
John McCall1acbbb52010-02-02 06:20:04 +00006837 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6838 E = OvlExpr->decls_end(); I != E; ++I) {
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006839 // Look through any using declarations to find the underlying function.
6840 NamedDecl *Fn = (*I)->getUnderlyingDecl();
6841
Douglas Gregorcd695e52008-11-10 20:40:00 +00006842 // C++ [over.over]p3:
6843 // Non-member functions and static member functions match
Sebastian Redl16d307d2009-02-05 12:33:33 +00006844 // targets of type "pointer-to-function" or "reference-to-function."
6845 // Nonstatic member functions match targets of
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006846 // type "pointer-to-member-function."
6847 // Note that according to DR 247, the containing class does not matter.
Douglas Gregor9b146582009-07-08 20:55:45 +00006848
Mike Stump11289f42009-09-09 15:08:12 +00006849 if (FunctionTemplateDecl *FunctionTemplate
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006850 = dyn_cast<FunctionTemplateDecl>(Fn)) {
Mike Stump11289f42009-09-09 15:08:12 +00006851 if (CXXMethodDecl *Method
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006852 = dyn_cast<CXXMethodDecl>(FunctionTemplate->getTemplatedDecl())) {
Mike Stump11289f42009-09-09 15:08:12 +00006853 // Skip non-static function templates when converting to pointer, and
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006854 // static when converting to member pointer.
6855 if (Method->isStatic() == IsMember)
6856 continue;
6857 } else if (IsMember)
6858 continue;
Mike Stump11289f42009-09-09 15:08:12 +00006859
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006860 // C++ [over.over]p2:
Mike Stump11289f42009-09-09 15:08:12 +00006861 // If the name is a function template, template argument deduction is
6862 // done (14.8.2.2), and if the argument deduction succeeds, the
6863 // resulting template argument list is used to generate a single
6864 // function template specialization, which is added to the set of
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006865 // overloaded functions considered.
Douglas Gregor9b146582009-07-08 20:55:45 +00006866 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00006867 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor9b146582009-07-08 20:55:45 +00006868 if (TemplateDeductionResult Result
John McCall1acbbb52010-02-02 06:20:04 +00006869 = DeduceTemplateArguments(FunctionTemplate, ExplicitTemplateArgs,
Douglas Gregor9b146582009-07-08 20:55:45 +00006870 FunctionType, Specialization, Info)) {
6871 // FIXME: make a note of the failed deduction for diagnostics.
6872 (void)Result;
6873 } else {
Douglas Gregor4ed49f32010-09-29 21:14:36 +00006874 // Template argument deduction ensures that we have an exact match.
6875 // This function template specicalization works.
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006876 Specialization = cast<FunctionDecl>(Specialization->getCanonicalDecl());
Mike Stump11289f42009-09-09 15:08:12 +00006877 assert(FunctionType
Douglas Gregor9b146582009-07-08 20:55:45 +00006878 == Context.getCanonicalType(Specialization->getType()));
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006879 Matches.push_back(std::make_pair(I.getPair(), Specialization));
Douglas Gregor9b146582009-07-08 20:55:45 +00006880 }
John McCalld14a8642009-11-21 08:51:07 +00006881
6882 continue;
Douglas Gregor9b146582009-07-08 20:55:45 +00006883 }
Mike Stump11289f42009-09-09 15:08:12 +00006884
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006885 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006886 // Skip non-static functions when converting to pointer, and static
6887 // when converting to member pointer.
6888 if (Method->isStatic() == IsMember)
Douglas Gregorcd695e52008-11-10 20:40:00 +00006889 continue;
Douglas Gregord3319842009-10-24 04:59:53 +00006890
6891 // If we have explicit template arguments, skip non-templates.
John McCall1acbbb52010-02-02 06:20:04 +00006892 if (OvlExpr->hasExplicitTemplateArgs())
Douglas Gregord3319842009-10-24 04:59:53 +00006893 continue;
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006894 } else if (IsMember)
Sebastian Redl18f8ff62009-02-04 21:23:32 +00006895 continue;
Douglas Gregorcd695e52008-11-10 20:40:00 +00006896
Chandler Carruthc25c6ee2009-12-29 06:17:27 +00006897 if (FunctionDecl *FunDecl = dyn_cast<FunctionDecl>(Fn)) {
Douglas Gregor40cb9ad2009-12-09 00:47:37 +00006898 QualType ResultTy;
6899 if (Context.hasSameUnqualifiedType(FunctionType, FunDecl->getType()) ||
6900 IsNoReturnConversion(Context, FunDecl->getType(), FunctionType,
6901 ResultTy)) {
John McCalla0296f72010-03-19 07:35:19 +00006902 Matches.push_back(std::make_pair(I.getPair(),
6903 cast<FunctionDecl>(FunDecl->getCanonicalDecl())));
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006904 FoundNonTemplateFunction = true;
6905 }
Mike Stump11289f42009-09-09 15:08:12 +00006906 }
Douglas Gregorcd695e52008-11-10 20:40:00 +00006907 }
6908
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006909 // If there were 0 or 1 matches, we're done.
Douglas Gregor064fdb22010-04-14 23:11:21 +00006910 if (Matches.empty()) {
6911 if (Complain) {
6912 Diag(From->getLocStart(), diag::err_addr_ovl_no_viable)
6913 << OvlExpr->getName() << FunctionType;
6914 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
6915 E = OvlExpr->decls_end();
6916 I != E; ++I)
6917 if (FunctionDecl *F = dyn_cast<FunctionDecl>((*I)->getUnderlyingDecl()))
6918 NoteOverloadCandidate(F);
6919 }
6920
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006921 return 0;
Douglas Gregor064fdb22010-04-14 23:11:21 +00006922 } else if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006923 FunctionDecl *Result = Matches[0].second;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006924 FoundResult = Matches[0].first;
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006925 MarkDeclarationReferenced(From->getLocStart(), Result);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006926 if (Complain) {
John McCall16df1e52010-03-30 21:47:33 +00006927 CheckAddressOfMemberAccess(OvlExpr, Matches[0].first);
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006928 }
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006929 return Result;
6930 }
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006931
6932 // C++ [over.over]p4:
6933 // If more than one function is selected, [...]
Douglas Gregorfae1d712009-09-26 03:56:17 +00006934 if (!FoundNonTemplateFunction) {
Douglas Gregor05155d82009-08-21 23:19:43 +00006935 // [...] and any given function template specialization F1 is
6936 // eliminated if the set contains a second function template
6937 // specialization whose function template is more specialized
6938 // than the function template of F1 according to the partial
6939 // ordering rules of 14.5.5.2.
6940
6941 // The algorithm specified above is quadratic. We instead use a
6942 // two-pass algorithm (similar to the one used to identify the
6943 // best viable function in an overload set) that identifies the
6944 // best function template (if it exists).
John McCalla0296f72010-03-19 07:35:19 +00006945
6946 UnresolvedSet<4> MatchesCopy; // TODO: avoid!
6947 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6948 MatchesCopy.addDecl(Matches[I].second, Matches[I].first.getAccess());
John McCall58cc69d2010-01-27 01:50:18 +00006949
6950 UnresolvedSetIterator Result =
John McCalla0296f72010-03-19 07:35:19 +00006951 getMostSpecialized(MatchesCopy.begin(), MatchesCopy.end(),
Douglas Gregorb837ea42011-01-11 17:34:58 +00006952 TPOC_Other, 0, From->getLocStart(),
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006953 PDiag(),
6954 PDiag(diag::err_addr_ovl_ambiguous)
John McCalla0296f72010-03-19 07:35:19 +00006955 << Matches[0].second->getDeclName(),
John McCalle1ac8d12010-01-13 00:25:19 +00006956 PDiag(diag::note_ovl_candidate)
6957 << (unsigned) oc_function_template);
Douglas Gregorbdd7b232010-09-12 08:16:09 +00006958 if (Result == MatchesCopy.end())
6959 return 0;
6960
John McCall58cc69d2010-01-27 01:50:18 +00006961 MarkDeclarationReferenced(From->getLocStart(), *Result);
John McCall16df1e52010-03-30 21:47:33 +00006962 FoundResult = Matches[Result - MatchesCopy.begin()].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006963 if (Complain)
John McCall16df1e52010-03-30 21:47:33 +00006964 CheckUnresolvedAccess(*this, OvlExpr, FoundResult);
John McCall58cc69d2010-01-27 01:50:18 +00006965 return cast<FunctionDecl>(*Result);
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006966 }
Mike Stump11289f42009-09-09 15:08:12 +00006967
Douglas Gregorfae1d712009-09-26 03:56:17 +00006968 // [...] any function template specializations in the set are
6969 // eliminated if the set also contains a non-template function, [...]
John McCall58cc69d2010-01-27 01:50:18 +00006970 for (unsigned I = 0, N = Matches.size(); I != N; ) {
John McCalla0296f72010-03-19 07:35:19 +00006971 if (Matches[I].second->getPrimaryTemplate() == 0)
John McCall58cc69d2010-01-27 01:50:18 +00006972 ++I;
6973 else {
John McCalla0296f72010-03-19 07:35:19 +00006974 Matches[I] = Matches[--N];
6975 Matches.set_size(N);
John McCall58cc69d2010-01-27 01:50:18 +00006976 }
6977 }
Douglas Gregorfae1d712009-09-26 03:56:17 +00006978
Mike Stump11289f42009-09-09 15:08:12 +00006979 // [...] After such eliminations, if any, there shall remain exactly one
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006980 // selected function.
John McCall58cc69d2010-01-27 01:50:18 +00006981 if (Matches.size() == 1) {
John McCalla0296f72010-03-19 07:35:19 +00006982 MarkDeclarationReferenced(From->getLocStart(), Matches[0].second);
John McCall16df1e52010-03-30 21:47:33 +00006983 FoundResult = Matches[0].first;
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00006984 if (Complain)
John McCalla0296f72010-03-19 07:35:19 +00006985 CheckUnresolvedAccess(*this, OvlExpr, Matches[0].first);
6986 return cast<FunctionDecl>(Matches[0].second);
Sebastian Redldf4b80e2009-10-17 21:12:09 +00006987 }
Mike Stump11289f42009-09-09 15:08:12 +00006988
Douglas Gregorb257e4f2009-07-08 23:33:52 +00006989 // FIXME: We should probably return the same thing that BestViableFunction
6990 // returns (even if we issue the diagnostics here).
Douglas Gregore81f58e2010-11-08 03:40:48 +00006991 if (Complain) {
6992 Diag(From->getLocStart(), diag::err_addr_ovl_ambiguous)
6993 << Matches[0].second->getDeclName();
6994 for (unsigned I = 0, E = Matches.size(); I != E; ++I)
6995 NoteOverloadCandidate(Matches[I].second);
6996 }
6997
Douglas Gregorcd695e52008-11-10 20:40:00 +00006998 return 0;
6999}
7000
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007001/// \brief Given an expression that refers to an overloaded function, try to
7002/// resolve that overloaded function expression down to a single function.
7003///
7004/// This routine can only resolve template-ids that refer to a single function
7005/// template, where that template-id refers to a single template whose template
7006/// arguments are either provided by the template-id or have defaults,
7007/// as described in C++0x [temp.arg.explicit]p3.
7008FunctionDecl *Sema::ResolveSingleFunctionTemplateSpecialization(Expr *From) {
7009 // C++ [over.over]p1:
7010 // [...] [Note: any redundant set of parentheses surrounding the
7011 // overloaded function name is ignored (5.1). ]
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007012 // C++ [over.over]p1:
7013 // [...] The overloaded function name can be preceded by the &
7014 // operator.
John McCall1acbbb52010-02-02 06:20:04 +00007015
7016 if (From->getType() != Context.OverloadTy)
7017 return 0;
7018
John McCall8d08b9b2010-08-27 09:08:28 +00007019 OverloadExpr *OvlExpr = OverloadExpr::find(From).Expression;
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007020
7021 // If we didn't actually find any template-ids, we're done.
John McCall1acbbb52010-02-02 06:20:04 +00007022 if (!OvlExpr->hasExplicitTemplateArgs())
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007023 return 0;
John McCall1acbbb52010-02-02 06:20:04 +00007024
7025 TemplateArgumentListInfo ExplicitTemplateArgs;
7026 OvlExpr->getExplicitTemplateArgs().copyInto(ExplicitTemplateArgs);
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007027
7028 // Look through all of the overloaded functions, searching for one
7029 // whose type matches exactly.
7030 FunctionDecl *Matched = 0;
John McCall1acbbb52010-02-02 06:20:04 +00007031 for (UnresolvedSetIterator I = OvlExpr->decls_begin(),
7032 E = OvlExpr->decls_end(); I != E; ++I) {
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007033 // C++0x [temp.arg.explicit]p3:
7034 // [...] In contexts where deduction is done and fails, or in contexts
7035 // where deduction is not done, if a template argument list is
7036 // specified and it, along with any default template arguments,
7037 // identifies a single function template specialization, then the
7038 // template-id is an lvalue for the function template specialization.
Douglas Gregoreebe7212010-07-14 23:20:53 +00007039 FunctionTemplateDecl *FunctionTemplate
7040 = cast<FunctionTemplateDecl>((*I)->getUnderlyingDecl());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007041
7042 // C++ [over.over]p2:
7043 // If the name is a function template, template argument deduction is
7044 // done (14.8.2.2), and if the argument deduction succeeds, the
7045 // resulting template argument list is used to generate a single
7046 // function template specialization, which is added to the set of
7047 // overloaded functions considered.
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007048 FunctionDecl *Specialization = 0;
John McCallbc077cf2010-02-08 23:07:23 +00007049 TemplateDeductionInfo Info(Context, OvlExpr->getNameLoc());
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007050 if (TemplateDeductionResult Result
7051 = DeduceTemplateArguments(FunctionTemplate, &ExplicitTemplateArgs,
7052 Specialization, Info)) {
7053 // FIXME: make a note of the failed deduction for diagnostics.
7054 (void)Result;
7055 continue;
7056 }
7057
7058 // Multiple matches; we can't resolve to a single declaration.
7059 if (Matched)
7060 return 0;
7061
7062 Matched = Specialization;
7063 }
Douglas Gregor5bb5e4a2010-10-12 23:32:35 +00007064
Douglas Gregor8364e6b2009-12-21 23:17:24 +00007065 return Matched;
7066}
7067
Douglas Gregorcabea402009-09-22 15:41:20 +00007068/// \brief Add a single candidate to the overload set.
7069static void AddOverloadedCallCandidate(Sema &S,
John McCalla0296f72010-03-19 07:35:19 +00007070 DeclAccessPair FoundDecl,
John McCall6b51f282009-11-23 01:53:49 +00007071 const TemplateArgumentListInfo *ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007072 Expr **Args, unsigned NumArgs,
7073 OverloadCandidateSet &CandidateSet,
7074 bool PartialOverloading) {
John McCalla0296f72010-03-19 07:35:19 +00007075 NamedDecl *Callee = FoundDecl.getDecl();
John McCalld14a8642009-11-21 08:51:07 +00007076 if (isa<UsingShadowDecl>(Callee))
7077 Callee = cast<UsingShadowDecl>(Callee)->getTargetDecl();
7078
Douglas Gregorcabea402009-09-22 15:41:20 +00007079 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(Callee)) {
John McCall6b51f282009-11-23 01:53:49 +00007080 assert(!ExplicitTemplateArgs && "Explicit template arguments?");
John McCalla0296f72010-03-19 07:35:19 +00007081 S.AddOverloadCandidate(Func, FoundDecl, Args, NumArgs, CandidateSet,
Douglas Gregorb05275a2010-04-16 17:41:49 +00007082 false, PartialOverloading);
Douglas Gregorcabea402009-09-22 15:41:20 +00007083 return;
John McCalld14a8642009-11-21 08:51:07 +00007084 }
7085
7086 if (FunctionTemplateDecl *FuncTemplate
7087 = dyn_cast<FunctionTemplateDecl>(Callee)) {
John McCalla0296f72010-03-19 07:35:19 +00007088 S.AddTemplateOverloadCandidate(FuncTemplate, FoundDecl,
7089 ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007090 Args, NumArgs, CandidateSet);
John McCalld14a8642009-11-21 08:51:07 +00007091 return;
7092 }
7093
7094 assert(false && "unhandled case in overloaded call candidate");
7095
7096 // do nothing?
Douglas Gregorcabea402009-09-22 15:41:20 +00007097}
7098
7099/// \brief Add the overload candidates named by callee and/or found by argument
7100/// dependent lookup to the given overload set.
John McCall57500772009-12-16 12:17:52 +00007101void Sema::AddOverloadedCallCandidates(UnresolvedLookupExpr *ULE,
Douglas Gregorcabea402009-09-22 15:41:20 +00007102 Expr **Args, unsigned NumArgs,
7103 OverloadCandidateSet &CandidateSet,
7104 bool PartialOverloading) {
John McCalld14a8642009-11-21 08:51:07 +00007105
7106#ifndef NDEBUG
7107 // Verify that ArgumentDependentLookup is consistent with the rules
7108 // in C++0x [basic.lookup.argdep]p3:
Douglas Gregorcabea402009-09-22 15:41:20 +00007109 //
Douglas Gregorcabea402009-09-22 15:41:20 +00007110 // Let X be the lookup set produced by unqualified lookup (3.4.1)
7111 // and let Y be the lookup set produced by argument dependent
7112 // lookup (defined as follows). If X contains
7113 //
7114 // -- a declaration of a class member, or
7115 //
7116 // -- a block-scope function declaration that is not a
John McCalld14a8642009-11-21 08:51:07 +00007117 // using-declaration, or
Douglas Gregorcabea402009-09-22 15:41:20 +00007118 //
7119 // -- a declaration that is neither a function or a function
7120 // template
7121 //
7122 // then Y is empty.
John McCalld14a8642009-11-21 08:51:07 +00007123
John McCall57500772009-12-16 12:17:52 +00007124 if (ULE->requiresADL()) {
7125 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7126 E = ULE->decls_end(); I != E; ++I) {
7127 assert(!(*I)->getDeclContext()->isRecord());
7128 assert(isa<UsingShadowDecl>(*I) ||
7129 !(*I)->getDeclContext()->isFunctionOrMethod());
7130 assert((*I)->getUnderlyingDecl()->isFunctionOrFunctionTemplate());
John McCalld14a8642009-11-21 08:51:07 +00007131 }
7132 }
7133#endif
7134
John McCall57500772009-12-16 12:17:52 +00007135 // It would be nice to avoid this copy.
7136 TemplateArgumentListInfo TABuffer;
7137 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7138 if (ULE->hasExplicitTemplateArgs()) {
7139 ULE->copyTemplateArgumentsInto(TABuffer);
7140 ExplicitTemplateArgs = &TABuffer;
7141 }
7142
7143 for (UnresolvedLookupExpr::decls_iterator I = ULE->decls_begin(),
7144 E = ULE->decls_end(); I != E; ++I)
John McCalla0296f72010-03-19 07:35:19 +00007145 AddOverloadedCallCandidate(*this, I.getPair(), ExplicitTemplateArgs,
John McCalld14a8642009-11-21 08:51:07 +00007146 Args, NumArgs, CandidateSet,
Douglas Gregorcabea402009-09-22 15:41:20 +00007147 PartialOverloading);
John McCalld14a8642009-11-21 08:51:07 +00007148
John McCall57500772009-12-16 12:17:52 +00007149 if (ULE->requiresADL())
John McCall4c4c1df2010-01-26 03:27:55 +00007150 AddArgumentDependentLookupCandidates(ULE->getName(), /*Operator*/ false,
7151 Args, NumArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007152 ExplicitTemplateArgs,
Douglas Gregorcabea402009-09-22 15:41:20 +00007153 CandidateSet,
7154 PartialOverloading);
7155}
John McCalld681c392009-12-16 08:11:27 +00007156
7157/// Attempts to recover from a call where no functions were found.
7158///
7159/// Returns true if new candidates were found.
John McCalldadc5752010-08-24 06:29:42 +00007160static ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007161BuildRecoveryCallExpr(Sema &SemaRef, Scope *S, Expr *Fn,
John McCall57500772009-12-16 12:17:52 +00007162 UnresolvedLookupExpr *ULE,
7163 SourceLocation LParenLoc,
7164 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007165 SourceLocation RParenLoc) {
John McCalld681c392009-12-16 08:11:27 +00007166
7167 CXXScopeSpec SS;
7168 if (ULE->getQualifier()) {
7169 SS.setScopeRep(ULE->getQualifier());
7170 SS.setRange(ULE->getQualifierRange());
7171 }
7172
John McCall57500772009-12-16 12:17:52 +00007173 TemplateArgumentListInfo TABuffer;
7174 const TemplateArgumentListInfo *ExplicitTemplateArgs = 0;
7175 if (ULE->hasExplicitTemplateArgs()) {
7176 ULE->copyTemplateArgumentsInto(TABuffer);
7177 ExplicitTemplateArgs = &TABuffer;
7178 }
7179
John McCalld681c392009-12-16 08:11:27 +00007180 LookupResult R(SemaRef, ULE->getName(), ULE->getNameLoc(),
7181 Sema::LookupOrdinaryName);
Douglas Gregor5fd04d42010-05-18 16:14:23 +00007182 if (SemaRef.DiagnoseEmptyLookup(S, SS, R, Sema::CTC_Expression))
John McCallfaf5fb42010-08-26 23:41:50 +00007183 return ExprError();
John McCalld681c392009-12-16 08:11:27 +00007184
John McCall57500772009-12-16 12:17:52 +00007185 assert(!R.empty() && "lookup results empty despite recovery");
7186
7187 // Build an implicit member call if appropriate. Just drop the
7188 // casts and such from the call, we don't really care.
John McCallfaf5fb42010-08-26 23:41:50 +00007189 ExprResult NewFn = ExprError();
John McCall57500772009-12-16 12:17:52 +00007190 if ((*R.begin())->isCXXClassMember())
Chandler Carruth8e543b32010-12-12 08:17:55 +00007191 NewFn = SemaRef.BuildPossibleImplicitMemberExpr(SS, R,
7192 ExplicitTemplateArgs);
John McCall57500772009-12-16 12:17:52 +00007193 else if (ExplicitTemplateArgs)
7194 NewFn = SemaRef.BuildTemplateIdExpr(SS, R, false, *ExplicitTemplateArgs);
7195 else
7196 NewFn = SemaRef.BuildDeclarationNameExpr(SS, R, false);
7197
7198 if (NewFn.isInvalid())
John McCallfaf5fb42010-08-26 23:41:50 +00007199 return ExprError();
John McCall57500772009-12-16 12:17:52 +00007200
7201 // This shouldn't cause an infinite loop because we're giving it
7202 // an expression with non-empty lookup results, which should never
7203 // end up here.
John McCallb268a282010-08-23 23:25:46 +00007204 return SemaRef.ActOnCallExpr(/*Scope*/ 0, NewFn.take(), LParenLoc,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007205 MultiExprArg(Args, NumArgs), RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007206}
Douglas Gregor4038cf42010-06-08 17:35:15 +00007207
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007208/// ResolveOverloadedCallFn - Given the call expression that calls Fn
Douglas Gregore254f902009-02-04 00:32:51 +00007209/// (which eventually refers to the declaration Func) and the call
7210/// arguments Args/NumArgs, attempt to resolve the function call down
7211/// to a specific function. If overload resolution succeeds, returns
7212/// the function declaration produced by overload
Douglas Gregora60a6912008-11-26 06:01:48 +00007213/// resolution. Otherwise, emits diagnostics, deletes all of the
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007214/// arguments and Fn, and returns NULL.
John McCalldadc5752010-08-24 06:29:42 +00007215ExprResult
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007216Sema::BuildOverloadedCallExpr(Scope *S, Expr *Fn, UnresolvedLookupExpr *ULE,
John McCall57500772009-12-16 12:17:52 +00007217 SourceLocation LParenLoc,
7218 Expr **Args, unsigned NumArgs,
John McCall57500772009-12-16 12:17:52 +00007219 SourceLocation RParenLoc) {
7220#ifndef NDEBUG
7221 if (ULE->requiresADL()) {
7222 // To do ADL, we must have found an unqualified name.
7223 assert(!ULE->getQualifier() && "qualified name with ADL");
7224
7225 // We don't perform ADL for implicit declarations of builtins.
7226 // Verify that this was correctly set up.
7227 FunctionDecl *F;
7228 if (ULE->decls_begin() + 1 == ULE->decls_end() &&
7229 (F = dyn_cast<FunctionDecl>(*ULE->decls_begin())) &&
7230 F->getBuiltinID() && F->isImplicit())
7231 assert(0 && "performing ADL for builtin");
7232
7233 // We don't perform ADL in C.
7234 assert(getLangOptions().CPlusPlus && "ADL enabled in C");
7235 }
7236#endif
7237
John McCallbc077cf2010-02-08 23:07:23 +00007238 OverloadCandidateSet CandidateSet(Fn->getExprLoc());
Douglas Gregorb8a9a412009-02-04 15:01:18 +00007239
John McCall57500772009-12-16 12:17:52 +00007240 // Add the functions denoted by the callee to the set of candidate
7241 // functions, including those from argument-dependent lookup.
7242 AddOverloadedCallCandidates(ULE, Args, NumArgs, CandidateSet);
John McCalld681c392009-12-16 08:11:27 +00007243
7244 // If we found nothing, try to recover.
7245 // AddRecoveryCallCandidates diagnoses the error itself, so we just
7246 // bailout out if it fails.
John McCall57500772009-12-16 12:17:52 +00007247 if (CandidateSet.empty())
Douglas Gregor2fb18b72010-04-14 20:27:54 +00007248 return BuildRecoveryCallExpr(*this, S, Fn, ULE, LParenLoc, Args, NumArgs,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007249 RParenLoc);
John McCalld681c392009-12-16 08:11:27 +00007250
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007251 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007252 switch (CandidateSet.BestViableFunction(*this, Fn->getLocStart(), Best)) {
John McCall57500772009-12-16 12:17:52 +00007253 case OR_Success: {
7254 FunctionDecl *FDecl = Best->Function;
John McCalla0296f72010-03-19 07:35:19 +00007255 CheckUnresolvedLookupAccess(ULE, Best->FoundDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007256 DiagnoseUseOfDecl(FDecl? FDecl : Best->FoundDecl.getDecl(),
7257 ULE->getNameLoc());
John McCall16df1e52010-03-30 21:47:33 +00007258 Fn = FixOverloadedFunctionReference(Fn, Best->FoundDecl, FDecl);
Chandler Carruth8e543b32010-12-12 08:17:55 +00007259 return BuildResolvedCallExpr(Fn, FDecl, LParenLoc, Args, NumArgs,
7260 RParenLoc);
John McCall57500772009-12-16 12:17:52 +00007261 }
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007262
7263 case OR_No_Viable_Function:
Chris Lattner45d9d602009-02-17 07:29:20 +00007264 Diag(Fn->getSourceRange().getBegin(),
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007265 diag::err_ovl_no_viable_function_in_call)
John McCall57500772009-12-16 12:17:52 +00007266 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007267 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007268 break;
7269
7270 case OR_Ambiguous:
7271 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_ambiguous_call)
John McCall57500772009-12-16 12:17:52 +00007272 << ULE->getName() << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007273 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007274 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00007275
7276 case OR_Deleted:
7277 Diag(Fn->getSourceRange().getBegin(), diag::err_ovl_deleted_call)
7278 << Best->Function->isDeleted()
John McCall57500772009-12-16 12:17:52 +00007279 << ULE->getName()
Douglas Gregor171c45a2009-02-18 21:56:37 +00007280 << Fn->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007281 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007282 break;
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007283 }
7284
Douglas Gregorb412e172010-07-25 18:17:45 +00007285 // Overload resolution failed.
John McCall57500772009-12-16 12:17:52 +00007286 return ExprError();
Douglas Gregor99dcbff2008-11-26 05:54:23 +00007287}
7288
John McCall4c4c1df2010-01-26 03:27:55 +00007289static bool IsOverloaded(const UnresolvedSetImpl &Functions) {
John McCall283b9012009-11-22 00:44:51 +00007290 return Functions.size() > 1 ||
7291 (Functions.size() == 1 && isa<FunctionTemplateDecl>(*Functions.begin()));
7292}
7293
Douglas Gregor084d8552009-03-13 23:49:33 +00007294/// \brief Create a unary operation that may resolve to an overloaded
7295/// operator.
7296///
7297/// \param OpLoc The location of the operator itself (e.g., '*').
7298///
7299/// \param OpcIn The UnaryOperator::Opcode that describes this
7300/// operator.
7301///
7302/// \param Functions The set of non-member functions that will be
7303/// considered by overload resolution. The caller needs to build this
7304/// set based on the context using, e.g.,
7305/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7306/// set should not contain any member functions; those will be added
7307/// by CreateOverloadedUnaryOp().
7308///
7309/// \param input The input argument.
John McCalldadc5752010-08-24 06:29:42 +00007310ExprResult
John McCall4c4c1df2010-01-26 03:27:55 +00007311Sema::CreateOverloadedUnaryOp(SourceLocation OpLoc, unsigned OpcIn,
7312 const UnresolvedSetImpl &Fns,
John McCallb268a282010-08-23 23:25:46 +00007313 Expr *Input) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007314 UnaryOperator::Opcode Opc = static_cast<UnaryOperator::Opcode>(OpcIn);
Douglas Gregor084d8552009-03-13 23:49:33 +00007315
7316 OverloadedOperatorKind Op = UnaryOperator::getOverloadedOperator(Opc);
7317 assert(Op != OO_None && "Invalid opcode for overloaded unary operator");
7318 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007319 // TODO: provide better source location info.
7320 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007321
John McCalle26a8722010-12-04 08:14:53 +00007322 if (Input->getObjectKind() == OK_ObjCProperty)
7323 ConvertPropertyForRValue(Input);
7324
Douglas Gregor084d8552009-03-13 23:49:33 +00007325 Expr *Args[2] = { Input, 0 };
7326 unsigned NumArgs = 1;
Mike Stump11289f42009-09-09 15:08:12 +00007327
Douglas Gregor084d8552009-03-13 23:49:33 +00007328 // For post-increment and post-decrement, add the implicit '0' as
7329 // the second argument, so that we know this is a post-increment or
7330 // post-decrement.
John McCalle3027922010-08-25 11:45:40 +00007331 if (Opc == UO_PostInc || Opc == UO_PostDec) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007332 llvm::APSInt Zero(Context.getTypeSize(Context.IntTy), false);
Argyrios Kyrtzidis43b20572010-08-28 09:06:06 +00007333 Args[1] = IntegerLiteral::Create(Context, Zero, Context.IntTy,
7334 SourceLocation());
Douglas Gregor084d8552009-03-13 23:49:33 +00007335 NumArgs = 2;
7336 }
7337
7338 if (Input->isTypeDependent()) {
Douglas Gregor630dec52010-06-17 15:46:20 +00007339 if (Fns.empty())
John McCallb268a282010-08-23 23:25:46 +00007340 return Owned(new (Context) UnaryOperator(Input,
Douglas Gregor630dec52010-06-17 15:46:20 +00007341 Opc,
7342 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007343 VK_RValue, OK_Ordinary,
Douglas Gregor630dec52010-06-17 15:46:20 +00007344 OpLoc));
7345
John McCall58cc69d2010-01-27 01:50:18 +00007346 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
John McCalld14a8642009-11-21 08:51:07 +00007347 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007348 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007349 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007350 /*ADL*/ true, IsOverloaded(Fns),
7351 Fns.begin(), Fns.end());
Douglas Gregor084d8552009-03-13 23:49:33 +00007352 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
7353 &Args[0], NumArgs,
7354 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007355 VK_RValue,
Douglas Gregor084d8552009-03-13 23:49:33 +00007356 OpLoc));
7357 }
7358
7359 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007360 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007361
7362 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007363 AddFunctionCandidates(Fns, &Args[0], NumArgs, CandidateSet, false);
Douglas Gregor084d8552009-03-13 23:49:33 +00007364
7365 // Add operator candidates that are member functions.
7366 AddMemberOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
7367
John McCall4c4c1df2010-01-26 03:27:55 +00007368 // Add candidates from ADL.
7369 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
Douglas Gregor6ec89d42010-02-05 05:15:43 +00007370 Args, NumArgs,
John McCall4c4c1df2010-01-26 03:27:55 +00007371 /*ExplicitTemplateArgs*/ 0,
7372 CandidateSet);
7373
Douglas Gregor084d8552009-03-13 23:49:33 +00007374 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007375 AddBuiltinOperatorCandidates(Op, OpLoc, &Args[0], NumArgs, CandidateSet);
Douglas Gregor084d8552009-03-13 23:49:33 +00007376
7377 // Perform overload resolution.
7378 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007379 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregor084d8552009-03-13 23:49:33 +00007380 case OR_Success: {
7381 // We found a built-in operator or an overloaded operator.
7382 FunctionDecl *FnDecl = Best->Function;
Mike Stump11289f42009-09-09 15:08:12 +00007383
Douglas Gregor084d8552009-03-13 23:49:33 +00007384 if (FnDecl) {
7385 // We matched an overloaded operator. Build a call to that
7386 // operator.
Mike Stump11289f42009-09-09 15:08:12 +00007387
Douglas Gregor084d8552009-03-13 23:49:33 +00007388 // Convert the arguments.
7389 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCalla0296f72010-03-19 07:35:19 +00007390 CheckMemberOperatorAccess(OpLoc, Args[0], 0, Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007391
John McCall16df1e52010-03-30 21:47:33 +00007392 if (PerformObjectArgumentInitialization(Input, /*Qualifier=*/0,
7393 Best->FoundDecl, Method))
Douglas Gregor084d8552009-03-13 23:49:33 +00007394 return ExprError();
7395 } else {
7396 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007397 ExprResult InputInit
Douglas Gregore6600372009-12-23 17:40:29 +00007398 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007399 Context,
Douglas Gregor8d48e9a2009-12-23 00:02:00 +00007400 FnDecl->getParamDecl(0)),
Douglas Gregore6600372009-12-23 17:40:29 +00007401 SourceLocation(),
John McCallb268a282010-08-23 23:25:46 +00007402 Input);
Douglas Gregore6600372009-12-23 17:40:29 +00007403 if (InputInit.isInvalid())
Douglas Gregor084d8552009-03-13 23:49:33 +00007404 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00007405 Input = InputInit.take();
Douglas Gregor084d8552009-03-13 23:49:33 +00007406 }
7407
John McCall4fa0d5f2010-05-06 18:15:07 +00007408 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7409
John McCall7decc9e2010-11-18 06:31:45 +00007410 // Determine the result type.
7411 QualType ResultTy = FnDecl->getResultType();
7412 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7413 ResultTy = ResultTy.getNonLValueExprType(Context);
Mike Stump11289f42009-09-09 15:08:12 +00007414
Douglas Gregor084d8552009-03-13 23:49:33 +00007415 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007416 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl);
Mike Stump11289f42009-09-09 15:08:12 +00007417
Eli Friedman030eee42009-11-18 03:58:17 +00007418 Args[0] = Input;
John McCallb268a282010-08-23 23:25:46 +00007419 CallExpr *TheCall =
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007420 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007421 Args, NumArgs, ResultTy, VK, OpLoc);
John McCall4fa0d5f2010-05-06 18:15:07 +00007422
John McCallb268a282010-08-23 23:25:46 +00007423 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssonf64a3da2009-10-13 21:19:37 +00007424 FnDecl))
7425 return ExprError();
7426
John McCallb268a282010-08-23 23:25:46 +00007427 return MaybeBindToTemporary(TheCall);
Douglas Gregor084d8552009-03-13 23:49:33 +00007428 } else {
7429 // We matched a built-in operator. Convert the arguments, then
7430 // break out so that we will build the appropriate built-in
7431 // operator node.
7432 if (PerformImplicitConversion(Input, Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007433 Best->Conversions[0], AA_Passing))
Douglas Gregor084d8552009-03-13 23:49:33 +00007434 return ExprError();
7435
7436 break;
7437 }
7438 }
7439
7440 case OR_No_Viable_Function:
7441 // No viable function; fall through to handling this as a
7442 // built-in operator, which will produce an error message for us.
7443 break;
7444
7445 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007446 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
Douglas Gregor084d8552009-03-13 23:49:33 +00007447 << UnaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007448 << Input->getType()
Douglas Gregor084d8552009-03-13 23:49:33 +00007449 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007450 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates,
7451 Args, NumArgs,
7452 UnaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor084d8552009-03-13 23:49:33 +00007453 return ExprError();
7454
7455 case OR_Deleted:
7456 Diag(OpLoc, diag::err_ovl_deleted_oper)
7457 << Best->Function->isDeleted()
7458 << UnaryOperator::getOpcodeStr(Opc)
7459 << Input->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007460 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor084d8552009-03-13 23:49:33 +00007461 return ExprError();
7462 }
7463
7464 // Either we found no viable overloaded operator or we matched a
7465 // built-in operator. In either case, fall through to trying to
7466 // build a built-in operation.
John McCallb268a282010-08-23 23:25:46 +00007467 return CreateBuiltinUnaryOp(OpLoc, Opc, Input);
Douglas Gregor084d8552009-03-13 23:49:33 +00007468}
7469
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007470/// \brief Create a binary operation that may resolve to an overloaded
7471/// operator.
7472///
7473/// \param OpLoc The location of the operator itself (e.g., '+').
7474///
7475/// \param OpcIn The BinaryOperator::Opcode that describes this
7476/// operator.
7477///
7478/// \param Functions The set of non-member functions that will be
7479/// considered by overload resolution. The caller needs to build this
7480/// set based on the context using, e.g.,
7481/// LookupOverloadedOperatorName() and ArgumentDependentLookup(). This
7482/// set should not contain any member functions; those will be added
7483/// by CreateOverloadedBinOp().
7484///
7485/// \param LHS Left-hand argument.
7486/// \param RHS Right-hand argument.
John McCalldadc5752010-08-24 06:29:42 +00007487ExprResult
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007488Sema::CreateOverloadedBinOp(SourceLocation OpLoc,
Mike Stump11289f42009-09-09 15:08:12 +00007489 unsigned OpcIn,
John McCall4c4c1df2010-01-26 03:27:55 +00007490 const UnresolvedSetImpl &Fns,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007491 Expr *LHS, Expr *RHS) {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007492 Expr *Args[2] = { LHS, RHS };
Douglas Gregore9899d92009-08-26 17:08:25 +00007493 LHS=RHS=0; //Please use only Args instead of LHS/RHS couple
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007494
7495 BinaryOperator::Opcode Opc = static_cast<BinaryOperator::Opcode>(OpcIn);
7496 OverloadedOperatorKind Op = BinaryOperator::getOverloadedOperator(Opc);
7497 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(Op);
7498
7499 // If either side is type-dependent, create an appropriate dependent
7500 // expression.
Douglas Gregore9899d92009-08-26 17:08:25 +00007501 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
John McCall4c4c1df2010-01-26 03:27:55 +00007502 if (Fns.empty()) {
Douglas Gregor5287f092009-11-05 00:51:44 +00007503 // If there are no functions to store, just build a dependent
7504 // BinaryOperator or CompoundAssignment.
John McCalle3027922010-08-25 11:45:40 +00007505 if (Opc <= BO_Assign || Opc > BO_OrAssign)
Douglas Gregor5287f092009-11-05 00:51:44 +00007506 return Owned(new (Context) BinaryOperator(Args[0], Args[1], Opc,
John McCall7decc9e2010-11-18 06:31:45 +00007507 Context.DependentTy,
7508 VK_RValue, OK_Ordinary,
7509 OpLoc));
Douglas Gregor5287f092009-11-05 00:51:44 +00007510
7511 return Owned(new (Context) CompoundAssignOperator(Args[0], Args[1], Opc,
7512 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007513 VK_LValue,
7514 OK_Ordinary,
Douglas Gregor5287f092009-11-05 00:51:44 +00007515 Context.DependentTy,
7516 Context.DependentTy,
7517 OpLoc));
7518 }
John McCall4c4c1df2010-01-26 03:27:55 +00007519
7520 // FIXME: save results of ADL from here?
John McCall58cc69d2010-01-27 01:50:18 +00007521 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007522 // TODO: provide better source location info in DNLoc component.
7523 DeclarationNameInfo OpNameInfo(OpName, OpLoc);
John McCalld14a8642009-11-21 08:51:07 +00007524 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007525 = UnresolvedLookupExpr::Create(Context, NamingClass, 0, SourceRange(),
7526 OpNameInfo, /*ADL*/ true, IsOverloaded(Fns),
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007527 Fns.begin(), Fns.end());
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007528 return Owned(new (Context) CXXOperatorCallExpr(Context, Op, Fn,
Mike Stump11289f42009-09-09 15:08:12 +00007529 Args, 2,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007530 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007531 VK_RValue,
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007532 OpLoc));
7533 }
7534
John McCalle26a8722010-12-04 08:14:53 +00007535 // Always do property rvalue conversions on the RHS.
7536 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7537 ConvertPropertyForRValue(Args[1]);
7538
7539 // The LHS is more complicated.
7540 if (Args[0]->getObjectKind() == OK_ObjCProperty) {
7541
7542 // There's a tension for assignment operators between primitive
7543 // property assignment and the overloaded operators.
7544 if (BinaryOperator::isAssignmentOp(Opc)) {
7545 const ObjCPropertyRefExpr *PRE = LHS->getObjCProperty();
7546
7547 // Is the property "logically" settable?
7548 bool Settable = (PRE->isExplicitProperty() ||
7549 PRE->getImplicitPropertySetter());
7550
7551 // To avoid gratuitously inventing semantics, use the primitive
7552 // unless it isn't. Thoughts in case we ever really care:
7553 // - If the property isn't logically settable, we have to
7554 // load and hope.
7555 // - If the property is settable and this is simple assignment,
7556 // we really should use the primitive.
7557 // - If the property is settable, then we could try overloading
7558 // on a generic lvalue of the appropriate type; if it works
7559 // out to a builtin candidate, we would do that same operation
7560 // on the property, and otherwise just error.
7561 if (Settable)
7562 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7563 }
7564
7565 ConvertPropertyForRValue(Args[0]);
7566 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007567
Sebastian Redl6a96bf72009-11-18 23:10:33 +00007568 // If this is the assignment operator, we only perform overload resolution
7569 // if the left-hand side is a class or enumeration type. This is actually
7570 // a hack. The standard requires that we do overload resolution between the
7571 // various built-in candidates, but as DR507 points out, this can lead to
7572 // problems. So we do it this way, which pretty much follows what GCC does.
7573 // Note that we go the traditional code path for compound assignment forms.
John McCalle3027922010-08-25 11:45:40 +00007574 if (Opc == BO_Assign && !Args[0]->getType()->isOverloadableType())
Douglas Gregore9899d92009-08-26 17:08:25 +00007575 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007576
John McCalle26a8722010-12-04 08:14:53 +00007577 // If this is the .* operator, which is not overloadable, just
7578 // create a built-in binary operator.
7579 if (Opc == BO_PtrMemD)
7580 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
7581
Douglas Gregor084d8552009-03-13 23:49:33 +00007582 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007583 OverloadCandidateSet CandidateSet(OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007584
7585 // Add the candidates from the given function set.
John McCall4c4c1df2010-01-26 03:27:55 +00007586 AddFunctionCandidates(Fns, Args, 2, CandidateSet, false);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007587
7588 // Add operator candidates that are member functions.
7589 AddMemberOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
7590
John McCall4c4c1df2010-01-26 03:27:55 +00007591 // Add candidates from ADL.
7592 AddArgumentDependentLookupCandidates(OpName, /*Operator*/ true,
7593 Args, 2,
7594 /*ExplicitTemplateArgs*/ 0,
7595 CandidateSet);
7596
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007597 // Add builtin operator candidates.
Douglas Gregorc02cfe22009-10-21 23:19:44 +00007598 AddBuiltinOperatorCandidates(Op, OpLoc, Args, 2, CandidateSet);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007599
7600 // Perform overload resolution.
7601 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007602 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Sebastian Redl1a99f442009-04-16 17:51:27 +00007603 case OR_Success: {
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007604 // We found a built-in operator or an overloaded operator.
7605 FunctionDecl *FnDecl = Best->Function;
7606
7607 if (FnDecl) {
7608 // We matched an overloaded operator. Build a call to that
7609 // operator.
7610
7611 // Convert the arguments.
7612 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FnDecl)) {
John McCallb3a44002010-01-28 01:42:12 +00007613 // Best->Access is only meaningful for class members.
John McCalla0296f72010-03-19 07:35:19 +00007614 CheckMemberOperatorAccess(OpLoc, Args[0], Args[1], Best->FoundDecl);
John McCallb3a44002010-01-28 01:42:12 +00007615
Chandler Carruth8e543b32010-12-12 08:17:55 +00007616 ExprResult Arg1 =
7617 PerformCopyInitialization(
7618 InitializedEntity::InitializeParameter(Context,
7619 FnDecl->getParamDecl(0)),
7620 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007621 if (Arg1.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007622 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007623
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007624 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007625 Best->FoundDecl, Method))
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007626 return ExprError();
7627
7628 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007629 } else {
7630 // Convert the arguments.
Chandler Carruth8e543b32010-12-12 08:17:55 +00007631 ExprResult Arg0 = PerformCopyInitialization(
7632 InitializedEntity::InitializeParameter(Context,
7633 FnDecl->getParamDecl(0)),
7634 SourceLocation(), Owned(Args[0]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007635 if (Arg0.isInvalid())
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007636 return ExprError();
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007637
Chandler Carruth8e543b32010-12-12 08:17:55 +00007638 ExprResult Arg1 =
7639 PerformCopyInitialization(
7640 InitializedEntity::InitializeParameter(Context,
7641 FnDecl->getParamDecl(1)),
7642 SourceLocation(), Owned(Args[1]));
Douglas Gregor0a70c4d2009-12-22 21:44:34 +00007643 if (Arg1.isInvalid())
7644 return ExprError();
7645 Args[0] = LHS = Arg0.takeAs<Expr>();
7646 Args[1] = RHS = Arg1.takeAs<Expr>();
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007647 }
7648
John McCall4fa0d5f2010-05-06 18:15:07 +00007649 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
7650
John McCall7decc9e2010-11-18 06:31:45 +00007651 // Determine the result type.
7652 QualType ResultTy = FnDecl->getResultType();
7653 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7654 ResultTy = ResultTy.getNonLValueExprType(Context);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007655
7656 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007657 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007658
John McCallb268a282010-08-23 23:25:46 +00007659 CXXOperatorCallExpr *TheCall =
7660 new (Context) CXXOperatorCallExpr(Context, Op, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00007661 Args, 2, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007662
John McCallb268a282010-08-23 23:25:46 +00007663 if (CheckCallReturnType(FnDecl->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00007664 FnDecl))
7665 return ExprError();
7666
John McCallb268a282010-08-23 23:25:46 +00007667 return MaybeBindToTemporary(TheCall);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007668 } else {
7669 // We matched a built-in operator. Convert the arguments, then
7670 // break out so that we will build the appropriate built-in
7671 // operator node.
Douglas Gregore9899d92009-08-26 17:08:25 +00007672 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007673 Best->Conversions[0], AA_Passing) ||
Douglas Gregore9899d92009-08-26 17:08:25 +00007674 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007675 Best->Conversions[1], AA_Passing))
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007676 return ExprError();
7677
7678 break;
7679 }
7680 }
7681
Douglas Gregor66950a32009-09-30 21:46:01 +00007682 case OR_No_Viable_Function: {
7683 // C++ [over.match.oper]p9:
7684 // If the operator is the operator , [...] and there are no
7685 // viable functions, then the operator is assumed to be the
7686 // built-in operator and interpreted according to clause 5.
John McCalle3027922010-08-25 11:45:40 +00007687 if (Opc == BO_Comma)
Douglas Gregor66950a32009-09-30 21:46:01 +00007688 break;
7689
Chandler Carruth8e543b32010-12-12 08:17:55 +00007690 // For class as left operand for assignment or compound assigment
7691 // operator do not fall through to handling in built-in, but report that
7692 // no overloaded assignment operator found
John McCalldadc5752010-08-24 06:29:42 +00007693 ExprResult Result = ExprError();
Douglas Gregor66950a32009-09-30 21:46:01 +00007694 if (Args[0]->getType()->isRecordType() &&
John McCalle3027922010-08-25 11:45:40 +00007695 Opc >= BO_Assign && Opc <= BO_OrAssign) {
Sebastian Redl027de2a2009-05-21 11:50:50 +00007696 Diag(OpLoc, diag::err_ovl_no_viable_oper)
7697 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007698 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
Douglas Gregor66950a32009-09-30 21:46:01 +00007699 } else {
7700 // No viable function; try to create a built-in operation, which will
7701 // produce an error. Then, show the non-viable candidates.
7702 Result = CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Sebastian Redl027de2a2009-05-21 11:50:50 +00007703 }
Douglas Gregor66950a32009-09-30 21:46:01 +00007704 assert(Result.isInvalid() &&
7705 "C++ binary operator overloading is missing candidates!");
7706 if (Result.isInvalid())
John McCall5c32be02010-08-24 20:38:10 +00007707 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7708 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor66950a32009-09-30 21:46:01 +00007709 return move(Result);
7710 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007711
7712 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007713 Diag(OpLoc, diag::err_ovl_ambiguous_oper_binary)
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007714 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregor052caec2010-11-13 20:06:38 +00007715 << Args[0]->getType() << Args[1]->getType()
Douglas Gregore9899d92009-08-26 17:08:25 +00007716 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007717 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7718 BinaryOperator::getOpcodeStr(Opc), OpLoc);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007719 return ExprError();
7720
7721 case OR_Deleted:
7722 Diag(OpLoc, diag::err_ovl_deleted_oper)
7723 << Best->Function->isDeleted()
7724 << BinaryOperator::getOpcodeStr(Opc)
Douglas Gregore9899d92009-08-26 17:08:25 +00007725 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007726 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007727 return ExprError();
John McCall0d1da222010-01-12 00:44:57 +00007728 }
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007729
Douglas Gregor66950a32009-09-30 21:46:01 +00007730 // We matched a built-in operator; build it.
Douglas Gregore9899d92009-08-26 17:08:25 +00007731 return CreateBuiltinBinOp(OpLoc, Opc, Args[0], Args[1]);
Douglas Gregor1baf54e2009-03-13 18:40:31 +00007732}
7733
John McCalldadc5752010-08-24 06:29:42 +00007734ExprResult
Sebastian Redladba46e2009-10-29 20:17:01 +00007735Sema::CreateOverloadedArraySubscriptExpr(SourceLocation LLoc,
7736 SourceLocation RLoc,
John McCallb268a282010-08-23 23:25:46 +00007737 Expr *Base, Expr *Idx) {
7738 Expr *Args[2] = { Base, Idx };
Sebastian Redladba46e2009-10-29 20:17:01 +00007739 DeclarationName OpName =
7740 Context.DeclarationNames.getCXXOperatorName(OO_Subscript);
7741
7742 // If either side is type-dependent, create an appropriate dependent
7743 // expression.
7744 if (Args[0]->isTypeDependent() || Args[1]->isTypeDependent()) {
7745
John McCall58cc69d2010-01-27 01:50:18 +00007746 CXXRecordDecl *NamingClass = 0; // because lookup ignores member operators
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007747 // CHECKME: no 'operator' keyword?
7748 DeclarationNameInfo OpNameInfo(OpName, LLoc);
7749 OpNameInfo.setCXXOperatorNameRange(SourceRange(LLoc, RLoc));
John McCalld14a8642009-11-21 08:51:07 +00007750 UnresolvedLookupExpr *Fn
Douglas Gregora6e053e2010-12-15 01:34:56 +00007751 = UnresolvedLookupExpr::Create(Context, NamingClass,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00007752 0, SourceRange(), OpNameInfo,
Douglas Gregor30a4f4c2010-05-23 18:57:34 +00007753 /*ADL*/ true, /*Overloaded*/ false,
7754 UnresolvedSetIterator(),
7755 UnresolvedSetIterator());
John McCalle66edc12009-11-24 19:00:30 +00007756 // Can't add any actual overloads yet
Sebastian Redladba46e2009-10-29 20:17:01 +00007757
Sebastian Redladba46e2009-10-29 20:17:01 +00007758 return Owned(new (Context) CXXOperatorCallExpr(Context, OO_Subscript, Fn,
7759 Args, 2,
7760 Context.DependentTy,
John McCall7decc9e2010-11-18 06:31:45 +00007761 VK_RValue,
Sebastian Redladba46e2009-10-29 20:17:01 +00007762 RLoc));
7763 }
7764
John McCalle26a8722010-12-04 08:14:53 +00007765 if (Args[0]->getObjectKind() == OK_ObjCProperty)
7766 ConvertPropertyForRValue(Args[0]);
7767 if (Args[1]->getObjectKind() == OK_ObjCProperty)
7768 ConvertPropertyForRValue(Args[1]);
7769
Sebastian Redladba46e2009-10-29 20:17:01 +00007770 // Build an empty overload set.
John McCallbc077cf2010-02-08 23:07:23 +00007771 OverloadCandidateSet CandidateSet(LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007772
7773 // Subscript can only be overloaded as a member function.
7774
7775 // Add operator candidates that are member functions.
7776 AddMemberOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7777
7778 // Add builtin operator candidates.
7779 AddBuiltinOperatorCandidates(OO_Subscript, LLoc, Args, 2, CandidateSet);
7780
7781 // Perform overload resolution.
7782 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007783 switch (CandidateSet.BestViableFunction(*this, LLoc, Best)) {
Sebastian Redladba46e2009-10-29 20:17:01 +00007784 case OR_Success: {
7785 // We found a built-in operator or an overloaded operator.
7786 FunctionDecl *FnDecl = Best->Function;
7787
7788 if (FnDecl) {
7789 // We matched an overloaded operator. Build a call to that
7790 // operator.
7791
John McCalla0296f72010-03-19 07:35:19 +00007792 CheckMemberOperatorAccess(LLoc, Args[0], Args[1], Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007793 DiagnoseUseOfDecl(Best->FoundDecl, LLoc);
John McCall58cc69d2010-01-27 01:50:18 +00007794
Sebastian Redladba46e2009-10-29 20:17:01 +00007795 // Convert the arguments.
7796 CXXMethodDecl *Method = cast<CXXMethodDecl>(FnDecl);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007797 if (PerformObjectArgumentInitialization(Args[0], /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00007798 Best->FoundDecl, Method))
Sebastian Redladba46e2009-10-29 20:17:01 +00007799 return ExprError();
7800
Anders Carlssona68e51e2010-01-29 18:37:50 +00007801 // Convert the arguments.
John McCalldadc5752010-08-24 06:29:42 +00007802 ExprResult InputInit
Anders Carlssona68e51e2010-01-29 18:37:50 +00007803 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00007804 Context,
Anders Carlssona68e51e2010-01-29 18:37:50 +00007805 FnDecl->getParamDecl(0)),
7806 SourceLocation(),
7807 Owned(Args[1]));
7808 if (InputInit.isInvalid())
7809 return ExprError();
7810
7811 Args[1] = InputInit.takeAs<Expr>();
7812
Sebastian Redladba46e2009-10-29 20:17:01 +00007813 // Determine the result type
John McCall7decc9e2010-11-18 06:31:45 +00007814 QualType ResultTy = FnDecl->getResultType();
7815 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
7816 ResultTy = ResultTy.getNonLValueExprType(Context);
Sebastian Redladba46e2009-10-29 20:17:01 +00007817
7818 // Build the actual expression node.
John McCall7decc9e2010-11-18 06:31:45 +00007819 Expr *FnExpr = CreateFunctionRefExpr(*this, FnDecl, LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007820
John McCallb268a282010-08-23 23:25:46 +00007821 CXXOperatorCallExpr *TheCall =
7822 new (Context) CXXOperatorCallExpr(Context, OO_Subscript,
7823 FnExpr, Args, 2,
John McCall7decc9e2010-11-18 06:31:45 +00007824 ResultTy, VK, RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007825
John McCallb268a282010-08-23 23:25:46 +00007826 if (CheckCallReturnType(FnDecl->getResultType(), LLoc, TheCall,
Sebastian Redladba46e2009-10-29 20:17:01 +00007827 FnDecl))
7828 return ExprError();
7829
John McCallb268a282010-08-23 23:25:46 +00007830 return MaybeBindToTemporary(TheCall);
Sebastian Redladba46e2009-10-29 20:17:01 +00007831 } else {
7832 // We matched a built-in operator. Convert the arguments, then
7833 // break out so that we will build the appropriate built-in
7834 // operator node.
7835 if (PerformImplicitConversion(Args[0], Best->BuiltinTypes.ParamTypes[0],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007836 Best->Conversions[0], AA_Passing) ||
Sebastian Redladba46e2009-10-29 20:17:01 +00007837 PerformImplicitConversion(Args[1], Best->BuiltinTypes.ParamTypes[1],
Douglas Gregor7c3bbdf2009-12-16 03:45:30 +00007838 Best->Conversions[1], AA_Passing))
Sebastian Redladba46e2009-10-29 20:17:01 +00007839 return ExprError();
7840
7841 break;
7842 }
7843 }
7844
7845 case OR_No_Viable_Function: {
John McCall02374852010-01-07 02:04:15 +00007846 if (CandidateSet.empty())
7847 Diag(LLoc, diag::err_ovl_no_oper)
7848 << Args[0]->getType() << /*subscript*/ 0
7849 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
7850 else
7851 Diag(LLoc, diag::err_ovl_no_viable_subscript)
7852 << Args[0]->getType()
7853 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007854 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7855 "[]", LLoc);
John McCall02374852010-01-07 02:04:15 +00007856 return ExprError();
Sebastian Redladba46e2009-10-29 20:17:01 +00007857 }
7858
7859 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00007860 Diag(LLoc, diag::err_ovl_ambiguous_oper_binary)
7861 << "[]"
7862 << Args[0]->getType() << Args[1]->getType()
7863 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007864 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, 2,
7865 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007866 return ExprError();
7867
7868 case OR_Deleted:
7869 Diag(LLoc, diag::err_ovl_deleted_oper)
7870 << Best->Function->isDeleted() << "[]"
7871 << Args[0]->getSourceRange() << Args[1]->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007872 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, 2,
7873 "[]", LLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007874 return ExprError();
7875 }
7876
7877 // We matched a built-in operator; build it.
John McCallb268a282010-08-23 23:25:46 +00007878 return CreateBuiltinArraySubscriptExpr(Args[0], LLoc, Args[1], RLoc);
Sebastian Redladba46e2009-10-29 20:17:01 +00007879}
7880
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007881/// BuildCallToMemberFunction - Build a call to a member
7882/// function. MemExpr is the expression that refers to the member
7883/// function (and includes the object parameter), Args/NumArgs are the
7884/// arguments to the function call (not including the object
7885/// parameter). The caller needs to validate that the member
7886/// expression refers to a member function or an overloaded member
7887/// function.
John McCalldadc5752010-08-24 06:29:42 +00007888ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00007889Sema::BuildCallToMemberFunction(Scope *S, Expr *MemExprE,
7890 SourceLocation LParenLoc, Expr **Args,
Douglas Gregorce5aa332010-09-09 16:33:13 +00007891 unsigned NumArgs, SourceLocation RParenLoc) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007892 // Dig out the member expression. This holds both the object
7893 // argument and the member function we're referring to.
John McCall10eae182009-11-30 22:42:35 +00007894 Expr *NakedMemExpr = MemExprE->IgnoreParens();
7895
John McCall10eae182009-11-30 22:42:35 +00007896 MemberExpr *MemExpr;
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007897 CXXMethodDecl *Method = 0;
John McCall3a65ef42010-04-08 00:13:37 +00007898 DeclAccessPair FoundDecl = DeclAccessPair::make(0, AS_public);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007899 NestedNameSpecifier *Qualifier = 0;
John McCall10eae182009-11-30 22:42:35 +00007900 if (isa<MemberExpr>(NakedMemExpr)) {
7901 MemExpr = cast<MemberExpr>(NakedMemExpr);
John McCall10eae182009-11-30 22:42:35 +00007902 Method = cast<CXXMethodDecl>(MemExpr->getMemberDecl());
John McCall16df1e52010-03-30 21:47:33 +00007903 FoundDecl = MemExpr->getFoundDecl();
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007904 Qualifier = MemExpr->getQualifier();
John McCall10eae182009-11-30 22:42:35 +00007905 } else {
7906 UnresolvedMemberExpr *UnresExpr = cast<UnresolvedMemberExpr>(NakedMemExpr);
Douglas Gregorcc3f3252010-03-03 23:55:11 +00007907 Qualifier = UnresExpr->getQualifier();
7908
John McCall6e9f8f62009-12-03 04:06:58 +00007909 QualType ObjectType = UnresExpr->getBaseType();
John McCall10eae182009-11-30 22:42:35 +00007910
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007911 // Add overload candidates
John McCallbc077cf2010-02-08 23:07:23 +00007912 OverloadCandidateSet CandidateSet(UnresExpr->getMemberLoc());
Mike Stump11289f42009-09-09 15:08:12 +00007913
John McCall2d74de92009-12-01 22:10:20 +00007914 // FIXME: avoid copy.
7915 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
7916 if (UnresExpr->hasExplicitTemplateArgs()) {
7917 UnresExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
7918 TemplateArgs = &TemplateArgsBuffer;
7919 }
7920
John McCall10eae182009-11-30 22:42:35 +00007921 for (UnresolvedMemberExpr::decls_iterator I = UnresExpr->decls_begin(),
7922 E = UnresExpr->decls_end(); I != E; ++I) {
7923
John McCall6e9f8f62009-12-03 04:06:58 +00007924 NamedDecl *Func = *I;
7925 CXXRecordDecl *ActingDC = cast<CXXRecordDecl>(Func->getDeclContext());
7926 if (isa<UsingShadowDecl>(Func))
7927 Func = cast<UsingShadowDecl>(Func)->getTargetDecl();
7928
Francois Pichet64225792011-01-18 05:04:39 +00007929 // Microsoft supports direct constructor calls.
7930 if (getLangOptions().Microsoft && isa<CXXConstructorDecl>(Func)) {
7931 AddOverloadCandidate(cast<CXXConstructorDecl>(Func), I.getPair(), Args, NumArgs,
7932 CandidateSet);
7933 } else if ((Method = dyn_cast<CXXMethodDecl>(Func))) {
Douglas Gregord3319842009-10-24 04:59:53 +00007934 // If explicit template arguments were provided, we can't call a
7935 // non-template member function.
John McCall2d74de92009-12-01 22:10:20 +00007936 if (TemplateArgs)
Douglas Gregord3319842009-10-24 04:59:53 +00007937 continue;
7938
John McCalla0296f72010-03-19 07:35:19 +00007939 AddMethodCandidate(Method, I.getPair(), ActingDC, ObjectType,
John McCallb89836b2010-01-26 01:37:31 +00007940 Args, NumArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007941 CandidateSet, /*SuppressUserConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007942 } else {
John McCall10eae182009-11-30 22:42:35 +00007943 AddMethodTemplateCandidate(cast<FunctionTemplateDecl>(Func),
John McCalla0296f72010-03-19 07:35:19 +00007944 I.getPair(), ActingDC, TemplateArgs,
John McCall6e9f8f62009-12-03 04:06:58 +00007945 ObjectType, Args, NumArgs,
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007946 CandidateSet,
7947 /*SuppressUsedConversions=*/false);
John McCall6b51f282009-11-23 01:53:49 +00007948 }
Douglas Gregor5ed5ae42009-08-21 18:42:58 +00007949 }
Mike Stump11289f42009-09-09 15:08:12 +00007950
John McCall10eae182009-11-30 22:42:35 +00007951 DeclarationName DeclName = UnresExpr->getMemberName();
7952
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007953 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00007954 switch (CandidateSet.BestViableFunction(*this, UnresExpr->getLocStart(),
Nick Lewycky9331ed82010-11-20 01:29:55 +00007955 Best)) {
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007956 case OR_Success:
7957 Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00007958 FoundDecl = Best->FoundDecl;
John McCalla0296f72010-03-19 07:35:19 +00007959 CheckUnresolvedMemberAccess(UnresExpr, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00007960 DiagnoseUseOfDecl(Best->FoundDecl, UnresExpr->getNameLoc());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007961 break;
7962
7963 case OR_No_Viable_Function:
John McCall10eae182009-11-30 22:42:35 +00007964 Diag(UnresExpr->getMemberLoc(),
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007965 diag::err_ovl_no_viable_member_function_in_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007966 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007967 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007968 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007969 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007970
7971 case OR_Ambiguous:
John McCall10eae182009-11-30 22:42:35 +00007972 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_ambiguous_member_call)
Douglas Gregor97628d62009-08-21 00:16:32 +00007973 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007974 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007975 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007976 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00007977
7978 case OR_Deleted:
John McCall10eae182009-11-30 22:42:35 +00007979 Diag(UnresExpr->getMemberLoc(), diag::err_ovl_deleted_member_call)
Douglas Gregor171c45a2009-02-18 21:56:37 +00007980 << Best->Function->isDeleted()
Douglas Gregor97628d62009-08-21 00:16:32 +00007981 << DeclName << MemExprE->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00007982 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00007983 // FIXME: Leaking incoming expressions!
John McCall2d74de92009-12-01 22:10:20 +00007984 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007985 }
7986
John McCall16df1e52010-03-30 21:47:33 +00007987 MemExprE = FixOverloadedFunctionReference(MemExprE, FoundDecl, Method);
John McCall2d74de92009-12-01 22:10:20 +00007988
John McCall2d74de92009-12-01 22:10:20 +00007989 // If overload resolution picked a static member, build a
7990 // non-member call based on that function.
7991 if (Method->isStatic()) {
7992 return BuildResolvedCallExpr(MemExprE, Method, LParenLoc,
7993 Args, NumArgs, RParenLoc);
7994 }
7995
John McCall10eae182009-11-30 22:42:35 +00007996 MemExpr = cast<MemberExpr>(MemExprE->IgnoreParens());
Douglas Gregor97fd6e22008-12-22 05:46:06 +00007997 }
7998
John McCall7decc9e2010-11-18 06:31:45 +00007999 QualType ResultType = Method->getResultType();
8000 ExprValueKind VK = Expr::getValueKindForType(ResultType);
8001 ResultType = ResultType.getNonLValueExprType(Context);
8002
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008003 assert(Method && "Member call to something that isn't a method?");
John McCallb268a282010-08-23 23:25:46 +00008004 CXXMemberCallExpr *TheCall =
8005 new (Context) CXXMemberCallExpr(Context, MemExprE, Args, NumArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008006 ResultType, VK, RParenLoc);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008007
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008008 // Check for a valid return type.
8009 if (CheckCallReturnType(Method->getResultType(), MemExpr->getMemberLoc(),
John McCallb268a282010-08-23 23:25:46 +00008010 TheCall, Method))
John McCall2d74de92009-12-01 22:10:20 +00008011 return ExprError();
Anders Carlssonc4859ba2009-10-10 00:06:20 +00008012
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008013 // Convert the object argument (for a non-static member function call).
John McCall16df1e52010-03-30 21:47:33 +00008014 // We only need to do this if there was actually an overload; otherwise
8015 // it was done at lookup.
John McCall2d74de92009-12-01 22:10:20 +00008016 Expr *ObjectArg = MemExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00008017 if (!Method->isStatic() &&
John McCall16df1e52010-03-30 21:47:33 +00008018 PerformObjectArgumentInitialization(ObjectArg, Qualifier,
8019 FoundDecl, Method))
John McCall2d74de92009-12-01 22:10:20 +00008020 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008021 MemExpr->setBase(ObjectArg);
8022
8023 // Convert the rest of the arguments
Chandler Carruth8e543b32010-12-12 08:17:55 +00008024 const FunctionProtoType *Proto =
8025 Method->getType()->getAs<FunctionProtoType>();
John McCallb268a282010-08-23 23:25:46 +00008026 if (ConvertArgumentsForCall(TheCall, MemExpr, Method, Proto, Args, NumArgs,
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008027 RParenLoc))
John McCall2d74de92009-12-01 22:10:20 +00008028 return ExprError();
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008029
John McCallb268a282010-08-23 23:25:46 +00008030 if (CheckFunctionCall(Method, TheCall))
John McCall2d74de92009-12-01 22:10:20 +00008031 return ExprError();
Anders Carlsson8c84c202009-08-16 03:42:12 +00008032
John McCallb268a282010-08-23 23:25:46 +00008033 return MaybeBindToTemporary(TheCall);
Douglas Gregor97fd6e22008-12-22 05:46:06 +00008034}
8035
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008036/// BuildCallToObjectOfClassType - Build a call to an object of class
8037/// type (C++ [over.call.object]), which can end up invoking an
8038/// overloaded function call operator (@c operator()) or performing a
8039/// user-defined conversion on the object argument.
John McCallfaf5fb42010-08-26 23:41:50 +00008040ExprResult
Mike Stump11289f42009-09-09 15:08:12 +00008041Sema::BuildCallToObjectOfClassType(Scope *S, Expr *Object,
Douglas Gregorb0846b02008-12-06 00:22:45 +00008042 SourceLocation LParenLoc,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008043 Expr **Args, unsigned NumArgs,
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008044 SourceLocation RParenLoc) {
John McCalle26a8722010-12-04 08:14:53 +00008045 if (Object->getObjectKind() == OK_ObjCProperty)
8046 ConvertPropertyForRValue(Object);
8047
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008048 assert(Object->getType()->isRecordType() && "Requires object type argument");
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008049 const RecordType *Record = Object->getType()->getAs<RecordType>();
Mike Stump11289f42009-09-09 15:08:12 +00008050
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008051 // C++ [over.call.object]p1:
8052 // If the primary-expression E in the function call syntax
Eli Friedman44b83ee2009-08-05 19:21:58 +00008053 // evaluates to a class object of type "cv T", then the set of
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008054 // candidate functions includes at least the function call
8055 // operators of T. The function call operators of T are obtained by
8056 // ordinary lookup of the name operator() in the context of
8057 // (E).operator().
John McCallbc077cf2010-02-08 23:07:23 +00008058 OverloadCandidateSet CandidateSet(LParenLoc);
Douglas Gregor91f84212008-12-11 16:49:14 +00008059 DeclarationName OpName = Context.DeclarationNames.getCXXOperatorName(OO_Call);
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008060
8061 if (RequireCompleteType(LParenLoc, Object->getType(),
Douglas Gregor89336232010-03-29 23:34:08 +00008062 PDiag(diag::err_incomplete_object_call)
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008063 << Object->getSourceRange()))
8064 return true;
8065
John McCall27b18f82009-11-17 02:14:36 +00008066 LookupResult R(*this, OpName, LParenLoc, LookupOrdinaryName);
8067 LookupQualifiedName(R, Record->getDecl());
8068 R.suppressDiagnostics();
8069
Douglas Gregorc473cbb2009-11-15 07:48:03 +00008070 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
Douglas Gregor358e7742009-11-07 17:23:56 +00008071 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008072 AddMethodCandidate(Oper.getPair(), Object->getType(),
John McCallb89836b2010-01-26 01:37:31 +00008073 Args, NumArgs, CandidateSet,
John McCallf0f1cf02009-11-17 07:50:12 +00008074 /*SuppressUserConversions=*/ false);
Douglas Gregor358e7742009-11-07 17:23:56 +00008075 }
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008076
Douglas Gregorab7897a2008-11-19 22:57:39 +00008077 // C++ [over.call.object]p2:
8078 // In addition, for each conversion function declared in T of the
8079 // form
8080 //
8081 // operator conversion-type-id () cv-qualifier;
8082 //
8083 // where cv-qualifier is the same cv-qualification as, or a
8084 // greater cv-qualification than, cv, and where conversion-type-id
Douglas Gregorf49fdf82008-11-20 13:33:37 +00008085 // denotes the type "pointer to function of (P1,...,Pn) returning
8086 // R", or the type "reference to pointer to function of
8087 // (P1,...,Pn) returning R", or the type "reference to function
8088 // of (P1,...,Pn) returning R", a surrogate call function [...]
Douglas Gregorab7897a2008-11-19 22:57:39 +00008089 // is also considered as a candidate function. Similarly,
8090 // surrogate call functions are added to the set of candidate
8091 // functions for each conversion function declared in an
8092 // accessible base class provided the function is not hidden
8093 // within T by another intervening declaration.
John McCallad371252010-01-20 00:46:10 +00008094 const UnresolvedSetImpl *Conversions
Douglas Gregor21591822010-01-11 19:36:35 +00008095 = cast<CXXRecordDecl>(Record->getDecl())->getVisibleConversionFunctions();
John McCallad371252010-01-20 00:46:10 +00008096 for (UnresolvedSetImpl::iterator I = Conversions->begin(),
John McCalld14a8642009-11-21 08:51:07 +00008097 E = Conversions->end(); I != E; ++I) {
John McCall6e9f8f62009-12-03 04:06:58 +00008098 NamedDecl *D = *I;
8099 CXXRecordDecl *ActingContext = cast<CXXRecordDecl>(D->getDeclContext());
8100 if (isa<UsingShadowDecl>(D))
8101 D = cast<UsingShadowDecl>(D)->getTargetDecl();
8102
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008103 // Skip over templated conversion functions; they aren't
8104 // surrogates.
John McCall6e9f8f62009-12-03 04:06:58 +00008105 if (isa<FunctionTemplateDecl>(D))
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008106 continue;
Douglas Gregor05155d82009-08-21 23:19:43 +00008107
John McCall6e9f8f62009-12-03 04:06:58 +00008108 CXXConversionDecl *Conv = cast<CXXConversionDecl>(D);
John McCalld14a8642009-11-21 08:51:07 +00008109
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008110 // Strip the reference type (if any) and then the pointer type (if
8111 // any) to get down to what might be a function type.
8112 QualType ConvType = Conv->getConversionType().getNonReferenceType();
8113 if (const PointerType *ConvPtrType = ConvType->getAs<PointerType>())
8114 ConvType = ConvPtrType->getPointeeType();
Douglas Gregorab7897a2008-11-19 22:57:39 +00008115
Douglas Gregor74ba25c2009-10-21 06:18:39 +00008116 if (const FunctionProtoType *Proto = ConvType->getAs<FunctionProtoType>())
John McCalla0296f72010-03-19 07:35:19 +00008117 AddSurrogateCandidate(Conv, I.getPair(), ActingContext, Proto,
John McCall6e9f8f62009-12-03 04:06:58 +00008118 Object->getType(), Args, NumArgs,
8119 CandidateSet);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008120 }
Mike Stump11289f42009-09-09 15:08:12 +00008121
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008122 // Perform overload resolution.
8123 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008124 switch (CandidateSet.BestViableFunction(*this, Object->getLocStart(),
8125 Best)) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008126 case OR_Success:
Douglas Gregorab7897a2008-11-19 22:57:39 +00008127 // Overload resolution succeeded; we'll build the appropriate call
8128 // below.
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008129 break;
8130
8131 case OR_No_Viable_Function:
John McCall02374852010-01-07 02:04:15 +00008132 if (CandidateSet.empty())
8133 Diag(Object->getSourceRange().getBegin(), diag::err_ovl_no_oper)
8134 << Object->getType() << /*call*/ 1
8135 << Object->getSourceRange();
8136 else
8137 Diag(Object->getSourceRange().getBegin(),
8138 diag::err_ovl_no_viable_object_call)
8139 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008140 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008141 break;
8142
8143 case OR_Ambiguous:
8144 Diag(Object->getSourceRange().getBegin(),
8145 diag::err_ovl_ambiguous_object_call)
Chris Lattner1e5665e2008-11-24 06:25:27 +00008146 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008147 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, Args, NumArgs);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008148 break;
Douglas Gregor171c45a2009-02-18 21:56:37 +00008149
8150 case OR_Deleted:
8151 Diag(Object->getSourceRange().getBegin(),
8152 diag::err_ovl_deleted_object_call)
8153 << Best->Function->isDeleted()
8154 << Object->getType() << Object->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008155 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, Args, NumArgs);
Douglas Gregor171c45a2009-02-18 21:56:37 +00008156 break;
Mike Stump11289f42009-09-09 15:08:12 +00008157 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008158
Douglas Gregorb412e172010-07-25 18:17:45 +00008159 if (Best == CandidateSet.end())
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008160 return true;
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008161
Douglas Gregorab7897a2008-11-19 22:57:39 +00008162 if (Best->Function == 0) {
8163 // Since there is no function declaration, this is one of the
8164 // surrogate candidates. Dig out the conversion function.
Mike Stump11289f42009-09-09 15:08:12 +00008165 CXXConversionDecl *Conv
Douglas Gregorab7897a2008-11-19 22:57:39 +00008166 = cast<CXXConversionDecl>(
8167 Best->Conversions[0].UserDefined.ConversionFunction);
8168
John McCalla0296f72010-03-19 07:35:19 +00008169 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008170 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008171
Douglas Gregorab7897a2008-11-19 22:57:39 +00008172 // We selected one of the surrogate functions that converts the
8173 // object parameter to a function pointer. Perform the conversion
8174 // on the object argument, then let ActOnCallExpr finish the job.
Fariborz Jahanian774cf792009-09-28 18:35:46 +00008175
8176 // Create an implicit member expr to refer to the conversion operator.
Fariborz Jahanian78cfcb52009-09-28 23:23:40 +00008177 // and then call it.
Douglas Gregor668443e2011-01-20 00:18:04 +00008178 ExprResult Call = BuildCXXMemberCallExpr(Object, Best->FoundDecl, Conv);
8179 if (Call.isInvalid())
8180 return ExprError();
8181
8182 return ActOnCallExpr(S, Call.get(), LParenLoc, MultiExprArg(Args, NumArgs),
Douglas Gregorce5aa332010-09-09 16:33:13 +00008183 RParenLoc);
Douglas Gregorab7897a2008-11-19 22:57:39 +00008184 }
8185
John McCalla0296f72010-03-19 07:35:19 +00008186 CheckMemberOperatorAccess(LParenLoc, Object, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008187 DiagnoseUseOfDecl(Best->FoundDecl, LParenLoc);
John McCall49ec2e62010-01-28 01:54:34 +00008188
Douglas Gregorab7897a2008-11-19 22:57:39 +00008189 // We found an overloaded operator(). Build a CXXOperatorCallExpr
8190 // that calls this method, using Object for the implicit object
8191 // parameter and passing along the remaining arguments.
8192 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
Chandler Carruth8e543b32010-12-12 08:17:55 +00008193 const FunctionProtoType *Proto =
8194 Method->getType()->getAs<FunctionProtoType>();
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008195
8196 unsigned NumArgsInProto = Proto->getNumArgs();
8197 unsigned NumArgsToCheck = NumArgs;
8198
8199 // Build the full argument list for the method call (the
8200 // implicit object parameter is placed at the beginning of the
8201 // list).
8202 Expr **MethodArgs;
8203 if (NumArgs < NumArgsInProto) {
8204 NumArgsToCheck = NumArgsInProto;
8205 MethodArgs = new Expr*[NumArgsInProto + 1];
8206 } else {
8207 MethodArgs = new Expr*[NumArgs + 1];
8208 }
8209 MethodArgs[0] = Object;
8210 for (unsigned ArgIdx = 0; ArgIdx < NumArgs; ++ArgIdx)
8211 MethodArgs[ArgIdx + 1] = Args[ArgIdx];
Mike Stump11289f42009-09-09 15:08:12 +00008212
John McCall7decc9e2010-11-18 06:31:45 +00008213 Expr *NewFn = CreateFunctionRefExpr(*this, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008214
8215 // Once we've built TheCall, all of the expressions are properly
8216 // owned.
John McCall7decc9e2010-11-18 06:31:45 +00008217 QualType ResultTy = Method->getResultType();
8218 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8219 ResultTy = ResultTy.getNonLValueExprType(Context);
8220
John McCallb268a282010-08-23 23:25:46 +00008221 CXXOperatorCallExpr *TheCall =
8222 new (Context) CXXOperatorCallExpr(Context, OO_Call, NewFn,
8223 MethodArgs, NumArgs + 1,
John McCall7decc9e2010-11-18 06:31:45 +00008224 ResultTy, VK, RParenLoc);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008225 delete [] MethodArgs;
8226
John McCallb268a282010-08-23 23:25:46 +00008227 if (CheckCallReturnType(Method->getResultType(), LParenLoc, TheCall,
Anders Carlsson3d5829c2009-10-13 21:49:31 +00008228 Method))
8229 return true;
8230
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008231 // We may have default arguments. If so, we need to allocate more
8232 // slots in the call for them.
8233 if (NumArgs < NumArgsInProto)
Ted Kremenek5a201952009-02-07 01:47:29 +00008234 TheCall->setNumArgs(Context, NumArgsInProto + 1);
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008235 else if (NumArgs > NumArgsInProto)
8236 NumArgsToCheck = NumArgsInProto;
8237
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008238 bool IsError = false;
8239
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008240 // Initialize the implicit object parameter.
Douglas Gregorcc3f3252010-03-03 23:55:11 +00008241 IsError |= PerformObjectArgumentInitialization(Object, /*Qualifier=*/0,
John McCall16df1e52010-03-30 21:47:33 +00008242 Best->FoundDecl, Method);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008243 TheCall->setArg(0, Object);
8244
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008245
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008246 // Check the argument types.
8247 for (unsigned i = 0; i != NumArgsToCheck; i++) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008248 Expr *Arg;
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008249 if (i < NumArgs) {
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008250 Arg = Args[i];
Mike Stump11289f42009-09-09 15:08:12 +00008251
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008252 // Pass the argument.
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008253
John McCalldadc5752010-08-24 06:29:42 +00008254 ExprResult InputInit
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008255 = PerformCopyInitialization(InitializedEntity::InitializeParameter(
Fariborz Jahanian8fb87ae2010-09-24 17:30:16 +00008256 Context,
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008257 Method->getParamDecl(i)),
John McCallb268a282010-08-23 23:25:46 +00008258 SourceLocation(), Arg);
Anders Carlsson7c5fe482010-01-29 18:43:53 +00008259
8260 IsError |= InputInit.isInvalid();
8261 Arg = InputInit.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008262 } else {
John McCalldadc5752010-08-24 06:29:42 +00008263 ExprResult DefArg
Douglas Gregor1bc688d2009-11-09 19:27:57 +00008264 = BuildCXXDefaultArgExpr(LParenLoc, Method, Method->getParamDecl(i));
8265 if (DefArg.isInvalid()) {
8266 IsError = true;
8267 break;
8268 }
8269
8270 Arg = DefArg.takeAs<Expr>();
Douglas Gregor02a0acd2009-01-13 05:10:00 +00008271 }
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008272
8273 TheCall->setArg(i + 1, Arg);
8274 }
8275
8276 // If this is a variadic call, handle args passed through "...".
8277 if (Proto->isVariadic()) {
8278 // Promote the arguments (C99 6.5.2.2p7).
8279 for (unsigned i = NumArgsInProto; i != NumArgs; i++) {
8280 Expr *Arg = Args[i];
Chris Lattnerbb53efb2010-05-16 04:01:30 +00008281 IsError |= DefaultVariadicArgumentPromotion(Arg, VariadicMethod, 0);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008282 TheCall->setArg(i + 1, Arg);
8283 }
8284 }
8285
Chris Lattnera8a7d0f2009-04-12 08:11:20 +00008286 if (IsError) return true;
8287
John McCallb268a282010-08-23 23:25:46 +00008288 if (CheckFunctionCall(Method, TheCall))
Anders Carlssonbc4c1072009-08-16 01:56:34 +00008289 return true;
8290
John McCalle172be52010-08-24 06:09:16 +00008291 return MaybeBindToTemporary(TheCall);
Douglas Gregor91cea0a2008-11-19 21:05:33 +00008292}
8293
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008294/// BuildOverloadedArrowExpr - Build a call to an overloaded @c operator->
Mike Stump11289f42009-09-09 15:08:12 +00008295/// (if one exists), where @c Base is an expression of class type and
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008296/// @c Member is the name of the member we're trying to find.
John McCalldadc5752010-08-24 06:29:42 +00008297ExprResult
John McCallb268a282010-08-23 23:25:46 +00008298Sema::BuildOverloadedArrowExpr(Scope *S, Expr *Base, SourceLocation OpLoc) {
Chandler Carruth8e543b32010-12-12 08:17:55 +00008299 assert(Base->getType()->isRecordType() &&
8300 "left-hand side must have class type");
Mike Stump11289f42009-09-09 15:08:12 +00008301
John McCalle26a8722010-12-04 08:14:53 +00008302 if (Base->getObjectKind() == OK_ObjCProperty)
8303 ConvertPropertyForRValue(Base);
8304
John McCallbc077cf2010-02-08 23:07:23 +00008305 SourceLocation Loc = Base->getExprLoc();
8306
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008307 // C++ [over.ref]p1:
8308 //
8309 // [...] An expression x->m is interpreted as (x.operator->())->m
8310 // for a class object x of type T if T::operator->() exists and if
8311 // the operator is selected as the best match function by the
8312 // overload resolution mechanism (13.3).
Chandler Carruth8e543b32010-12-12 08:17:55 +00008313 DeclarationName OpName =
8314 Context.DeclarationNames.getCXXOperatorName(OO_Arrow);
John McCallbc077cf2010-02-08 23:07:23 +00008315 OverloadCandidateSet CandidateSet(Loc);
Ted Kremenekc23c7e62009-07-29 21:53:49 +00008316 const RecordType *BaseRecord = Base->getType()->getAs<RecordType>();
Douglas Gregord8061562009-08-06 03:17:00 +00008317
John McCallbc077cf2010-02-08 23:07:23 +00008318 if (RequireCompleteType(Loc, Base->getType(),
Eli Friedman132e70b2009-11-18 01:28:03 +00008319 PDiag(diag::err_typecheck_incomplete_tag)
8320 << Base->getSourceRange()))
8321 return ExprError();
8322
John McCall27b18f82009-11-17 02:14:36 +00008323 LookupResult R(*this, OpName, OpLoc, LookupOrdinaryName);
8324 LookupQualifiedName(R, BaseRecord->getDecl());
8325 R.suppressDiagnostics();
Anders Carlsson78b54932009-09-10 23:18:36 +00008326
8327 for (LookupResult::iterator Oper = R.begin(), OperEnd = R.end();
John McCall6e9f8f62009-12-03 04:06:58 +00008328 Oper != OperEnd; ++Oper) {
John McCalla0296f72010-03-19 07:35:19 +00008329 AddMethodCandidate(Oper.getPair(), Base->getType(), 0, 0, CandidateSet,
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008330 /*SuppressUserConversions=*/false);
John McCall6e9f8f62009-12-03 04:06:58 +00008331 }
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008332
8333 // Perform overload resolution.
8334 OverloadCandidateSet::iterator Best;
John McCall5c32be02010-08-24 20:38:10 +00008335 switch (CandidateSet.BestViableFunction(*this, OpLoc, Best)) {
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008336 case OR_Success:
8337 // Overload resolution succeeded; we'll build the call below.
8338 break;
8339
8340 case OR_No_Viable_Function:
8341 if (CandidateSet.empty())
8342 Diag(OpLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregord8061562009-08-06 03:17:00 +00008343 << Base->getType() << Base->getSourceRange();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008344 else
8345 Diag(OpLoc, diag::err_ovl_no_viable_oper)
Douglas Gregord8061562009-08-06 03:17:00 +00008346 << "operator->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008347 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008348 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008349
8350 case OR_Ambiguous:
Douglas Gregor052caec2010-11-13 20:06:38 +00008351 Diag(OpLoc, diag::err_ovl_ambiguous_oper_unary)
8352 << "->" << Base->getType() << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008353 CandidateSet.NoteCandidates(*this, OCD_ViableCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008354 return ExprError();
Douglas Gregor171c45a2009-02-18 21:56:37 +00008355
8356 case OR_Deleted:
8357 Diag(OpLoc, diag::err_ovl_deleted_oper)
8358 << Best->Function->isDeleted()
Anders Carlsson78b54932009-09-10 23:18:36 +00008359 << "->" << Base->getSourceRange();
John McCall5c32be02010-08-24 20:38:10 +00008360 CandidateSet.NoteCandidates(*this, OCD_AllCandidates, &Base, 1);
Douglas Gregord8061562009-08-06 03:17:00 +00008361 return ExprError();
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008362 }
8363
John McCalla0296f72010-03-19 07:35:19 +00008364 CheckMemberOperatorAccess(OpLoc, Base, 0, Best->FoundDecl);
John McCall4fa0d5f2010-05-06 18:15:07 +00008365 DiagnoseUseOfDecl(Best->FoundDecl, OpLoc);
John McCalla0296f72010-03-19 07:35:19 +00008366
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008367 // Convert the object parameter.
8368 CXXMethodDecl *Method = cast<CXXMethodDecl>(Best->Function);
John McCall16df1e52010-03-30 21:47:33 +00008369 if (PerformObjectArgumentInitialization(Base, /*Qualifier=*/0,
8370 Best->FoundDecl, Method))
Douglas Gregord8061562009-08-06 03:17:00 +00008371 return ExprError();
Douglas Gregor9ecea262008-11-21 03:04:22 +00008372
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008373 // Build the operator call.
John McCall7decc9e2010-11-18 06:31:45 +00008374 Expr *FnExpr = CreateFunctionRefExpr(*this, Method);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008375
John McCall7decc9e2010-11-18 06:31:45 +00008376 QualType ResultTy = Method->getResultType();
8377 ExprValueKind VK = Expr::getValueKindForType(ResultTy);
8378 ResultTy = ResultTy.getNonLValueExprType(Context);
John McCallb268a282010-08-23 23:25:46 +00008379 CXXOperatorCallExpr *TheCall =
8380 new (Context) CXXOperatorCallExpr(Context, OO_Arrow, FnExpr,
John McCall7decc9e2010-11-18 06:31:45 +00008381 &Base, 1, ResultTy, VK, OpLoc);
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008382
John McCallb268a282010-08-23 23:25:46 +00008383 if (CheckCallReturnType(Method->getResultType(), OpLoc, TheCall,
Anders Carlssone4f4b5e2009-10-13 22:43:21 +00008384 Method))
8385 return ExprError();
John McCallb268a282010-08-23 23:25:46 +00008386 return Owned(TheCall);
Douglas Gregore0e79bd2008-11-20 16:27:02 +00008387}
8388
Douglas Gregorcd695e52008-11-10 20:40:00 +00008389/// FixOverloadedFunctionReference - E is an expression that refers to
8390/// a C++ overloaded function (possibly with some parentheses and
8391/// perhaps a '&' around it). We have resolved the overloaded function
8392/// to the function declaration Fn, so patch up the expression E to
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008393/// refer (possibly indirectly) to Fn. Returns the new expr.
John McCalla8ae2222010-04-06 21:38:20 +00008394Expr *Sema::FixOverloadedFunctionReference(Expr *E, DeclAccessPair Found,
John McCall16df1e52010-03-30 21:47:33 +00008395 FunctionDecl *Fn) {
Douglas Gregorcd695e52008-11-10 20:40:00 +00008396 if (ParenExpr *PE = dyn_cast<ParenExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008397 Expr *SubExpr = FixOverloadedFunctionReference(PE->getSubExpr(),
8398 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008399 if (SubExpr == PE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008400 return PE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008401
8402 return new (Context) ParenExpr(PE->getLParen(), PE->getRParen(), SubExpr);
8403 }
8404
8405 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall16df1e52010-03-30 21:47:33 +00008406 Expr *SubExpr = FixOverloadedFunctionReference(ICE->getSubExpr(),
8407 Found, Fn);
Douglas Gregor091f0422009-10-23 22:18:25 +00008408 assert(Context.hasSameType(ICE->getSubExpr()->getType(),
Douglas Gregor51c538b2009-11-20 19:42:02 +00008409 SubExpr->getType()) &&
Douglas Gregor091f0422009-10-23 22:18:25 +00008410 "Implicit cast type cannot be determined from overload");
John McCallcf142162010-08-07 06:22:56 +00008411 assert(ICE->path_empty() && "fixing up hierarchy conversion?");
Douglas Gregor51c538b2009-11-20 19:42:02 +00008412 if (SubExpr == ICE->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008413 return ICE;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008414
John McCallcf142162010-08-07 06:22:56 +00008415 return ImplicitCastExpr::Create(Context, ICE->getType(),
8416 ICE->getCastKind(),
8417 SubExpr, 0,
John McCall2536c6d2010-08-25 10:28:54 +00008418 ICE->getValueKind());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008419 }
8420
8421 if (UnaryOperator *UnOp = dyn_cast<UnaryOperator>(E)) {
John McCalle3027922010-08-25 11:45:40 +00008422 assert(UnOp->getOpcode() == UO_AddrOf &&
Douglas Gregorcd695e52008-11-10 20:40:00 +00008423 "Can only take the address of an overloaded function");
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008424 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Fn)) {
8425 if (Method->isStatic()) {
8426 // Do nothing: static member functions aren't any different
8427 // from non-member functions.
John McCalld14a8642009-11-21 08:51:07 +00008428 } else {
John McCalle66edc12009-11-24 19:00:30 +00008429 // Fix the sub expression, which really has to be an
8430 // UnresolvedLookupExpr holding an overloaded member function
8431 // or template.
John McCall16df1e52010-03-30 21:47:33 +00008432 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8433 Found, Fn);
John McCalld14a8642009-11-21 08:51:07 +00008434 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008435 return UnOp;
Douglas Gregor51c538b2009-11-20 19:42:02 +00008436
John McCalld14a8642009-11-21 08:51:07 +00008437 assert(isa<DeclRefExpr>(SubExpr)
8438 && "fixed to something other than a decl ref");
8439 assert(cast<DeclRefExpr>(SubExpr)->getQualifier()
8440 && "fixed to a member ref with no nested name qualifier");
8441
8442 // We have taken the address of a pointer to member
8443 // function. Perform the computation here so that we get the
8444 // appropriate pointer to member type.
8445 QualType ClassType
8446 = Context.getTypeDeclType(cast<RecordDecl>(Method->getDeclContext()));
8447 QualType MemPtrType
8448 = Context.getMemberPointerType(Fn->getType(), ClassType.getTypePtr());
8449
John McCall7decc9e2010-11-18 06:31:45 +00008450 return new (Context) UnaryOperator(SubExpr, UO_AddrOf, MemPtrType,
8451 VK_RValue, OK_Ordinary,
8452 UnOp->getOperatorLoc());
Douglas Gregor6f233ef2009-02-11 01:18:59 +00008453 }
8454 }
John McCall16df1e52010-03-30 21:47:33 +00008455 Expr *SubExpr = FixOverloadedFunctionReference(UnOp->getSubExpr(),
8456 Found, Fn);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008457 if (SubExpr == UnOp->getSubExpr())
John McCallc3007a22010-10-26 07:05:15 +00008458 return UnOp;
Anders Carlssonfcb4ab42009-10-21 17:16:23 +00008459
John McCalle3027922010-08-25 11:45:40 +00008460 return new (Context) UnaryOperator(SubExpr, UO_AddrOf,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008461 Context.getPointerType(SubExpr->getType()),
John McCall7decc9e2010-11-18 06:31:45 +00008462 VK_RValue, OK_Ordinary,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008463 UnOp->getOperatorLoc());
Douglas Gregor51c538b2009-11-20 19:42:02 +00008464 }
John McCalld14a8642009-11-21 08:51:07 +00008465
8466 if (UnresolvedLookupExpr *ULE = dyn_cast<UnresolvedLookupExpr>(E)) {
John McCall2d74de92009-12-01 22:10:20 +00008467 // FIXME: avoid copy.
8468 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
John McCalle66edc12009-11-24 19:00:30 +00008469 if (ULE->hasExplicitTemplateArgs()) {
John McCall2d74de92009-12-01 22:10:20 +00008470 ULE->copyTemplateArgumentsInto(TemplateArgsBuffer);
8471 TemplateArgs = &TemplateArgsBuffer;
John McCalle66edc12009-11-24 19:00:30 +00008472 }
8473
John McCalld14a8642009-11-21 08:51:07 +00008474 return DeclRefExpr::Create(Context,
8475 ULE->getQualifier(),
8476 ULE->getQualifierRange(),
8477 Fn,
8478 ULE->getNameLoc(),
John McCall2d74de92009-12-01 22:10:20 +00008479 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008480 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008481 TemplateArgs);
John McCalld14a8642009-11-21 08:51:07 +00008482 }
8483
John McCall10eae182009-11-30 22:42:35 +00008484 if (UnresolvedMemberExpr *MemExpr = dyn_cast<UnresolvedMemberExpr>(E)) {
John McCall6b51f282009-11-23 01:53:49 +00008485 // FIXME: avoid copy.
John McCall2d74de92009-12-01 22:10:20 +00008486 TemplateArgumentListInfo TemplateArgsBuffer, *TemplateArgs = 0;
8487 if (MemExpr->hasExplicitTemplateArgs()) {
8488 MemExpr->copyTemplateArgumentsInto(TemplateArgsBuffer);
8489 TemplateArgs = &TemplateArgsBuffer;
8490 }
John McCall6b51f282009-11-23 01:53:49 +00008491
John McCall2d74de92009-12-01 22:10:20 +00008492 Expr *Base;
8493
John McCall7decc9e2010-11-18 06:31:45 +00008494 // If we're filling in a static method where we used to have an
8495 // implicit member access, rewrite to a simple decl ref.
John McCall2d74de92009-12-01 22:10:20 +00008496 if (MemExpr->isImplicitAccess()) {
8497 if (cast<CXXMethodDecl>(Fn)->isStatic()) {
8498 return DeclRefExpr::Create(Context,
8499 MemExpr->getQualifier(),
8500 MemExpr->getQualifierRange(),
8501 Fn,
8502 MemExpr->getMemberLoc(),
8503 Fn->getType(),
John McCall7decc9e2010-11-18 06:31:45 +00008504 VK_LValue,
John McCall2d74de92009-12-01 22:10:20 +00008505 TemplateArgs);
Douglas Gregorb15af892010-01-07 23:12:05 +00008506 } else {
8507 SourceLocation Loc = MemExpr->getMemberLoc();
8508 if (MemExpr->getQualifier())
8509 Loc = MemExpr->getQualifierRange().getBegin();
8510 Base = new (Context) CXXThisExpr(Loc,
8511 MemExpr->getBaseType(),
8512 /*isImplicit=*/true);
8513 }
John McCall2d74de92009-12-01 22:10:20 +00008514 } else
John McCallc3007a22010-10-26 07:05:15 +00008515 Base = MemExpr->getBase();
John McCall2d74de92009-12-01 22:10:20 +00008516
8517 return MemberExpr::Create(Context, Base,
Douglas Gregor51c538b2009-11-20 19:42:02 +00008518 MemExpr->isArrow(),
8519 MemExpr->getQualifier(),
8520 MemExpr->getQualifierRange(),
8521 Fn,
John McCall16df1e52010-03-30 21:47:33 +00008522 Found,
Abramo Bagnarad6d2f182010-08-11 22:01:17 +00008523 MemExpr->getMemberNameInfo(),
John McCall2d74de92009-12-01 22:10:20 +00008524 TemplateArgs,
John McCall7decc9e2010-11-18 06:31:45 +00008525 Fn->getType(),
8526 cast<CXXMethodDecl>(Fn)->isStatic()
8527 ? VK_LValue : VK_RValue,
8528 OK_Ordinary);
Douglas Gregor51c538b2009-11-20 19:42:02 +00008529 }
8530
John McCallc3007a22010-10-26 07:05:15 +00008531 llvm_unreachable("Invalid reference to overloaded function");
8532 return E;
Douglas Gregorcd695e52008-11-10 20:40:00 +00008533}
8534
John McCalldadc5752010-08-24 06:29:42 +00008535ExprResult Sema::FixOverloadedFunctionReference(ExprResult E,
8536 DeclAccessPair Found,
8537 FunctionDecl *Fn) {
John McCall16df1e52010-03-30 21:47:33 +00008538 return Owned(FixOverloadedFunctionReference((Expr *)E.get(), Found, Fn));
Douglas Gregor3e1e5272009-12-09 23:02:17 +00008539}
8540
Douglas Gregor5251f1b2008-10-21 16:13:35 +00008541} // end namespace clang